Edit D:\AVA\AVAStandard\AVA.ResourcesPlatform.WebUI\CSS\zh-CN\NewtonTheme\assets\vendor.js
/*! * Modernizr v2.8.3 * www.modernizr.com * * Copyright (c) Faruk Ates, Paul Irish, Alex Sexton * Available under the BSD and MIT licenses: www.modernizr.com/license/ */ /* * Modernizr tests which native CSS3 and HTML5 features are available in * the current UA and makes the results available to you in two ways: * as properties on a global Modernizr object, and as classes on the * <html> element. This information allows you to progressively enhance * your pages with a granular level of control over the experience. * * Modernizr has an optional (not included) conditional resource loader * called Modernizr.load(), based on Yepnope.js (yepnopejs.com). * To get a build that includes Modernizr.load(), as well as choosing * which tests to include, go to www.modernizr.com/download/ * * Authors Faruk Ates, Paul Irish, Alex Sexton * Contributors Ryan Seddon, Ben Alman */ window.Modernizr = (function( window, document, undefined ) { var version = '2.8.3', Modernizr = {}, /*>>cssclasses*/ // option for enabling the HTML classes to be added enableClasses = true, /*>>cssclasses*/ docElement = document.documentElement, /** * Create our "modernizr" element that we do most feature tests on. */ mod = 'modernizr', modElem = document.createElement(mod), mStyle = modElem.style, /** * Create the input element for various Web Forms feature tests. */ inputElem /*>>inputelem*/ = document.createElement('input') /*>>inputelem*/ , /*>>smile*/ smile = ':)', /*>>smile*/ toString = {}.toString, // TODO :: make the prefixes more granular /*>>prefixes*/ // List of property values to set for css tests. See ticket #21 prefixes = ' -webkit- -moz- -o- -ms- '.split(' '), /*>>prefixes*/ /*>>domprefixes*/ // Following spec is to expose vendor-specific style properties as: // elem.style.WebkitBorderRadius // and the following would be incorrect: // elem.style.webkitBorderRadius // Webkit ghosts their properties in lowercase but Opera & Moz do not. // Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+ // erik.eae.net/archives/2008/03/10/21.48.10/ // More here: github.com/Modernizr/Modernizr/issues/issue/21 omPrefixes = 'Webkit Moz O ms', cssomPrefixes = omPrefixes.split(' '), domPrefixes = omPrefixes.toLowerCase().split(' '), /*>>domprefixes*/ /*>>ns*/ ns = {'svg': 'http://www.w3.org/2000/svg'}, /*>>ns*/ tests = {}, inputs = {}, attrs = {}, classes = [], slice = classes.slice, featureName, // used in testing loop /*>>teststyles*/ // Inject element with style element and some CSS rules injectElementWithStyles = function( rule, callback, nodes, testnames ) { var style, ret, node, docOverflow, div = document.createElement('div'), // After page load injecting a fake body doesn't work so check if body exists body = document.body, // IE6 and 7 won't return offsetWidth or offsetHeight unless it's in the body element, so we fake it. fakeBody = body || document.createElement('body'); if ( parseInt(nodes, 10) ) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while ( nodes-- ) { node = document.createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements. // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx // Documents served as xml will throw if using ­ so use xml friendly encoded version. See issue #277 style = ['­','<style id="s', mod, '">', rule, '</style>'].join(''); div.id = mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (body ? div : fakeBody).innerHTML += style; fakeBody.appendChild(div); if ( !body ) { //avoid crashing IE8, if background image is used fakeBody.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible fakeBody.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(fakeBody); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if ( !body ) { fakeBody.parentNode.removeChild(fakeBody); docElement.style.overflow = docOverflow; } else { div.parentNode.removeChild(div); } return !!ret; }, /*>>teststyles*/ /*>>mq*/ // adapted from matchMedia polyfill // by Scott Jehl and Paul Irish // gist.github.com/786768 testMediaQuery = function( mq ) { var matchMedia = window.matchMedia || window.msMatchMedia; if ( matchMedia ) { return matchMedia(mq) && matchMedia(mq).matches || false; } var bool; injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) { bool = (window.getComputedStyle ? getComputedStyle(node, null) : node.currentStyle)['position'] == 'absolute'; }); return bool; }, /*>>mq*/ /*>>hasevent*/ // // isEventSupported determines if a given element supports the given event // kangax.github.com/iseventsupported/ // // The following results are known incorrects: // Modernizr.hasEvent("webkitTransitionEnd", elem) // false negative // Modernizr.hasEvent("textInput") // in Webkit. github.com/Modernizr/Modernizr/issues/333 // ... isEventSupported = (function() { var TAGNAMES = { 'select': 'input', 'change': 'input', 'submit': 'form', 'reset': 'form', 'error': 'img', 'load': 'img', 'abort': 'img' }; function isEventSupported( eventName, element ) { element = element || document.createElement(TAGNAMES[eventName] || 'div'); eventName = 'on' + eventName; // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those var isSupported = eventName in element; if ( !isSupported ) { // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element if ( !element.setAttribute ) { element = document.createElement('div'); } if ( element.setAttribute && element.removeAttribute ) { element.setAttribute(eventName, ''); isSupported = is(element[eventName], 'function'); // If property was created, "remove it" (by setting value to `undefined`) if ( !is(element[eventName], 'undefined') ) { element[eventName] = undefined; } element.removeAttribute(eventName); } } element = null; return isSupported; } return isEventSupported; })(), /*>>hasevent*/ // TODO :: Add flag for hasownprop ? didn't last time // hasOwnProperty shim by kangax needed for Safari 2.0 support _hasOwnProperty = ({}).hasOwnProperty, hasOwnProp; if ( !is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined') ) { hasOwnProp = function (object, property) { return _hasOwnProperty.call(object, property); }; } else { hasOwnProp = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */ return ((property in object) && is(object.constructor.prototype[property], 'undefined')); }; } // Adapted from ES5-shim https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js // es5.github.com/#x15.3.4.5 if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { var target = this; if (typeof target != "function") { throw new TypeError(); } var args = slice.call(arguments, 1), bound = function () { if (this instanceof bound) { var F = function(){}; F.prototype = target.prototype; var self = new F(); var result = target.apply( self, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return self; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; return bound; }; } /** * setCss applies given styles to the Modernizr DOM node. */ function setCss( str ) { mStyle.cssText = str; } /** * setCssAll extrapolates all vendor-specific css strings. */ function setCssAll( str1, str2 ) { return setCss(prefixes.join(str1 + ';') + ( str2 || '' )); } /** * is returns a boolean for if typeof obj is exactly type. */ function is( obj, type ) { return typeof obj === type; } /** * contains returns a boolean for if substr is found within str. */ function contains( str, substr ) { return !!~('' + str).indexOf(substr); } /*>>testprop*/ // testProps is a generic CSS / DOM property test. // In testing support for a given CSS property, it's legit to test: // `elem.style[styleName] !== undefined` // If the property is supported it will return an empty string, // if unsupported it will return undefined. // We'll take advantage of this quick test and skip setting a style // on our modernizr element, but instead just testing undefined vs // empty string. // Because the testing of the CSS property names (with "-", as // opposed to the camelCase DOM properties) is non-portable and // non-standard but works in WebKit and IE (but not Gecko or Opera), // we explicitly reject properties with dashes so that authors // developing in WebKit or IE first don't end up with // browser-specific content by accident. function testProps( props, prefixed ) { for ( var i in props ) { var prop = props[i]; if ( !contains(prop, "-") && mStyle[prop] !== undefined ) { return prefixed == 'pfx' ? prop : true; } } return false; } /*>>testprop*/ // TODO :: add testDOMProps /** * testDOMProps is a generic DOM property test; if a browser supports * a certain property, it won't return undefined for it. */ function testDOMProps( props, obj, elem ) { for ( var i in props ) { var item = obj[props[i]]; if ( item !== undefined) { // return the property name as a string if (elem === false) return props[i]; // let's bind a function if (is(item, 'function')){ // default to autobind unless override return item.bind(elem || obj); } // return the unbound function or obj or value return item; } } return false; } /*>>testallprops*/ /** * testPropsAll tests a list of DOM properties we want to check against. * We specify literally ALL possible (known and/or likely) properties on * the element including the non-vendor prefixed one, for forward- * compatibility. */ function testPropsAll( prop, prefixed, elem ) { var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' '); // did they call .prefixed('boxSizing') or are we just testing a prop? if(is(prefixed, "string") || is(prefixed, "undefined")) { return testProps(props, prefixed); // otherwise, they called .prefixed('requestAnimationFrame', window[, elem]) } else { props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' '); return testDOMProps(props, prefixed, elem); } } /*>>testallprops*/ /** * Tests * ----- */ // The *new* flexbox // dev.w3.org/csswg/css3-flexbox tests['flexbox'] = function() { return testPropsAll('flexWrap'); }; // The *old* flexbox // www.w3.org/TR/2009/WD-css3-flexbox-20090723/ tests['flexboxlegacy'] = function() { return testPropsAll('boxDirection'); }; // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ tests['canvas'] = function() { var elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d')); }; tests['canvastext'] = function() { return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function')); }; // webk.it/70117 is tracking a legit WebGL feature detect proposal // We do a soft detect which may false positive in order to avoid // an expensive context creation: bugzil.la/732441 tests['webgl'] = function() { return !!window.WebGLRenderingContext; }; /* * The Modernizr.touch test only indicates if the browser supports * touch events, which does not necessarily reflect a touchscreen * device, as evidenced by tablets running Windows 7 or, alas, * the Palm Pre / WebOS (touch) phones. * * Additionally, Chrome (desktop) used to lie about its support on this, * but that has since been rectified: crbug.com/36415 * * We also test for Firefox 4 Multitouch Support. * * For more info, see: modernizr.github.com/Modernizr/touch.html */ tests['touch'] = function() { var bool; if(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { bool = true; } else { injectElementWithStyles(['@media (',prefixes.join('touch-enabled),('),mod,')','{#modernizr{top:9px;position:absolute}}'].join(''), function( node ) { bool = node.offsetTop === 9; }); } return bool; }; // geolocation is often considered a trivial feature detect... // Turns out, it's quite tricky to get right: // // Using !!navigator.geolocation does two things we don't want. It: // 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513 // 2. Disables page caching in WebKit: webk.it/43956 // // Meanwhile, in Firefox < 8, an about:config setting could expose // a false positive that would throw an exception: bugzil.la/688158 tests['geolocation'] = function() { return 'geolocation' in navigator; }; tests['postmessage'] = function() { return !!window.postMessage; }; // Chrome incognito mode used to throw an exception when using openDatabase // It doesn't anymore. tests['websqldatabase'] = function() { return !!window.openDatabase; }; // Vendors had inconsistent prefixing with the experimental Indexed DB: // - Webkit's implementation is accessible through webkitIndexedDB // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB // For speed, we don't test the legacy (and beta-only) indexedDB tests['indexedDB'] = function() { return !!testPropsAll("indexedDB", window); }; // documentMode logic from YUI to filter out IE8 Compat Mode // which false positives. tests['hashchange'] = function() { return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7); }; // Per 1.6: // This used to be Modernizr.historymanagement but the longer // name has been deprecated in favor of a shorter and property-matching one. // The old API is still available in 1.6, but as of 2.0 will throw a warning, // and in the first release thereafter disappear entirely. tests['history'] = function() { return !!(window.history && history.pushState); }; tests['draganddrop'] = function() { var div = document.createElement('div'); return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div); }; // FF3.6 was EOL'ed on 4/24/12, but the ESR version of FF10 // will be supported until FF19 (2/12/13), at which time, ESR becomes FF17. // FF10 still uses prefixes, so check for it until then. // for more ESR info, see: mozilla.org/en-US/firefox/organizations/faq/ tests['websockets'] = function() { return 'WebSocket' in window || 'MozWebSocket' in window; }; // css-tricks.com/rgba-browser-support/ tests['rgba'] = function() { // Set an rgba() color and check the returned value setCss('background-color:rgba(150,255,150,.5)'); return contains(mStyle.backgroundColor, 'rgba'); }; tests['hsla'] = function() { // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally, // except IE9 who retains it as hsla setCss('background-color:hsla(120,40%,100%,.5)'); return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla'); }; tests['multiplebgs'] = function() { // Setting multiple images AND a color on the background shorthand property // and then querying the style.background property value for the number of // occurrences of "url(" is a reliable method for detecting ACTUAL support for this! setCss('background:url(https://),url(https://),red url(https://)'); // If the UA supports multiple backgrounds, there should be three occurrences // of the string "url(" in the return value for elemStyle.background return (/(url\s*\(.*?){3}/).test(mStyle.background); }; // this will false positive in Opera Mini // github.com/Modernizr/Modernizr/issues/396 tests['backgroundsize'] = function() { return testPropsAll('backgroundSize'); }; tests['borderimage'] = function() { return testPropsAll('borderImage'); }; // Super comprehensive table about all the unique implementations of // border-radius: muddledramblings.com/table-of-css3-border-radius-compliance tests['borderradius'] = function() { return testPropsAll('borderRadius'); }; // WebOS unfortunately false positives on this test. tests['boxshadow'] = function() { return testPropsAll('boxShadow'); }; // FF3.0 will false positive on this test tests['textshadow'] = function() { return document.createElement('div').style.textShadow === ''; }; tests['opacity'] = function() { // Browsers that actually have CSS Opacity implemented have done so // according to spec, which means their return values are within the // range of [0.0,1.0] - including the leading zero. setCssAll('opacity:.55'); // The non-literal . in this regex is intentional: // German Chrome returns this value as 0,55 // github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632 return (/^0.55$/).test(mStyle.opacity); }; // Note, Android < 4 will pass this test, but can only animate // a single property at a time // goo.gl/v3V4Gp tests['cssanimations'] = function() { return testPropsAll('animationName'); }; tests['csscolumns'] = function() { return testPropsAll('columnCount'); }; tests['cssgradients'] = function() { /** * For CSS Gradients syntax, please see: * webkit.org/blog/175/introducing-css-gradients/ * developer.mozilla.org/en/CSS/-moz-linear-gradient * developer.mozilla.org/en/CSS/-moz-radial-gradient * dev.w3.org/csswg/css3-images/#gradients- */ var str1 = 'background-image:', str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));', str3 = 'linear-gradient(left top,#9f9, white);'; setCss( // legacy webkit syntax (FIXME: remove when syntax not in use anymore) (str1 + '-webkit- '.split(' ').join(str2 + str1) + // standard syntax // trailing 'background-image:' prefixes.join(str3 + str1)).slice(0, -str1.length) ); return contains(mStyle.backgroundImage, 'gradient'); }; tests['cssreflections'] = function() { return testPropsAll('boxReflect'); }; tests['csstransforms'] = function() { return !!testPropsAll('transform'); }; tests['csstransforms3d'] = function() { var ret = !!testPropsAll('perspective'); // Webkit's 3D transforms are passed off to the browser's own graphics renderer. // It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in // some conditions. As a result, Webkit typically recognizes the syntax but // will sometimes throw a false positive, thus we must do a more thorough check: if ( ret && 'webkitPerspective' in docElement.style ) { // Webkit allows this media query to succeed only if the feature is enabled. // `@media (transform-3d),(-webkit-transform-3d){ ... }` injectElementWithStyles('@media (transform-3d),(-webkit-transform-3d){#modernizr{left:9px;position:absolute;height:3px;}}', function( node, rule ) { ret = node.offsetLeft === 9 && node.offsetHeight === 3; }); } return ret; }; tests['csstransitions'] = function() { return testPropsAll('transition'); }; /*>>fontface*/ // @font-face detection routine by Diego Perini // javascript.nwbox.com/CSSSupport/ // false positives: // WebOS github.com/Modernizr/Modernizr/issues/342 // WP7 github.com/Modernizr/Modernizr/issues/538 tests['fontface'] = function() { var bool; injectElementWithStyles('@font-face {font-family:"font";src:url("https://")}', function( node, rule ) { var style = document.getElementById('smodernizr'), sheet = style.sheet || style.styleSheet, cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : ''; bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0; }); return bool; }; /*>>fontface*/ // CSS generated content detection tests['generatedcontent'] = function() { var bool; injectElementWithStyles(['#',mod,'{font:0/0 a}#',mod,':after{content:"',smile,'";visibility:hidden;font:3px/1 a}'].join(''), function( node ) { bool = node.offsetHeight >= 3; }); return bool; }; // These tests evaluate support of the video/audio elements, as well as // testing what types of content they support. // // We're using the Boolean constructor here, so that we can extend the value // e.g. Modernizr.video // true // Modernizr.video.ogg // 'probably' // // Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845 // thx to NielsLeenheer and zcorpan // Note: in some older browsers, "no" was a return value instead of empty string. // It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2 // It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5 tests['video'] = function() { var elem = document.createElement('video'), bool = false; // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224 try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('video/ogg; codecs="theora"') .replace(/^no$/,''); // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546 bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"') .replace(/^no$/,''); bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,''); } } catch(e) { } return bool; }; tests['audio'] = function() { var elem = document.createElement('audio'), bool = false; try { if ( bool = !!elem.canPlayType ) { bool = new Boolean(bool); bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,''); bool.mp3 = elem.canPlayType('audio/mpeg;') .replace(/^no$/,''); // Mimetypes accepted: // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements // bit.ly/iphoneoscodecs bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/,''); bool.m4a = ( elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;')) .replace(/^no$/,''); } } catch(e) { } return bool; }; // In FF4, if disabled, window.localStorage should === null. // Normally, we could not test that directly and need to do a // `('localStorage' in window) && ` test first because otherwise Firefox will // throw bugzil.la/365772 if cookies are disabled // Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem // will throw the exception: // QUOTA_EXCEEDED_ERRROR DOM Exception 22. // Peculiarly, getItem and removeItem calls do not throw. // Because we are forced to try/catch this, we'll go aggressive. // Just FWIW: IE8 Compat mode supports these features completely: // www.quirksmode.org/dom/html5.html // But IE8 doesn't support either with local files tests['localstorage'] = function() { try { localStorage.setItem(mod, mod); localStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['sessionstorage'] = function() { try { sessionStorage.setItem(mod, mod); sessionStorage.removeItem(mod); return true; } catch(e) { return false; } }; tests['webworkers'] = function() { return !!window.Worker; }; tests['applicationcache'] = function() { return !!window.applicationCache; }; // Thanks to Erik Dahlstrom tests['svg'] = function() { return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect; }; // specifically for SVG inline in HTML, not within XHTML // test page: paulirish.com/demo/inline-svg tests['inlinesvg'] = function() { var div = document.createElement('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) == ns.svg; }; // SVG SMIL animation tests['smil'] = function() { return !!document.createElementNS && /SVGAnimate/.test(toString.call(document.createElementNS(ns.svg, 'animate'))); }; // This test is only for clip paths in SVG proper, not clip paths on HTML content // demo: srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg // However read the comments to dig into applying SVG clippaths to HTML content here: // github.com/Modernizr/Modernizr/issues/213#issuecomment-1149491 tests['svgclippaths'] = function() { return !!document.createElementNS && /SVGClipPath/.test(toString.call(document.createElementNS(ns.svg, 'clipPath'))); }; /*>>webforms*/ // input features and input types go directly onto the ret object, bypassing the tests loop. // Hold this guy to execute in a moment. function webforms() { /*>>input*/ // Run through HTML5's new input attributes to see if the UA understands any. // We're using f which is the <input> element created early on // Mike Taylr has created a comprehensive resource for testing these attributes // when applied to all input types: // miketaylr.com/code/input-type-attr.html // spec: www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary // Only input placeholder is tested while textarea's placeholder is not. // Currently Safari 4 and Opera 11 have support only for the input placeholder // Both tests are available in feature-detects/forms-placeholder.js Modernizr['input'] = (function( props ) { for ( var i = 0, len = props.length; i < len; i++ ) { attrs[ props[i] ] = !!(props[i] in inputElem); } if (attrs.list){ // safari false positive's on datalist: webk.it/74252 // see also github.com/Modernizr/Modernizr/issues/146 attrs.list = !!(document.createElement('datalist') && window.HTMLDataListElement); } return attrs; })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ')); /*>>input*/ /*>>inputtypes*/ // Run through HTML5's new input types to see if the UA understands any. // This is put behind the tests runloop because it doesn't return a // true/false like all the other tests; instead, it returns an object // containing each input type with its corresponding true/false value // Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/ Modernizr['inputtypes'] = (function(props) { for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) { inputElem.setAttribute('type', inputElemType = props[i]); bool = inputElem.type !== 'text'; // We first check to see if the type we give it sticks.. // If the type does, we feed it a textual value, which shouldn't be valid. // If the value doesn't stick, we know there's input sanitization which infers a custom UI if ( bool ) { inputElem.value = smile; inputElem.style.cssText = 'position:absolute;visibility:hidden;'; if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) { docElement.appendChild(inputElem); defaultView = document.defaultView; // Safari 2-4 allows the smiley as a value, despite making a slider bool = defaultView.getComputedStyle && defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' && // Mobile android web browser has false positive, so must // check the height to see if the widget is actually there. (inputElem.offsetHeight !== 0); docElement.removeChild(inputElem); } else if ( /^(search|tel)$/.test(inputElemType) ){ // Spec doesn't define any special parsing or detectable UI // behaviors so we pass these through as true // Interestingly, opera fails the earlier test, so it doesn't // even make it here. } else if ( /^(url|email)$/.test(inputElemType) ) { // Real url and email support comes with prebaked validation. bool = inputElem.checkValidity && inputElem.checkValidity() === false; } else { // If the upgraded input compontent rejects the :) text, we got a winner bool = inputElem.value != smile; } } inputs[ props[i] ] = !!bool; } return inputs; })('search tel url email datetime date month week time datetime-local number range color'.split(' ')); /*>>inputtypes*/ } /*>>webforms*/ // End of test definitions // ----------------------- // Run through all tests and detect their support in the current UA. // todo: hypothetically we could be doing an array of tests and use a basic loop here. for ( var feature in tests ) { if ( hasOwnProp(tests, feature) ) { // run the test, throw the return value into the Modernizr, // then based on that boolean, define an appropriate className // and push it into an array of classes we'll join later. featureName = feature.toLowerCase(); Modernizr[featureName] = tests[feature](); classes.push((Modernizr[featureName] ? '' : 'no-') + featureName); } } /*>>webforms*/ // input tests need to run. Modernizr.input || webforms(); /*>>webforms*/ /** * addTest allows the user to define their own feature tests * the result will be added onto the Modernizr object, * as well as an appropriate className set on the html element * * @param feature - String naming the feature * @param test - Function returning true if feature is supported, false if not */ Modernizr.addTest = function ( feature, test ) { if ( typeof feature == 'object' ) { for ( var key in feature ) { if ( hasOwnProp( feature, key ) ) { Modernizr.addTest( key, feature[ key ] ); } } } else { feature = feature.toLowerCase(); if ( Modernizr[feature] !== undefined ) { // we're going to quit if you're trying to overwrite an existing test // if we were to allow it, we'd do this: // var re = new RegExp("\\b(no-)?" + feature + "\\b"); // docElement.className = docElement.className.replace( re, '' ); // but, no rly, stuff 'em. return Modernizr; } test = typeof test == 'function' ? test() : test; if (typeof enableClasses !== "undefined" && enableClasses) { docElement.className += ' ' + (test ? '' : 'no-') + feature; } Modernizr[feature] = test; } return Modernizr; // allow chaining. }; // Reset modElem.cssText to nothing to reduce memory footprint. setCss(''); modElem = inputElem = null; /*>>shiv*/ /** * @preserve HTML5 Shiv prev3.7.1 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed */ ;(function(window, document) { /*jshint evil:true */ /** version */ var version = '3.7.0'; /** Preset options */ var options = window.html5 || {}; /** Used to skip problem elements */ var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i; /** Not all elements can be cloned in IE **/ var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i; /** Detect whether the browser supports default html5 styles */ var supportsHtml5Styles; /** Name of the expando, to work with multiple documents or to re-shiv one document */ var expando = '_html5shiv'; /** The id for the the documents expando */ var expanID = 0; /** Cached data for each document */ var expandoData = {}; /** Detect whether the browser supports unknown elements */ var supportsUnknownElements; (function() { try { var a = document.createElement('a'); a.innerHTML = '<xyz></xyz>'; //if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles supportsHtml5Styles = ('hidden' in a); supportsUnknownElements = a.childNodes.length == 1 || (function() { // assign a false positive if unable to shiv (document.createElement)('a'); var frag = document.createDocumentFragment(); return ( typeof frag.cloneNode == 'undefined' || typeof frag.createDocumentFragment == 'undefined' || typeof frag.createElement == 'undefined' ); }()); } catch(e) { // assign a false positive if detection fails => unable to shiv supportsHtml5Styles = true; supportsUnknownElements = true; } }()); /*--------------------------------------------------------------------------*/ /** * Creates a style sheet with the given CSS text and adds it to the document. * @private * @param {Document} ownerDocument The document. * @param {String} cssText The CSS text. * @returns {StyleSheet} The style element. */ function addStyleSheet(ownerDocument, cssText) { var p = ownerDocument.createElement('p'), parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement; p.innerHTML = 'x<style>' + cssText + '</style>'; return parent.insertBefore(p.lastChild, parent.firstChild); } /** * Returns the value of `html5.elements` as an array. * @private * @returns {Array} An array of shived element node names. */ function getElements() { var elements = html5.elements; return typeof elements == 'string' ? elements.split(' ') : elements; } /** * Returns the data associated to the given document * @private * @param {Document} ownerDocument The document. * @returns {Object} An object of data. */ function getExpandoData(ownerDocument) { var data = expandoData[ownerDocument[expando]]; if (!data) { data = {}; expanID++; ownerDocument[expando] = expanID; expandoData[expanID] = data; } return data; } /** * returns a shived element for the given nodeName and document * @memberOf html5 * @param {String} nodeName name of the element * @param {Document} ownerDocument The context document. * @returns {Object} The shived element. */ function createElement(nodeName, ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createElement(nodeName); } if (!data) { data = getExpandoData(ownerDocument); } var node; if (data.cache[nodeName]) { node = data.cache[nodeName].cloneNode(); } else if (saveClones.test(nodeName)) { node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode(); } else { node = data.createElem(nodeName); } // Avoid adding some elements to fragments in IE < 9 because // * Attributes like `name` or `type` cannot be set/changed once an element // is inserted into a document/fragment // * Link elements with `src` attributes that are inaccessible, as with // a 403 response, will cause the tab/window to crash // * Script elements appended to fragments will execute when their `src` // or `text` property is set return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node; } /** * returns a shived DocumentFragment for the given document * @memberOf html5 * @param {Document} ownerDocument The context document. * @returns {Object} The shived DocumentFragment. */ function createDocumentFragment(ownerDocument, data){ if (!ownerDocument) { ownerDocument = document; } if(supportsUnknownElements){ return ownerDocument.createDocumentFragment(); } data = data || getExpandoData(ownerDocument); var clone = data.frag.cloneNode(), i = 0, elems = getElements(), l = elems.length; for(;i<l;i++){ clone.createElement(elems[i]); } return clone; } /** * Shivs the `createElement` and `createDocumentFragment` methods of the document. * @private * @param {Document|DocumentFragment} ownerDocument The document. * @param {Object} data of the document. */ function shivMethods(ownerDocument, data) { if (!data.cache) { data.cache = {}; data.createElem = ownerDocument.createElement; data.createFrag = ownerDocument.createDocumentFragment; data.frag = data.createFrag(); } ownerDocument.createElement = function(nodeName) { //abort shiv if (!html5.shivMethods) { return data.createElem(nodeName); } return createElement(nodeName, ownerDocument, data); }; ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' + 'var n=f.cloneNode(),c=n.createElement;' + 'h.shivMethods&&(' + // unroll the `createElement` calls getElements().join().replace(/[\w\-]+/g, function(nodeName) { data.createElem(nodeName); data.frag.createElement(nodeName); return 'c("' + nodeName + '")'; }) + ');return n}' )(html5, data.frag); } /*--------------------------------------------------------------------------*/ /** * Shivs the given document. * @memberOf html5 * @param {Document} ownerDocument The document to shiv. * @returns {Document} The shived document. */ function shivDocument(ownerDocument) { if (!ownerDocument) { ownerDocument = document; } var data = getExpandoData(ownerDocument); if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) { data.hasCSS = !!addStyleSheet(ownerDocument, // corrects block display not defined in IE6/7/8/9 'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' + // adds styling not present in IE6/7/8/9 'mark{background:#FF0;color:#000}' + // hides non-rendered elements 'template{display:none}' ); } if (!supportsUnknownElements) { shivMethods(ownerDocument, data); } return ownerDocument; } /*--------------------------------------------------------------------------*/ /** * The `html5` object is exposed so that more elements can be shived and * existing shiving can be detected on iframes. * @type Object * @example * * // options can be changed before the script is included * html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false }; */ var html5 = { /** * An array or space separated string of node names of the elements to shiv. * @memberOf html5 * @type Array|String */ 'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video', /** * current version of html5shiv */ 'version': version, /** * A flag to indicate that the HTML5 style sheet should be inserted. * @memberOf html5 * @type Boolean */ 'shivCSS': (options.shivCSS !== false), /** * Is equal to true if a browser supports creating unknown/HTML5 elements * @memberOf html5 * @type boolean */ 'supportsUnknownElements': supportsUnknownElements, /** * A flag to indicate that the document's `createElement` and `createDocumentFragment` * methods should be overwritten. * @memberOf html5 * @type Boolean */ 'shivMethods': (options.shivMethods !== false), /** * A string to describe the type of `html5` object ("default" or "default print"). * @memberOf html5 * @type String */ 'type': 'default', // shivs the document according to the specified `html5` object options 'shivDocument': shivDocument, //creates a shived element createElement: createElement, //creates a shived documentFragment createDocumentFragment: createDocumentFragment }; /*--------------------------------------------------------------------------*/ // expose html5 window.html5 = html5; // shiv the document shivDocument(document); }(this, document)); /*>>shiv*/ // Assign private properties to the return object with prefix Modernizr._version = version; // expose these for the plugin API. Look in the source for how to join() them against your input /*>>prefixes*/ Modernizr._prefixes = prefixes; /*>>prefixes*/ /*>>domprefixes*/ Modernizr._domPrefixes = domPrefixes; Modernizr._cssomPrefixes = cssomPrefixes; /*>>domprefixes*/ /*>>mq*/ // Modernizr.mq tests a given media query, live against the current state of the window // A few important notes: // * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false // * A max-width or orientation query will be evaluated against the current state, which may change later. // * You must specify values. Eg. If you are testing support for the min-width media query use: // Modernizr.mq('(min-width:0)') // usage: // Modernizr.mq('only screen and (max-width:768)') Modernizr.mq = testMediaQuery; /*>>mq*/ /*>>hasevent*/ // Modernizr.hasEvent() detects support for a given event, with an optional element to test on // Modernizr.hasEvent('gesturestart', elem) Modernizr.hasEvent = isEventSupported; /*>>hasevent*/ /*>>testprop*/ // Modernizr.testProp() investigates whether a given style property is recognized // Note that the property names must be provided in the camelCase variant. // Modernizr.testProp('pointerEvents') Modernizr.testProp = function(prop){ return testProps([prop]); }; /*>>testprop*/ /*>>testallprops*/ // Modernizr.testAllProps() investigates whether a given style property, // or any of its vendor-prefixed variants, is recognized // Note that the property names must be provided in the camelCase variant. // Modernizr.testAllProps('boxSizing') Modernizr.testAllProps = testPropsAll; /*>>testallprops*/ /*>>teststyles*/ // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... }) Modernizr.testStyles = injectElementWithStyles; /*>>teststyles*/ /*>>prefixed*/ // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input // Modernizr.prefixed('boxSizing') // 'MozBoxSizing' // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style. // Return values will also be the camelCase variant, if you need to translate that to hypenated style use: // // str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-'); // If you're trying to ascertain which transition end event to bind to, you might do something like... // // var transEndEventNames = { // 'WebkitTransition' : 'webkitTransitionEnd', // 'MozTransition' : 'transitionend', // 'OTransition' : 'oTransitionEnd', // 'msTransition' : 'MSTransitionEnd', // 'transition' : 'transitionend' // }, // transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ]; Modernizr.prefixed = function(prop, obj, elem){ if(!obj) { return testPropsAll(prop, 'pfx'); } else { // Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame' return testPropsAll(prop, obj, elem); } }; /*>>prefixed*/ /*>>cssclasses*/ // Remove "no-js" class from <html> element, if it exists: docElement.className = docElement.className.replace(/(^|\s)no-js(\s|$)/, '$1$2') + // Add the new classes to the <html> element. (enableClasses ? ' js ' + classes.join(' ') : ''); /*>>cssclasses*/ return Modernizr; })(this, this.document); /*! * https://github.com/es-shims/es5-shim * @license es5-shim Copyright 2009-2014 by contributors, MIT License * see https://github.com/es-shims/es5-shim/blob/master/LICENSE */ // vim: ts=4 sts=4 sw=4 expandtab //Add semicolon to prevent IIFE from being passed as argument to concated code. ; // UMD (Universal Module Definition) // see https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { /** * Brings an environment as close to ECMAScript 5 compliance * as is possible with the facilities of erstwhile engines. * * Annotated ES5: http://es5.github.com/ (specific links below) * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf * Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/ */ // Shortcut to an often accessed properties, in order to avoid multiple // dereference that costs universally. var ArrayPrototype = Array.prototype; var ObjectPrototype = Object.prototype; var FunctionPrototype = Function.prototype; var StringPrototype = String.prototype; var NumberPrototype = Number.prototype; var _Array_slice_ = ArrayPrototype.slice; var array_splice = ArrayPrototype.splice; var array_push = ArrayPrototype.push; var array_unshift = ArrayPrototype.unshift; var call = FunctionPrototype.call; // Having a toString local variable name breaks in Opera so use _toString. var _toString = ObjectPrototype.toString; var isFunction = function (val) { return ObjectPrototype.toString.call(val) === '[object Function]'; }; var isRegex = function (val) { return ObjectPrototype.toString.call(val) === '[object RegExp]'; }; var isArray = function isArray(obj) { return _toString.call(obj) === "[object Array]"; }; var isString = function isString(obj) { return _toString.call(obj) === "[object String]"; }; var isArguments = function isArguments(value) { var str = _toString.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = !isArray(value) && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && isFunction(value.callee); } return isArgs; }; var supportsDescriptors = Object.defineProperty && (function () { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is ES3 */ return false; } }()); // Define configurable, writable and non-enumerable props // if they don't exist. var defineProperty; if (supportsDescriptors) { defineProperty = function (object, name, method, forceAssign) { if (!forceAssign && (name in object)) { return; } Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: method }); }; } else { defineProperty = function (object, name, method, forceAssign) { if (!forceAssign && (name in object)) { return; } object[name] = method; }; } var defineProperties = function (object, map, forceAssign) { for (var name in map) { if (ObjectPrototype.hasOwnProperty.call(map, name)) { defineProperty(object, name, map[name], forceAssign); } } }; // // Util // ====== // // ES5 9.4 // http://es5.github.com/#x9.4 // http://jsperf.com/to-integer function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toStr; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (isFunction(valueOf)) { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toStr = input.toString; if (isFunction(toStr)) { val = toStr.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } // ES5 9.9 // http://es5.github.com/#x9.9 var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert " + o + " to object"); } return Object(o); }; var ToUint32 = function ToUint32(x) { return x >>> 0; }; // // Function // ======== // // ES-5 15.3.4.5 // http://es5.github.com/#x15.3.4.5 function Empty() {} defineProperties(FunctionPrototype, { bind: function bind(that) { // .length is 1 // 1. Let Target be the this value. var target = this; // 2. If IsCallable(Target) is false, throw a TypeError exception. if (!isFunction(target)) { throw new TypeError("Function.prototype.bind called on incompatible " + target); } // 3. Let A be a new (possibly empty) internal list of all of the // argument values provided after thisArg (arg1, arg2 etc), in order. // XXX slicedArgs will stand in for "A" if used var args = _Array_slice_.call(arguments, 1); // for normal call // 4. Let F be a new native ECMAScript object. // 11. Set the [[Prototype]] internal property of F to the standard // built-in Function prototype object as specified in 15.3.3.1. // 12. Set the [[Call]] internal property of F as described in // 15.3.4.5.1. // 13. Set the [[Construct]] internal property of F as described in // 15.3.4.5.2. // 14. Set the [[HasInstance]] internal property of F as described in // 15.3.4.5.3. var binder = function () { if (this instanceof bound) { // 15.3.4.5.2 [[Construct]] // When the [[Construct]] internal method of a function object, // F that was created using the bind function is called with a // list of arguments ExtraArgs, the following steps are taken: // 1. Let target be the value of F's [[TargetFunction]] // internal property. // 2. If target has no [[Construct]] internal method, a // TypeError exception is thrown. // 3. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Construct]] internal // method of target providing args as the arguments. var result = target.apply( this, args.concat(_Array_slice_.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { // 15.3.4.5.1 [[Call]] // When the [[Call]] internal method of a function object, F, // which was created using the bind function is called with a // this value and a list of arguments ExtraArgs, the following // steps are taken: // 1. Let boundArgs be the value of F's [[BoundArgs]] internal // property. // 2. Let boundThis be the value of F's [[BoundThis]] internal // property. // 3. Let target be the value of F's [[TargetFunction]] internal // property. // 4. Let args be a new list containing the same values as the // list boundArgs in the same order followed by the same // values as the list ExtraArgs in the same order. // 5. Return the result of calling the [[Call]] internal method // of target providing boundThis as the this value and // providing args as the arguments. // equiv: target.call(this, ...boundArgs, ...args) return target.apply( that, args.concat(_Array_slice_.call(arguments)) ); } }; // 15. If the [[Class]] internal property of Target is "Function", then // a. Let L be the length property of Target minus the length of A. // b. Set the length own property of F to either 0 or L, whichever is // larger. // 16. Else set the length own property of F to 0. var boundLength = Math.max(0, target.length - args.length); // 17. Set the attributes of the length own property of F to the values // specified in 15.3.5.1. var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push("$" + i); } // XXX Build a dynamic function with desired amount of arguments is the only // way to set the length property of a function. // In environments where Content Security Policies enabled (Chrome extensions, // for ex.) all use of eval or Function costructor throws an exception. // However in all of these environments Function.prototype.bind exists // and so this code will never be executed. var bound = Function("binder", "return function (" + boundArgs.join(",") + "){return binder.apply(this,arguments)}")(binder); if (target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); // Clean up dangling references. Empty.prototype = null; } // TODO // 18. Set the [[Extensible]] internal property of F to true. // TODO // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). // 20. Call the [[DefineOwnProperty]] internal method of F with // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and // false. // 21. Call the [[DefineOwnProperty]] internal method of F with // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, // and false. // TODO // NOTE Function objects created using Function.prototype.bind do not // have a prototype property or the [[Code]], [[FormalParameters]], and // [[Scope]] internal properties. // XXX can't delete prototype in pure-js. // 22. Return F. return bound; } }); // _Please note: Shortcuts are defined after `Function.prototype.bind` as we // us it in defining shortcuts. var owns = call.bind(ObjectPrototype.hasOwnProperty); // If JS engine supports accessors creating shortcuts. var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(ObjectPrototype, "__defineGetter__"))) { defineGetter = call.bind(ObjectPrototype.__defineGetter__); defineSetter = call.bind(ObjectPrototype.__defineSetter__); lookupGetter = call.bind(ObjectPrototype.__lookupGetter__); lookupSetter = call.bind(ObjectPrototype.__lookupSetter__); } // // Array // ===== // // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.12 var spliceNoopReturnsEmptyArray = (function () { var a = [1, 2]; var result = a.splice(); return a.length === 2 && isArray(result) && result.length === 0; }()); defineProperties(ArrayPrototype, { // Safari 5.0 bug where .splice() returns undefined splice: function splice(start, deleteCount) { if (arguments.length === 0) { return []; } else { return array_splice.apply(this, arguments); } } }, spliceNoopReturnsEmptyArray); var spliceWorksWithEmptyObject = (function () { var obj = {}; ArrayPrototype.splice.call(obj, 0, 0, 1); return obj.length === 1; }()); defineProperties(ArrayPrototype, { splice: function splice(start, deleteCount) { if (arguments.length === 0) { return []; } var args = arguments; this.length = Math.max(toInteger(this.length), 0); if (arguments.length > 0 && typeof deleteCount !== 'number') { args = _Array_slice_.call(arguments); if (args.length < 2) { args.push(this.length - start); } else { args[1] = toInteger(deleteCount); } } return array_splice.apply(this, args); } }, !spliceWorksWithEmptyObject); // ES5 15.4.4.12 // http://es5.github.com/#x15.4.4.13 // Return len+argCount. // [bugfix, ielt8] // IE < 8 bug: [].unshift(0) === undefined but should be "1" var hasUnshiftReturnValueBug = [].unshift(0) !== 1; defineProperties(ArrayPrototype, { unshift: function () { array_unshift.apply(this, arguments); return this.length; } }, hasUnshiftReturnValueBug); // ES5 15.4.3.2 // http://es5.github.com/#x15.4.3.2 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray defineProperties(Array, { isArray: isArray }); // The IsCallable() check in the Array functions // has been replaced with a strict check on the // internal class of the object to trap cases where // the provided function was actually a regular // expression literal, which in V8 and // JavaScriptCore is a typeof "function". Only in // V8 are regular expression literals permitted as // reduce parameters, so it is desirable in the // general case for the shim to match the more // strict and common behavior of rejecting regular // expressions. // ES5 15.4.4.18 // http://es5.github.com/#x15.4.4.18 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach // Check failure of by-index access of string characters (IE < 9) // and failure of `0 in boxedString` (Rhino) var boxedString = Object("a"); var splitString = boxedString[0] !== "a" || !(0 in boxedString); var properlyBoxesContext = function properlyBoxed(method) { // Check node 0.6.21 bug where third parameter is not boxed var properlyBoxesNonStrict = true; var properlyBoxesStrict = true; if (method) { method.call('foo', function (_, __, context) { if (typeof context !== 'object') { properlyBoxesNonStrict = false; } }); method.call([1], function () { 'use strict'; properlyBoxesStrict = typeof this === 'string'; }, 'x'); } return !!method && properlyBoxesNonStrict && properlyBoxesStrict; }; defineProperties(ArrayPrototype, { forEach: function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, thisp = arguments[1], i = -1, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { // Invoke the callback function with call, passing arguments: // context, property value, property key, thisArg object // context fun.call(thisp, self[i], i, object); } } } }, !properlyBoxesContext(ArrayPrototype.forEach)); // ES5 15.4.4.19 // http://es5.github.com/#x15.4.4.19 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map defineProperties(ArrayPrototype, { map: function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; } }, !properlyBoxesContext(ArrayPrototype.map)); // ES5 15.4.4.20 // http://es5.github.com/#x15.4.4.20 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter defineProperties(ArrayPrototype, { filter: function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; } }, !properlyBoxesContext(ArrayPrototype.filter)); // ES5 15.4.4.16 // http://es5.github.com/#x15.4.4.16 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every defineProperties(ArrayPrototype, { every: function every(fun /*, thisp */) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; } }, !properlyBoxesContext(ArrayPrototype.every)); // ES5 15.4.4.17 // http://es5.github.com/#x15.4.4.17 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some defineProperties(ArrayPrototype, { some: function some(fun /*, thisp */) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, length = self.length >>> 0, thisp = arguments[1]; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; } }, !properlyBoxesContext(ArrayPrototype.some)); // ES5 15.4.4.21 // http://es5.github.com/#x15.4.4.21 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce var reduceCoercesToObject = false; if (ArrayPrototype.reduce) { reduceCoercesToObject = typeof ArrayPrototype.reduce.call('es5', function (_, __, ___, list) { return list; }) === 'object'; } defineProperties(ArrayPrototype, { reduce: function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value and an empty array if (!length && arguments.length === 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } // if array contains no values, no initial value to return if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; } }, !reduceCoercesToObject); // ES5 15.4.4.22 // http://es5.github.com/#x15.4.4.22 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight var reduceRightCoercesToObject = false; if (ArrayPrototype.reduceRight) { reduceRightCoercesToObject = typeof ArrayPrototype.reduceRight.call('es5', function (_, __, ___, list) { return list; }) === 'object'; } defineProperties(ArrayPrototype, { reduceRight: function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && isString(this) ? this.split('') : object, length = self.length >>> 0; // If no callback function or if callback is not a callable function if (!isFunction(fun)) { throw new TypeError(fun + " is not a function"); } // no value to return if no initial value, empty array if (!length && arguments.length === 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } // if array contains no values, no initial value to return if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } if (i < 0) { return result; } do { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; } }, !reduceRightCoercesToObject); // ES5 15.4.4.14 // http://es5.github.com/#x15.4.4.14 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf var hasFirefox2IndexOfBug = Array.prototype.indexOf && [0, 1].indexOf(1, 2) !== -1; defineProperties(ArrayPrototype, { indexOf: function indexOf(sought /*, fromIndex */ ) { var self = splitString && isString(this) ? this.split('') : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } // handle negative indices i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; } }, hasFirefox2IndexOfBug); // ES5 15.4.4.15 // http://es5.github.com/#x15.4.4.15 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf var hasFirefox2LastIndexOfBug = Array.prototype.lastIndexOf && [0, 1].lastIndexOf(0, -3) !== -1; defineProperties(ArrayPrototype, { lastIndexOf: function lastIndexOf(sought /*, fromIndex */) { var self = splitString && isString(this) ? this.split('') : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } // handle negative indices i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; } }, hasFirefox2LastIndexOfBug); // // Object // ====== // // ES5 15.2.3.14 // http://es5.github.com/#x15.2.3.14 // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation var hasDontEnumBug = !({'toString': null}).propertyIsEnumerable('toString'), hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; defineProperties(Object, { keys: function keys(object) { var isFn = isFunction(object), isArgs = isArguments(object), isObject = object !== null && typeof object === 'object', isStr = isObject && isString(object); if (!isObject && !isFn && !isArgs) { throw new TypeError("Object.keys called on a non-object"); } var theKeys = []; var skipProto = hasProtoEnumBug && isFn; if (isStr || isArgs) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && owns(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var ctor = object.constructor, skipConstructor = ctor && ctor.prototype === object; for (var j = 0; j < dontEnumsLength; j++) { var dontEnum = dontEnums[j]; if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) { theKeys.push(dontEnum); } } } return theKeys; } }); var keysWorksWithArguments = Object.keys && (function () { // Safari 5.0 bug return Object.keys(arguments).length === 2; }(1, 2)); var originalKeys = Object.keys; defineProperties(Object, { keys: function keys(object) { if (isArguments(object)) { return originalKeys(ArrayPrototype.slice.call(object)); } else { return originalKeys(object); } } }, !keysWorksWithArguments); // // Date // ==== // // ES5 15.9.5.43 // http://es5.github.com/#x15.9.5.43 // This function returns a String value represent the instance in time // represented by this Date object. The format of the String is the Date Time // string format defined in 15.9.1.15. All fields are present in the String. // The time zone is always UTC, denoted by the suffix Z. If the time value of // this object is not a finite Number a RangeError exception is thrown. var negativeDate = -62198755200000; var negativeYearString = "-000001"; var hasNegativeDateBug = Date.prototype.toISOString && new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1; defineProperties(Date.prototype, { toISOString: function toISOString() { var result, length, value, year, month; if (!isFinite(this)) { throw new RangeError("Date.prototype.toISOString called on non-finite value."); } year = this.getUTCFullYear(); month = this.getUTCMonth(); // see https://github.com/es-shims/es5-shim/issues/111 year += Math.floor(month / 12); month = (month % 12 + 12) % 12; // the date time string format is specified in 15.9.1.15. result = [month + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; year = ( (year < 0 ? "-" : (year > 9999 ? "+" : "")) + ("00000" + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6) ); length = result.length; while (length--) { value = result[length]; // pad months, days, hours, minutes, and seconds to have two // digits. if (value < 10) { result[length] = "0" + value; } } // pad milliseconds to have three digits. return ( year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + ("000" + this.getUTCMilliseconds()).slice(-3) + "Z" ); } }, hasNegativeDateBug); // ES5 15.9.5.44 // http://es5.github.com/#x15.9.5.44 // This function provides a String representation of a Date object for use by // JSON.stringify (15.12.3). var dateToJSONIsSupported = false; try { dateToJSONIsSupported = ( Date.prototype.toJSON && new Date(NaN).toJSON() === null && new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 && Date.prototype.toJSON.call({ // generic toISOString: function () { return true; } }) ); } catch (e) { } if (!dateToJSONIsSupported) { Date.prototype.toJSON = function toJSON(key) { // When the toJSON method is called with argument key, the following // steps are taken: // 1. Let O be the result of calling ToObject, giving it the this // value as its argument. // 2. Let tv be toPrimitive(O, hint Number). var o = Object(this), tv = toPrimitive(o), toISO; // 3. If tv is a Number and is not finite, return null. if (typeof tv === "number" && !isFinite(tv)) { return null; } // 4. Let toISO be the result of calling the [[Get]] internal method of // O with argument "toISOString". toISO = o.toISOString; // 5. If IsCallable(toISO) is false, throw a TypeError exception. if (typeof toISO !== "function") { throw new TypeError("toISOString property is not callable"); } // 6. Return the result of calling the [[Call]] internal method of // toISO with O as the this value and an empty argument list. return toISO.call(o); // NOTE 1 The argument is ignored. // NOTE 2 The toJSON function is intentionally generic; it does not // require that its this value be a Date object. Therefore, it can be // transferred to other kinds of objects for use as a method. However, // it does require that any such object have a toISOString method. An // object is free to use the argument key to filter its // stringification. }; } // ES5 15.9.4.2 // http://es5.github.com/#x15.9.4.2 // based on work shared by Daniel Friesen (dantman) // http://gist.github.com/303249 var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15; var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z')); var doesNotParseY2KNewYear = isNaN(Date.parse("2000-01-01T00:00:00.000Z")); if (!Date.parse || doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) { // XXX global assignment won't work in embeddings that use // an alternate object for the context. Date = (function (NativeDate) { // Date.length === 7 function Date(Y, M, D, h, m, s, ms) { var length = arguments.length; if (this instanceof NativeDate) { var date = length === 1 && String(Y) === Y ? // isString(Y) // We explicitly pass it through parse: new NativeDate(Date.parse(Y)) : // We have to manually make calls depending on argument // length here length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : length >= 6 ? new NativeDate(Y, M, D, h, m, s) : length >= 5 ? new NativeDate(Y, M, D, h, m) : length >= 4 ? new NativeDate(Y, M, D, h) : length >= 3 ? new NativeDate(Y, M, D) : length >= 2 ? new NativeDate(Y, M) : length >= 1 ? new NativeDate(Y) : new NativeDate(); // Prevent mixups with unfixed Date object date.constructor = Date; return date; } return NativeDate.apply(this, arguments); } // 15.9.1.15 Date Time String Format. var isoDateExpression = new RegExp("^" + "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + // 6-digit extended year "(?:-(\\d{2})" + // optional month capture "(?:-(\\d{2})" + // optional day capture "(?:" + // capture hours:minutes:seconds.milliseconds "T(\\d{2})" + // hours capture ":(\\d{2})" + // minutes capture "(?:" + // optional :seconds.milliseconds ":(\\d{2})" + // seconds capture "(?:(\\.\\d{1,}))?" + // milliseconds capture ")?" + "(" + // capture UTC offset component "Z|" + // UTC capture "(?:" + // offset specifier +/-hours:minutes "([-+])" + // sign capture "(\\d{2})" + // hours offset capture ":(\\d{2})" + // minutes offset capture ")" + ")?)?)?)?" + "$"); var months = [ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 ]; function dayFromMonth(year, month) { var t = month > 1 ? 1 : 0; return ( months[month] + Math.floor((year - 1969 + t) / 4) - Math.floor((year - 1901 + t) / 100) + Math.floor((year - 1601 + t) / 400) + 365 * (year - 1970) ); } function toUTC(t) { return Number(new NativeDate(1970, 0, 1, 0, 0, 0, t)); } // Copy any custom methods a 3rd party library may have added for (var key in NativeDate) { Date[key] = NativeDate[key]; } // Copy "native" methods explicitly; they may be non-enumerable Date.now = NativeDate.now; Date.UTC = NativeDate.UTC; Date.prototype = NativeDate.prototype; Date.prototype.constructor = Date; // Upgrade Date.parse to handle simplified ISO 8601 strings Date.parse = function parse(string) { var match = isoDateExpression.exec(string); if (match) { // parse months, days, hours, minutes, seconds, and milliseconds // provide default values if necessary // parse the UTC offset component var year = Number(match[1]), month = Number(match[2] || 1) - 1, day = Number(match[3] || 1) - 1, hour = Number(match[4] || 0), minute = Number(match[5] || 0), second = Number(match[6] || 0), millisecond = Math.floor(Number(match[7] || 0) * 1000), // When time zone is missed, local offset should be used // (ES 5.1 bug) // see https://bugs.ecmascript.org/show_bug.cgi?id=112 isLocalTime = Boolean(match[4] && !match[8]), signOffset = match[9] === "-" ? 1 : -1, hourOffset = Number(match[10] || 0), minuteOffset = Number(match[11] || 0), result; if ( hour < ( minute > 0 || second > 0 || millisecond > 0 ? 24 : 25 ) && minute < 60 && second < 60 && millisecond < 1000 && month > -1 && month < 12 && hourOffset < 24 && minuteOffset < 60 && // detect invalid offsets day > -1 && day < ( dayFromMonth(year, month + 1) - dayFromMonth(year, month) ) ) { result = ( (dayFromMonth(year, month) + day) * 24 + hour + hourOffset * signOffset ) * 60; result = ( (result + minute + minuteOffset * signOffset) * 60 + second ) * 1000 + millisecond; if (isLocalTime) { result = toUTC(result); } if (-8.64e15 <= result && result <= 8.64e15) { return result; } } return NaN; } return NativeDate.parse.apply(this, arguments); }; return Date; })(Date); } // ES5 15.9.4.4 // http://es5.github.com/#x15.9.4.4 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } // // Number // ====== // // ES5.1 15.7.4.5 // http://es5.github.com/#x15.7.4.5 var hasToFixedBugs = NumberPrototype.toFixed && ( (0.00008).toFixed(3) !== '0.000' || (0.9).toFixed(0) !== '1' || (1.255).toFixed(2) !== '1.25' || (1000000000000000128).toFixed(0) !== "1000000000000000128" ); var toFixedHelpers = { base: 1e7, size: 6, data: [0, 0, 0, 0, 0, 0], multiply: function multiply(n, c) { var i = -1; while (++i < toFixedHelpers.size) { c += n * toFixedHelpers.data[i]; toFixedHelpers.data[i] = c % toFixedHelpers.base; c = Math.floor(c / toFixedHelpers.base); } }, divide: function divide(n) { var i = toFixedHelpers.size, c = 0; while (--i >= 0) { c += toFixedHelpers.data[i]; toFixedHelpers.data[i] = Math.floor(c / n); c = (c % n) * toFixedHelpers.base; } }, numToString: function numToString() { var i = toFixedHelpers.size; var s = ''; while (--i >= 0) { if (s !== '' || i === 0 || toFixedHelpers.data[i] !== 0) { var t = String(toFixedHelpers.data[i]); if (s === '') { s = t; } else { s += '0000000'.slice(0, 7 - t.length) + t; } } } return s; }, pow: function pow(x, n, acc) { return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc))); }, log: function log(x) { var n = 0; while (x >= 4096) { n += 12; x /= 4096; } while (x >= 2) { n += 1; x /= 2; } return n; } }; defineProperties(NumberPrototype, { toFixed: function toFixed(fractionDigits) { var f, x, s, m, e, z, j, k; // Test for NaN and round fractionDigits down f = Number(fractionDigits); f = f !== f ? 0 : Math.floor(f); if (f < 0 || f > 20) { throw new RangeError("Number.toFixed called with invalid number of decimals"); } x = Number(this); // Test for NaN if (x !== x) { return "NaN"; } // If it is too big or small, return the string value of the number if (x <= -1e21 || x >= 1e21) { return String(x); } s = ""; if (x < 0) { s = "-"; x = -x; } m = "0"; if (x > 1e-21) { // 1e-21 < x < 1e21 // -70 < log2(x) < 70 e = toFixedHelpers.log(x * toFixedHelpers.pow(2, 69, 1)) - 69; z = (e < 0 ? x * toFixedHelpers.pow(2, -e, 1) : x / toFixedHelpers.pow(2, e, 1)); z *= 0x10000000000000; // Math.pow(2, 52); e = 52 - e; // -18 < e < 122 // x = z / 2 ^ e if (e > 0) { toFixedHelpers.multiply(0, z); j = f; while (j >= 7) { toFixedHelpers.multiply(1e7, 0); j -= 7; } toFixedHelpers.multiply(toFixedHelpers.pow(10, j, 1), 0); j = e - 1; while (j >= 23) { toFixedHelpers.divide(1 << 23); j -= 23; } toFixedHelpers.divide(1 << j); toFixedHelpers.multiply(1, 1); toFixedHelpers.divide(2); m = toFixedHelpers.numToString(); } else { toFixedHelpers.multiply(0, z); toFixedHelpers.multiply(1 << (-e), 0); m = toFixedHelpers.numToString() + '0.00000000000000000000'.slice(2, 2 + f); } } if (f > 0) { k = m.length; if (k <= f) { m = s + '0.0000000000000000000'.slice(0, f - k + 2) + m; } else { m = s + m.slice(0, k - f) + '.' + m.slice(k - f); } } else { m = s + m; } return m; } }, hasToFixedBugs); // // String // ====== // // ES5 15.5.4.14 // http://es5.github.com/#x15.5.4.14 // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers] // Many browsers do not split properly with regular expressions or they // do not perform the split correctly under obscure conditions. // See http://blog.stevenlevithan.com/archives/cross-browser-split // I've tested in many browsers and this seems to cover the deviant ones: // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""] // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""] // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not // [undefined, "t", undefined, "e", ...] // ''.split(/.?/) should be [], not [""] // '.'.split(/()()/) should be ["."], not ["", "", "."] var string_split = StringPrototype.split; if ( 'ab'.split(/(?:ab)*/).length !== 2 || '.'.split(/(.?)(.?)/).length !== 4 || 'tesst'.split(/(s)*/)[1] === "t" || 'test'.split(/(?:)/, -1).length !== 4 || ''.split(/.?/).length || '.'.split(/()()/).length > 1 ) { (function () { var compliantExecNpcg = /()??/.exec("")[1] === void 0; // NPCG: nonparticipating capturing group StringPrototype.split = function (separator, limit) { var string = this; if (separator === void 0 && limit === 0) { return []; } // If `separator` is not a regex, use native split if (_toString.call(separator) !== "[object RegExp]") { return string_split.call(this, separator, limit); } var output = [], flags = (separator.ignoreCase ? "i" : "") + (separator.multiline ? "m" : "") + (separator.extended ? "x" : "") + // Proposed for ES6 (separator.sticky ? "y" : ""), // Firefox 3+ lastLastIndex = 0, // Make `global` and avoid `lastIndex` issues by working with a copy separator2, match, lastIndex, lastLength; separator = new RegExp(separator.source, flags + "g"); string += ""; // Type-convert if (!compliantExecNpcg) { // Doesn't need flags gy, but they don't hurt separator2 = new RegExp("^" + separator.source + "$(?!\\s)", flags); } /* Values for `limit`, per the spec: * If undefined: 4294967295 // Math.pow(2, 32) - 1 * If 0, Infinity, or NaN: 0 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296; * If negative number: 4294967296 - Math.floor(Math.abs(limit)) * If other: Type-convert, then use the above rules */ limit = limit === void 0 ? -1 >>> 0 : // Math.pow(2, 32) - 1 ToUint32(limit); while (match = separator.exec(string)) { // `separator.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0].length; if (lastIndex > lastLastIndex) { output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === void 0) { match[i] = void 0; } } }); } if (match.length > 1 && match.index < string.length) { ArrayPrototype.push.apply(output, match.slice(1)); } lastLength = match[0].length; lastLastIndex = lastIndex; if (output.length >= limit) { break; } } if (separator.lastIndex === match.index) { separator.lastIndex++; // Avoid an infinite loop } } if (lastLastIndex === string.length) { if (lastLength || !separator.test("")) { output.push(""); } } else { output.push(string.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; }()); // [bugfix, chrome] // If separator is undefined, then the result array contains just one String, // which is the this value (converted to a String). If limit is not undefined, // then the output array is truncated so that it contains no more than limit // elements. // "0".split(undefined, 0) -> [] } else if ("0".split(void 0, 0).length) { StringPrototype.split = function split(separator, limit) { if (separator === void 0 && limit === 0) { return []; } return string_split.call(this, separator, limit); }; } var str_replace = StringPrototype.replace; var replaceReportsGroupsCorrectly = (function () { var groups = []; 'x'.replace(/x(.)?/g, function (match, group) { groups.push(group); }); return groups.length === 1 && typeof groups[0] === 'undefined'; }()); if (!replaceReportsGroupsCorrectly) { StringPrototype.replace = function replace(searchValue, replaceValue) { var isFn = isFunction(replaceValue); var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source); if (!isFn || !hasCapturingGroups) { return str_replace.call(this, searchValue, replaceValue); } else { var wrappedReplaceValue = function (match) { var length = arguments.length; var originalLastIndex = searchValue.lastIndex; searchValue.lastIndex = 0; var args = searchValue.exec(match); searchValue.lastIndex = originalLastIndex; args.push(arguments[length - 2], arguments[length - 1]); return replaceValue.apply(this, args); }; return str_replace.call(this, searchValue, wrappedReplaceValue); } }; } // ECMA-262, 3rd B.2.3 // Not an ECMAScript standard, although ECMAScript 3rd Edition has a // non-normative section suggesting uniform semantics and it should be // normalized across all browsers // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE var string_substr = StringPrototype.substr; var hasNegativeSubstrBug = "".substr && "0b".substr(-1) !== "b"; defineProperties(StringPrototype, { substr: function substr(start, length) { return string_substr.call( this, start < 0 ? ((start = this.length + start) < 0 ? 0 : start) : start, length ); } }, hasNegativeSubstrBug); // ES5 15.5.4.20 // whitespace from: http://es5.github.io/#x15.5.4.20 var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; var zeroWidth = '\u200b'; var wsRegexChars = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + wsRegexChars + wsRegexChars + "*"); var trimEndRegexp = new RegExp(wsRegexChars + wsRegexChars + "*$"); var hasTrimWhitespaceBug = StringPrototype.trim && (ws.trim() || !zeroWidth.trim()); defineProperties(StringPrototype, { // http://blog.stevenlevithan.com/archives/faster-trim-javascript // http://perfectionkills.com/whitespace-deviations/ trim: function trim() { if (this === void 0 || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); } }, hasTrimWhitespaceBug); // ES-5 15.1.2.2 if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) { parseInt = (function (origParseInt) { var hexRegex = /^0[xX]/; return function parseIntES5(str, radix) { str = String(str).trim(); if (!Number(radix)) { radix = hexRegex.test(str) ? 16 : 10; } return origParseInt(str, radix); }; }(parseInt)); } })); /*! * jQuery JavaScript Library v1.9.0 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-1-14 */ (function( window, undefined ) { "use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // 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.9.0", // 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 = /^(?:(<[\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 and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }; 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, // The number of elements contained in the matched element set size: function() { return this.length; }, 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 options, name, src, copy, copyIsArray, 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({ 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 ) { 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 ) { // 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; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; 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 tmp, args, proxy; 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(); } }); 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", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // 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 ); } // 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); // 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 // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // 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; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; 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 ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { 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() { var support, all, a, select, opt, input, fragment, 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'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // 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"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) 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 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) 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) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // 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), test/csp.php 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"; // 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%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // 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 !== "undefined" ) { // 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 ); // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 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 thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // 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)) && getByName && data === undefined ) { 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 ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].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 ( getByName ) { // 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 /* For internal use only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, 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 ) ); } for ( i = 0, l = name.length; i < l; 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 : 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) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, 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, false ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name, false ); }, // 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 ) { 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, elem = this[0], i = 0, data = null; // 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-" ) ) { name = jQuery.camelCase( name.substring(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 jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, 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--; } hooks.cur = fn; 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]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/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, isBool = typeof stateVal === "boolean"; 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 ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === "undefined" || 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 hooks, ret, 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, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.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 ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : 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 values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var ret, hooks, notxml, 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 === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== "undefined" ) { ret = elem.getAttribute( 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 ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { 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: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, 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 ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return 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/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, 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; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, 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 = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, 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; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, 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 ] = jQuery.extend( 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 ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // 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 = jQuery.extend( 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; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * 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 handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, // Don't attach events to noData or text/comment nodes (but allow plain objects) elemData = elem.nodeType !== 3 && elem.nodeType !== 8 && jQuery._data( elem ); 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 !== "undefined" && (!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 // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // 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, origCount, tmp, events, t, handleObj, 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 i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = event.type || event, namespaces = 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 ); event.isTrigger = true; 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( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && 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, j, ret, matched, handleObj, 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 i, matches, sel, handleObj, 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") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( 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, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, 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 eventDoc, doc, body, 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 }, 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; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && 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 === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, 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 ] === "undefined" ) { 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 origFn, type; // 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 ); }); }, 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 ); }, 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 ); } }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); 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 ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, 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; }, // 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 operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + 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 + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + 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" ), // 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" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /\{\s*\[native code\]\s*\}/, // 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, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * 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 cache, keys = []; return (cache = function( 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); }); } /** * 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 { // release memory in IE div = null; } } 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 ( !documentIsXML && !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, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = 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, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * 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; }; /** * 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; // 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 documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { 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 { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; 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.tagNameNoComments ? 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 === "*" ) { for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(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 explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // 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 ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").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 = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || 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 = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(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; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE ); // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 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; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; 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']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !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 ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = a && b && a.nextSibling; for ( ; cur; cur = cur.nextSibling ) { if ( cur === b ) { return -1; } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types 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 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 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]); } } }); }); } /** * 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, 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[4] ) { 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( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return 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( 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.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 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 identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.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; }) } }; // 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 ); } 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 && combinator.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( tokens.slice( 0, i - 1 ) ).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 ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); 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 // `i` starts as a string, so matchedCount would equal "00" if there are no elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); 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" && context.nodeType === 9 && !documentIsXML && 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 for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; 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, slice.call( seed, 0 ) ); 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, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; 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 ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, 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; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < self.length; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < this.length; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( jQuery.unique( ret ) ); ret.selector = ( this.selector ? this.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, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // 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". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, 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++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } 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) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; 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 ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, 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, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } 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 ); }, 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(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, 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, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { 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( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent && this.nodeType === 1 || this.nodeType === 11 ) { jQuery( this ).remove(); if ( next ) { next.parentNode.insertBefore( elem, next ); } else { parent.appendChild( elem ); } } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, 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, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); 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( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : 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.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + 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, data, e; // 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 !== "undefined" ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== "undefined" ? 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, srcElements, node, i, clone, 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 contains, elem, tag, tmp, wrap, tbody, j, 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 data, id, elem, type, 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 !== "undefined" ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var curCSS, getStyles, iframe, 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 elem, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.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 ] && !isHidden( elem ) ) { jQuery._data( elem, "olddisplay", 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 styles, len, 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 ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : 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; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": 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 val, num, 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 ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations 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; } }); // 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 ) { 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)$/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 ); } } 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 key, deep, 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, type, response, 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.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 }); }; }); 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.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 transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // 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; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // 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 not modified if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.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; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // 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 function ajaxConvert( s, response ) { var conv, conv2, current, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current 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.splice( i--, 0, current ); } 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 }; } } } } // Update prev for next iteration prev = 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, statusText, responseHeaders, responses, xml; // 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; xml = xhr.responseXML; responseHeaders = xhr.getAllResponseHeaders(); // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // 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 end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 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 ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } 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; } } createTweens( animation, props ); 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 index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // 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.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // 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 ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); 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 a non 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, "auto" ); // 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; } } } }; // Remove in 2.0 - this supports IE8's 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 ); doAnimation.finish = function() { anim.stop( true ); }; // 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.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // 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 !== "undefined" ) { 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 || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // 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() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use 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.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); (function(e,t){var n=function(){function r(t,r){if(t=="dot"){r='<ol class="dots">';e.each(n.li,function(e){r+='<li class="'+(e==n.i?t+" active":t)+'">'+ ++e+"</li>"});r+="</ol>"}else{r='<div class="';r=r+t+'s">'+r+t+' prev">'+n.o.prev+"</div>"+r+t+' next">'+n.o.next+"</div></div>"}n.el.addClass("has-"+t+"s").append(r).find("."+t).click(function(){var t=e(this);t.hasClass("dot")?n.stop().to(t.index()):t.hasClass("prev")?n.prev():n.next()})}var n=this;n.o={speed:500,delay:3e3,init:0,pause:!t,loop:!t,keys:t,dots:t,arrows:t,prev:"←",next:"→",fluid:t,starting:t,complete:t,items:">ul",item:">li",easing:"swing",autoplay:true};n.init=function(t,i){n.o=e.extend(n.o,i);n.el=t;n.ul=t.find(n.o.items);n.max=[t.outerWidth()|0,t.outerHeight()|0];n.li=n.ul.find(n.o.item).each(function(t){var r=e(this),i=r.outerWidth(),s=r.outerHeight();if(i>n.max[0])n.max[0]=i;if(s>n.max[1])n.max[1]=s});var i=n.o,s=n.ul,o=n.li,u=o.length;n.i=0;t.css({width:n.max[0],height:o.first().outerHeight(),overflow:"hidden"});s.css({position:"relative",left:0,width:u*100+"%"});o.css({"float":"left",width:n.max[0]+"px"});i.autoplay&&setTimeout(function(){if(i.delay|0){n.play();if(i.pause){t.on("mouseover mouseout",function(e){n.stop();e.type=="mouseout"&&n.play()})}}},i.init|0);if(i.keys){e(document).keydown(function(e){var t=e.which;if(t==37)n.prev();else if(t==39)n.next();else if(t==27)n.stop()})}i.dots&&r("dot");i.arrows&&r("arrow");if(i.fluid){e(window).resize(function(){n.r&&clearTimeout(n.r);n.r=setTimeout(function(){var e={height:o.eq(n.i).outerHeight()},r=t.outerWidth();s.css(e);e["width"]=Math.min(Math.round(r/t.parent().width()*100),100)+"%";t.css(e)},50)}).resize()}if(e.event.special["swipe"]||e.Event("swipe")){t.on("swipeleft swiperight swipeLeft swipeRight",function(e){e.type.toLowerCase()=="swipeleft"?n.next():n.prev()})}return n};n.to=function(r,i){if(n.t){n.stop();n.play()}var s=n.o,o=n.el,u=n.ul,a=n.li,l=n.i,c=a.eq(r);e.isFunction(s.starting)&&!i&&s.starting(o,a.eq(l));if((!c.length||r<0)&&s.loop==t)return;if(!c.length)r=0;if(r<0)r=a.length-1;c=a.eq(r);var h=i?5:s.speed|0,p=s.easing,d={height:c.outerHeight()};if(!u.queue("fx").length){o.find(".dot").eq(r).addClass("active").siblings().removeClass("active");o.animate(d,h,p)&&u.animate(e.extend({left:"-"+r+"00%"},d),h,p,function(t){n.i=r;e.isFunction(s.complete)&&!i&&s.complete(o,c)})}};n.play=function(){n.t=setInterval(function(){n.to(n.i+1)},n.o.delay|0)};n.stop=function(){n.t=clearInterval(n.t);return n};n.next=function(){return n.stop().to(n.i+1)};n.prev=function(){return n.stop().to(n.i-1)};};e.fn.unslider=function(t){var r=this.length;return this.each(function(i){var s=e(this),u="unslider"+(r>1?"-"+ ++i:""),a=(new n).init(s,t);s.data(u,a).data("key",u)})};n.version="1.0.0"})(jQuery,false) (function(g){g.html5={};g.html5.version="6.8.4616"})(jwplayer); (function(g){var h=document;g.parseDimension=function(a){return"string"==typeof a?""===a?0:-1<a.lastIndexOf("%")?a:parseInt(a.replace("px",""),10):a};g.timeFormat=function(a){if(0<a){var c=Math.floor(a/3600),e=Math.floor((a-3600*c)/60);a=Math.floor(a%60);return(c?c+":":"")+(10>e?"0":"")+e+":"+(10>a?"0":"")+a}return"00:00"};g.bounds=function(a){var c={left:0,right:0,width:0,height:0,top:0,bottom:0};if(!a||!h.body.contains(a))return c;if(a.getBoundingClientRect){a=a.getBoundingClientRect(a);var e=window.pageYOffset, b=window.pageXOffset;if(!a.width&&!a.height&&!a.left&&!a.top)return c;c.left=a.left+b;c.right=a.right+b;c.top=a.top+e;c.bottom=a.bottom+e;c.width=a.right-a.left;c.height=a.bottom-a.top}else{c.width=a.offsetWidth|0;c.height=a.offsetHeight|0;do c.left+=a.offsetLeft|0,c.top+=a.offsetTop|0;while(a=a.offsetParent);c.right=c.left+c.width;c.bottom=c.top+c.height}return c};g.empty=function(a){if(a)for(;0<a.childElementCount;)a.removeChild(a.children[0])}})(jwplayer.utils); (function(g){function h(a,b,c){if(!e.exists(b))return"";c=c?" !important":"";return isNaN(b)?b.match(/png|gif|jpe?g/i)&&0>b.indexOf("url")?"url("+b+")":b+c:0===b||"z-index"===a||"opacity"===a?""+b+c:/color/i.test(a)?"#"+e.pad(b.toString(16).replace(/^0x/i,""),6)+c:Math.ceil(b)+"px"+c}function a(a,b){for(var c=0;c<a.length;c++){var d=a[c],e,f;for(e in b){f=e;f=f.split("-");for(var h=1;h<f.length;h++)f[h]=f[h].charAt(0).toUpperCase()+f[h].slice(1);f=f.join("");d.style[f]!==b[e]&&(d.style[f]=b[e])}}} function c(a){var c=b[a].sheet,d,e,h;if(c){d=c.cssRules;e=l[a];h=a;var u=f[h];h+=" { ";for(var m in u)h+=m+": "+u[m]+"; ";h+="}";if(void 0!==e&&e<d.length&&d[e].selectorText===a){if(h===d[e].cssText)return;c.deleteRule(e)}else e=d.length,l[a]=e;c.insertRule(h,e)}}var e=g.utils,b={},d,f={},u=null,l={},m=e.css=function(a,e,l){f[a]||(f[a]={});var j=f[a];l=l||!1;var m=!1,g,w;for(g in e)w=h(g,e[g],l),""!==w?w!==j[g]&&(j[g]=w,m=!0):void 0!==j[g]&&(delete j[g],m=!0);if(m){if(!b[a]){if(!d||5E4<d.sheet.cssRules.length)e= document.createElement("style"),e.type="text/css",document.getElementsByTagName("head")[0].appendChild(e),d=e;b[a]=d}null!==u?u.styleSheets[a]=f[a]:c(a)}};m.style=function(b,c,d){if(!(void 0===b||null===b)){void 0===b.length&&(b=[b]);var e={},f;for(f in c)e[f]=h(f,c[f]);if(null!==u&&!d){c=(c=b.__cssRules)||{};for(var l in e)c[l]=e[l];b.__cssRules=c;0>u.elements.indexOf(b)&&u.elements.push(b)}else a(b,e)}};m.block=function(a){null===u&&(u={id:a,styleSheets:{},elements:[]})};m.unblock=function(b){if(u&& (!b||u.id===b)){for(var d in u.styleSheets)c(d);for(b=0;b<u.elements.length;b++)d=u.elements[b],a(d,d.__cssRules);u=null}};e.clearCss=function(a){for(var d in f)0<=d.indexOf(a)&&delete f[d];for(var e in b)0<=e.indexOf(a)&&c(e)};e.transform=function(a,b){var c={};b=b||"";c.transform=b;c["-webkit-transform"]=b;c["-ms-transform"]=b;c["-moz-transform"]=b;c["-o-transform"]=b;"string"===typeof a?m(a,c):m.style(a,c)};e.dragStyle=function(a,b){m(a,{"-webkit-user-select":b,"-moz-user-select":b,"-ms-user-select":b, "-webkit-user-drag":b,"user-select":b,"user-drag":b})};e.transitionStyle=function(a,b){navigator.userAgent.match(/5\.\d(\.\d)? safari/i)||m(a,{"-webkit-transition":b,"-moz-transition":b,"-o-transition":b,transition:b})};e.rotate=function(a,b){e.transform(a,"rotate("+b+"deg)")};e.rgbHex=function(a){a=String(a).replace("#","");3===a.length&&(a=a[0]+a[0]+a[1]+a[1]+a[2]+a[2]);return"#"+a.substr(-6)};e.hexToRgba=function(a,b){var c="rgb",d=[parseInt(a.substr(1,2),16),parseInt(a.substr(3,2),16),parseInt(a.substr(5, 2),16)];void 0!==b&&100!==b&&(c+="a",d.push(b/100));return c+"("+d.join(",")+")"};m(".jwplayer ".slice(0,-1)+" div span a img ul li video".split(" ").join(", .jwplayer ")+", .jwclick",{margin:0,padding:0,border:0,color:"#000000","font-size":"100%",font:"inherit","vertical-align":"baseline","background-color":"transparent","text-align":"left",direction:"ltr","-webkit-tap-highlight-color":"rgba(255, 255, 255, 0)"});m(".jwplayer ul",{"list-style":"none"})})(jwplayer); (function(g){var h=g.stretching={NONE:"none",FILL:"fill",UNIFORM:"uniform",EXACTFIT:"exactfit"};g.scale=function(a,c,e,b,d){var f="";c=c||1;e=e||1;b|=0;d|=0;if(1!==c||1!==e)f="scale("+c+", "+e+")";if(b||d)f="translate("+b+"px, "+d+"px)";g.transform(a,f)};g.stretch=function(a,c,e,b,d,f){if(!c||!e||!b||!d||!f)return!1;a=a||h.UNIFORM;var u=2*Math.ceil(e/2)/d,l=2*Math.ceil(b/2)/f,m="video"===c.tagName.toLowerCase(),r=!1,n="jw"+a.toLowerCase();switch(a.toLowerCase()){case h.FILL:u>l?l=u:u=l;r=!0;break; case h.NONE:u=l=1;case h.EXACTFIT:r=!0;break;default:u>l?0.95<d*l/e?(r=!0,n="jwexactfit"):(d*=l,f*=l):0.95<f*u/b?(r=!0,n="jwexactfit"):(d*=u,f*=u),r&&(u=2*Math.ceil(e/2)/d,l=2*Math.ceil(b/2)/f)}m?(a={left:"",right:"",width:"",height:""},r?(e<d&&(a.left=a.right=Math.ceil((e-d)/2)),b<f&&(a.top=a.bottom=Math.ceil((b-f)/2)),a.width=d,a.height=f,g.scale(c,u,l,0,0)):(r=!1,g.transform(c)),g.css.style(c,a)):c.className=c.className.replace(/\s*jw(none|exactfit|uniform|fill)/g,"")+" "+n;return r}})(jwplayer.utils); (function(g){g.dfxp=function(){var h=jwplayer.utils.seconds;this.parse=function(a){var c=[{begin:0,text:""}];a=a.replace(/^\s+/,"").replace(/\s+$/,"");var e=a.split("\x3c/p\x3e"),b=a.split("\x3c/tt:p\x3e"),d=[];for(a=0;a<e.length;a++)0<=e[a].indexOf("\x3cp")&&(e[a]=e[a].substr(e[a].indexOf("\x3cp")+2).replace(/^\s+/,"").replace(/\s+$/,""),d.push(e[a]));for(a=0;a<b.length;a++)0<=b[a].indexOf("\x3ctt:p")&&(b[a]=b[a].substr(b[a].indexOf("\x3ctt:p")+5).replace(/^\s+/,"").replace(/\s+$/,""),d.push(b[a])); e=d;for(a=0;a<e.length;a++){b=e[a];d={};try{var f=b.indexOf('begin\x3d"'),b=b.substr(f+7),f=b.indexOf('" end\x3d"');d.begin=h(b.substr(0,f));b=b.substr(f+7);f=b.indexOf('"');d.end=h(b.substr(0,f));f=b.indexOf('"\x3e');b=b.substr(f+2);d.text=b}catch(u){}b=d;b.text&&(c.push(b),b.end&&(c.push({begin:b.end,text:""}),delete b.end))}if(1<c.length)return c;throw{message:"Invalid DFXP file:"};}}})(jwplayer.parsers); (function(g){g.srt=function(){var h=jwplayer.utils,a=h.seconds;this.parse=function(c,e){var b=e?[]:[{begin:0,text:""}];c=h.trim(c);var d=c.split("\r\n\r\n");1==d.length&&(d=c.split("\n\n"));for(var f=0;f<d.length;f++)if("WEBVTT"!=d[f]){var u,l=d[f];u={};var m=l.split("\r\n");1==m.length&&(m=l.split("\n"));try{l=1;0<m[0].indexOf(" --\x3e ")&&(l=0);var r=m[l].indexOf(" --\x3e ");0<r&&(u.begin=a(m[l].substr(0,r)),u.end=a(m[l].substr(r+5)));if(m[l+1]){u.text=m[l+1];for(l+=2;l<m.length;l++)u.text+="\x3cbr/\x3e"+ m[l]}}catch(n){}u.text&&(b.push(u),u.end&&!e&&(b.push({begin:u.end,text:""}),delete u.end))}if(1<b.length)return b;throw{message:"Invalid SRT file"};}}})(jwplayer.parsers); (function(g){var h=g.utils,a=h.css,c=!0,e=!1,b=g.events,d=80,f=30;g.html5.adskipbutton=function(u,l,m,r){function n(a){if(!(0>p)){var b=v.getContext("2d");b.clearRect(0,0,d,f);w(b,0,0,d,f,5,c,e,e);w(b,0,0,d,f,5,e,c,e);b.fillStyle="#979797";b.globalAlpha=1;var k=v.width/2,j=v.height/2;b.textAlign="center";b.font="Bold 11px Sans-Serif";b.fillText(m.replace(/xx/gi,Math.ceil(p-a)),k,j+4)}}function g(a,b){if("number"==h.typeOf(F))p=F;else if("%"==F.slice(-1)){var c=parseFloat(F.slice(0,-1));b&&!isNaN(c)&& (p=b*c/100)}else"string"==h.typeOf(F)?p=h.seconds(F):isNaN(F)||(p=F)}function j(){k&&x.sendEvent(b.JWPLAYER_AD_SKIPPED)}function q(){if(k){var a=v.getContext("2d");a.clearRect(0,0,d,f);w(a,0,0,d,f,5,c,e,c);w(a,0,0,d,f,5,e,c,c);a.fillStyle="#FFFFFF";a.globalAlpha=1;var b=v.height/2,j=v.width/2;a.textAlign="center";a.font="Bold 12px Sans-Serif";a.fillText(r+" ",j,b+4);a.drawImage(A,v.width-(v.width-a.measureText(r).width)/2-4,(f-s.height)/2)}}function C(){if(k){var a=v.getContext("2d");a.clearRect(0, 0,d,f);w(a,0,0,d,f,5,c,e,e);w(a,0,0,d,f,5,e,c,e);a.fillStyle="#979797";a.globalAlpha=1;var b=v.height/2,j=v.width/2;a.textAlign="center";a.font="Bold 12px Sans-Serif";a.fillText(r+" ",j,b+4);a.drawImage(s,v.width-(v.width-a.measureText(r).width)/2-4,(f-s.height)/2)}}function w(a,b,d,e,k,j,f,h,r){"undefined"==typeof h&&(h=c);"undefined"===typeof j&&(j=5);a.beginPath();a.moveTo(b+j,d);a.lineTo(b+e-j,d);a.quadraticCurveTo(b+e,d,b+e,d+j);a.lineTo(b+e,d+k-j);a.quadraticCurveTo(b+e,d+k,b+e-j,d+k);a.lineTo(b+ j,d+k);a.quadraticCurveTo(b,d+k,b,d+k-j);a.lineTo(b,d+j);a.quadraticCurveTo(b,d,b+j,d);a.closePath();h&&(a.strokeStyle="white",a.globalAlpha=r?1:0.25,a.stroke());f&&(a.fillStyle="#000000",a.globalAlpha=0.5,a.fill())}function t(a,b){var c=document.createElement(a);b&&(c.className=b);return c}var D,v,x=new b.eventdispatcher,p=-1,k=e,B,F=0,s,A;h.extend(this,x);this.updateSkipTime=function(b,l){var u=v.getContext("2d");g(b,l);if(0<=p)if(a.style(D,{visibility:B?"visible":"hidden"}),0<p-b)n(b);else if(!k){k= c;u.clearRect(0,0,d,f);w(u,0,0,d,f,5,c,e,e);w(u,0,0,d,f,5,e,c);u.fillStyle="#979797";u.globalAlpha=1;var m=v.height/2,x=v.width/2;u.textAlign="center";u.font="Bold 12px Sans-Serif";u.fillText(r+" ",x,m+4);u.drawImage(s,v.width-(v.width-u.measureText(r).width)/2-4,(f-s.height)/2);h.isMobile()?(new h.touch(D)).addEventListener(h.touchEvents.TAP,j):(D.addEventListener("click",j),D.addEventListener("mouseover",q),D.addEventListener("mouseout",C));D.style.cursor="pointer"}};this.reset=function(a){k= !1;F=a;g(0,0);n(0)};this.show=function(){B=!0;0<p&&a.style(D,{visibility:"visible"})};this.hide=function(){B=!1;a.style(D,{visibility:"hidden"})};this.element=function(){return D};s=new Image;s.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAICAYAAAArzdW1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3NpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo0ODkzMWI3Ny04YjE5LTQzYzMtOGM2Ni0wYzdkODNmZTllNDYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDI0OTcxRkE0OEM2MTFFM0I4MTREM0ZBQTFCNDE3NTgiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDI0OTcxRjk0OEM2MTFFM0I4MTREM0ZBQTFCNDE3NTgiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NDA5ZGQxNDktNzdkMi00M2E3LWJjYWYtOTRjZmM2MWNkZDI0IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjQ4OTMxYjc3LThiMTktNDNjMy04YzY2LTBjN2Q4M2ZlOWU0NiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PqAZXX0AAABYSURBVHjafI2BCcAwCAQ/kr3ScRwjW+g2SSezCi0kYHpwKLy8JCLDbWaGTM+MAFzuVNXhNiTQsh+PS9QhZ7o9JuFMeUVNwjsamDma4K+3oy1cqX/hxyPAAAQwNKV27g9PAAAAAElFTkSuQmCC"; s.className="jwskipimage jwskipout";A=new Image;A.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAICAYAAAArzdW1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3NpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDo0ODkzMWI3Ny04YjE5LTQzYzMtOGM2Ni0wYzdkODNmZTllNDYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RDI0OTcxRkU0OEM2MTFFM0I4MTREM0ZBQTFCNDE3NTgiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RDI0OTcxRkQ0OEM2MTFFM0I4MTREM0ZBQTFCNDE3NTgiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NDA5ZGQxNDktNzdkMi00M2E3LWJjYWYtOTRjZmM2MWNkZDI0IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjQ4OTMxYjc3LThiMTktNDNjMy04YzY2LTBjN2Q4M2ZlOWU0NiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PvgIj/QAAABYSURBVHjadI6BCcAgDAS/0jmyih2tm2lHSRZJX6hQQ3w4FP49LKraSHV3ZLDzAuAi3cwaqUhSfvft+EweznHneUdTzPGRmp5hEJFhAo3LaCnjn7blzCvAAH9YOSCL5RZKAAAAAElFTkSuQmCC"; A.className="jwskipimage jwskipover";D=t("div","jwskip");D.id=u.id+"_skipcontainer";v=t("canvas");D.appendChild(v);this.width=v.width=d;this.height=v.height=f;D.appendChild(A);D.appendChild(s);a.style(D,{visibility:"hidden",bottom:l})};a(".jwskip",{position:"absolute","float":"right",display:"inline-block",width:d,height:f,right:10});a(".jwskipimage",{position:"relative",display:"none"})})(window.jwplayer); (function(g){var h=g.utils,a=g.events,c=a.state,e=g.parsers,b=h.css,d="playing",f=document;g.html5.captions=function(b,l){function m(a){h.log("CAPTIONS("+a+")")}function r(a){(H=a.fullscreen)?(n(),setTimeout(n,500)):C(!0)}function n(){var a=x.offsetHeight,b=x.offsetWidth;0!==a&&0!==b&&B.resize(b,Math.round(0.94*a))}function z(a,b){h.ajax(a,function(a){var c=a.responseXML?a.responseXML.firstChild:null;K++;if(c){"xml"==e.localName(c)&&(c=c.nextSibling);for(;c.nodeType==c.COMMENT_NODE;)c=c.nextSibling}c= c&&"tt"==e.localName(c)?new g.parsers.dfxp:new g.parsers.srt;try{var d=c.parse(a.responseText);s<A.length&&(A[b].data=d);C(!1)}catch(k){m(k.message+": "+A[b].file)}K==A.length&&(0<I&&(t(I),I=-1),q())},j,!0)}function j(a){K++;m(a);K==A.length&&(0<I&&(t(I),I=-1),q())}function q(){for(var b=[],c=0;c<A.length;c++)b.push(A[c]);P.sendEvent(a.JWPLAYER_CAPTIONS_LOADED,{captionData:b})}function C(a){!A.length||Q?B.hide():F==d&&0<G?(B.show(),H?r({fullscreen:!0}):(w(),a&&setTimeout(w,500))):B.hide()}function w(){B.resize()} function t(b){0<b?(s=b-1,G=b,s>=A.length||(A[s].data?B.populate(A[s].data):K==A.length?(m("file not loaded: "+A[s].file),0!=G&&D(a.JWPLAYER_CAPTIONS_CHANGED,A,0),G=0):I=b,C(!1))):(G=0,C(!1))}function D(a,b,c){P.sendEvent(a,{type:a,tracks:b,track:c})}function v(){for(var a=[{label:"Off"}],b=0;b<A.length;b++)a.push({label:A[b].label});return a}var x,p={back:!0,color:"#FFFFFF",fontSize:15,fontFamily:"Arial,sans-serif",fontOpacity:100,backgroundColor:"#000",backgroundOpacity:100,edgeStyle:null,windowColor:"#FFFFFF", windowOpacity:0},k={fontStyle:"normal",fontWeight:"normal",textDecoration:"none"},B,F,s,A=[],K=0,I=-1,G=0,H=!1,P=new a.eventdispatcher,Q=h.isAndroid(4)&&!h.isChrome();h.extend(this,P);this.element=function(){return x};this.getCaptionsList=function(){return v()};this.getCurrentCaptions=function(){return G};this.setCurrentCaptions=function(b){0<=b&&(G!=b&&b<=A.length)&&(t(b),b=v(),h.saveCookie("captionLabel",b[G].label),D(a.JWPLAYER_CAPTIONS_CHANGED,b,G))};x=f.createElement("div");x.id=b.id+"_caption"; x.className="jwcaptions";b.jwAddEventListener(a.JWPLAYER_PLAYER_STATE,function(a){switch(a.newstate){case c.IDLE:F="idle";C(!1);break;case c.PLAYING:F=d,C(!1)}});b.jwAddEventListener(a.JWPLAYER_PLAYLIST_ITEM,function(){s=0;A=[];B.update(0);K=0;if(!Q){for(var c=b.jwGetPlaylist()[b.jwGetPlaylistIndex()].tracks,d=[],e=0,k="",j=0,k="",e=0;e<c.length;e++)k=c[e].kind.toLowerCase(),("captions"==k||"subtitles"==k)&&d.push(c[e]);for(e=G=0;e<d.length;e++)if(k=d[e].file)d[e].label||(d[e].label=e.toString()), A.push(d[e]),z(A[e].file,e);for(e=0;e<A.length;e++)if(A[e]["default"]){j=e+1;break}if(k=h.getCookies().captionLabel){c=v();for(e=0;e<c.length;e++)if(k==c[e].label){j=e;break}}0<j&&t(j);C(!1);D(a.JWPLAYER_CAPTIONS_LIST,v(),G)}});b.jwAddEventListener(a.JWPLAYER_MEDIA_ERROR,m);b.jwAddEventListener(a.JWPLAYER_ERROR,m);b.jwAddEventListener(a.JWPLAYER_READY,function(){h.foreach(p,function(a,b){l&&(void 0!==l[a]?b=l[a]:void 0!==l[a.toLowerCase()]&&(b=l[a.toLowerCase()]));k[a]=b});B=new g.html5.captions.renderer(k, x);C(!1)});b.jwAddEventListener(a.JWPLAYER_MEDIA_TIME,function(a){B.update(a.position)});b.jwAddEventListener(a.JWPLAYER_FULLSCREEN,r);b.jwAddEventListener(a.JWPLAYER_RESIZE,function(){C(!1)})};b(".jwcaptions",{position:"absolute",cursor:"pointer",width:"100%",height:"100%",overflow:"hidden"})})(jwplayer); (function(g){var h=g.utils,a=h.css.style;g.html5.captions.renderer=function(c,e){function b(b){b=b||"";q="hidden";a(m,{visibility:q});n.innerHTML=b;b.length&&(q="visible",setTimeout(d,16))}function d(){if("visible"===q){var b=m.clientWidth,d=Math.pow(b/400,0.6),e=c.fontSize*d;a(n,{maxWidth:b+"px",fontSize:Math.round(e)+"px",lineHeight:Math.round(1.4*e)+"px",padding:Math.round(1*d)+"px "+Math.round(8*d)+"px"});c.windowOpacity&&a(r,{padding:Math.round(5*d)+"px",borderRadius:Math.round(5*d)+"px"});a(m, {visibility:q})}}function f(){for(var a=-1,c=0;c<l.length;c++)if(l[c].begin<=j&&(c==l.length-1||l[c+1].begin>=j)){a=c;break}-1==a?b(""):a!=g&&(g=a,b(l[c].text))}function u(a,b,c){c=h.hexToRgba("#000000",c);"dropshadow"===a?b.textShadow="0 2px 1px "+c:"raised"===a?b.textShadow="0 0 5px "+c+", 0 1px 5px "+c+", 0 2px 5px "+c:"depressed"===a?b.textShadow="0 -2px 1px "+c:"uniform"===a&&(b.textShadow="-2px 0 1px "+c+",2px 0 1px "+c+",0 -2px 1px "+c+",0 2px 1px "+c+",-1px 1px 1px "+c+",1px 1px 1px "+c+",1px -1px 1px "+ c+",1px 1px 1px "+c)}var l,m,r,n,g,j,q="visible",C=-1;this.hide=function(){clearInterval(C);a(m,{display:"none"})};this.populate=function(a){g=-1;l=a;f()};this.resize=function(){d()};this.show=function(){a(m,{display:"block"});d();clearInterval(C);C=setInterval(d,250)};this.update=function(a){j=a;l&&f()};var w=c.fontOpacity,t=c.windowOpacity,D=c.edgeStyle,v=c.backgroundColor,x={display:"inline-block"},p={color:h.hexToRgba(h.rgbHex(c.color),w),display:"inline-block",fontFamily:c.fontFamily,fontStyle:c.fontStyle, fontWeight:c.fontWeight,textAlign:"center",textDecoration:c.textDecoration,wordWrap:"break-word"};t&&(x.backgroundColor=h.hexToRgba(h.rgbHex(c.windowColor),t));u(D,p,w);c.back?p.backgroundColor=h.hexToRgba(h.rgbHex(v),c.backgroundOpacity):null===D&&u("uniform",p);m=document.createElement("div");r=document.createElement("div");n=document.createElement("span");a(m,{display:"block",height:"auto",position:"absolute",bottom:"20px",textAlign:"center",width:"100%"});a(r,x);a(n,p);r.appendChild(n);m.appendChild(r); e.appendChild(m)}})(jwplayer); (function(g){var h=g.html5,a=g.utils,c=g.events,e=c.state,b=a.css,d=a.transitionStyle,f=a.isMobile(),u=a.isAndroid(4)&&!a.isChrome(),l="button",m="text",r="slider",n="none",z="100%",j={display:n},q={display:"block"},C={display:x},w="array",t=!1,D=!0,v=null,x,p=window,k=document;h.controlbar=function(d,F){function s(a,b,c){return{name:a,type:b,className:c}}function A(c){b.block($);if(c.duration==Number.POSITIVE_INFINITY||!c.duration&&a.isSafari()&&!f)Z.setText(J.jwGetPlaylist()[J.jwGetPlaylistIndex()].title||"Live broadcast"); else{var d;E.elapsed&&(d=a.timeFormat(c.position),E.elapsed.innerHTML=d);E.duration&&(d=a.timeFormat(c.duration),E.duration.innerHTML=d);0<c.duration?X(c.position/c.duration):X(0);va=c.duration;wa||Z.setText()}}function K(){var a=J.jwGetMute();Ka=J.jwGetVolume()/100;S("mute",a||0===Ka);V(a?0:Ka)}function I(){b.style(E.hd,j);b.style(E.cc,j);Pa();sa()}function G(a){Qa=a.currentQuality|0;E.hd&&(E.hd.querySelector("button").className=2===fa.length&&0===Qa?"off":"");ma&&0<=Qa&&ma.setActive(a.currentQuality)} function H(a){ga&&(La=a.track|0,E.cc&&(E.cc.querySelector("button").className=2===ga.length&&0===La?"off":""),na&&0<=La&&na.setActive(a.track))}function P(){la=a.extend({},Xa,oa.getComponentSettings("controlbar"),F);xa=N("background").height;var c=ta?0:la.margin;b.style(W,{height:xa,bottom:c,left:c,right:c,"max-width":ta?"":la.maxwidth});b(Q(".jwtext"),{font:la.fontsize+"px/"+N("background").height+"px "+la.font,color:la.fontcolor,"font-weight":la.fontweight});b(Q(".jwoverlay"),{bottom:xa})}function Q(a){return"#"+ $+(a?" "+a:"")}function M(){return k.createElement("span")}function y(c,d,e,j,k){var f=M(),h=N(c);j=j?" left center":" center";var r=aa(h);f.className="jw"+c;f.innerHTML="\x26nbsp;";if(h&&h.src)return e=e?{background:"url('"+h.src+"') repeat-x "+j,"background-size":r,height:k?h.height:x}:{background:"url('"+h.src+"') no-repeat"+j,"background-size":r,width:h.width,height:k?h.height:x},f.skin=h,b(Q((k?".jwvertical ":"")+".jw"+c),a.extend(e,d)),E[c]=f}function R(a,c,d,e){c&&c.src&&(b(a,{width:c.width, background:"url("+c.src+") no-repeat center","background-size":aa(c)}),d.src&&!f&&b(a+":hover,"+a+".off:hover",{background:"url("+d.src+") no-repeat center","background-size":aa(d)}),e&&e.src&&b(a+".off",{background:"url("+e.src+") no-repeat center","background-size":aa(e)}))}function T(a){return function(b){rb[a]&&(rb[a](),f&&Ma.sendEvent(c.JWPLAYER_USER_ACTION));b.preventDefault&&b.preventDefault()}}function ca(b){a.foreach(gb,function(a,c){a!=b&&("cc"==a&&(clearTimeout(Da),Da=x),"hd"==a&&(clearTimeout(Ea), Ea=x),c.hide())})}function ba(){!ta&&!wa&&(b.block($),Ha.show(),Ca("volume",Ha),ca("volume"))}function S(b,c){a.exists(c)||(c=!hb[b]);E[b]&&(E[b].className="jw"+b+(c?" jwtoggle jwtoggling":" jwtoggling"),setTimeout(function(){E[b].className=E[b].className.replace(" jwtoggling","")},100));hb[b]=c}function aa(a){return a?parseInt(a.width,10)+"px "+parseInt(a.height,10)+"px":"0 0"}function Y(){fa&&2<fa.length&&(ib&&(clearTimeout(ib),ib=x),b.block($),ma.show(),Ca("hd",ma),ca("hd"))}function qa(){ga&& 2<ga.length&&(jb&&(clearTimeout(jb),jb=x),b.block($),na.show(),Ca("cc",na),ca("cc"))}function da(a){0<=a&&a<fa.length&&(J.jwSetCurrentQuality(a),clearTimeout(Ea),Ea=x,ma.hide())}function Ra(a){0<=a&&a<ga.length&&(J.jwSetCurrentCaptions(a),clearTimeout(Da),Da=x,na.hide())}function ha(){2==ga.length&&Ra((La+1)%2)}function kb(){2==fa.length&&da((Qa+1)%2)}function Ia(a){a.preventDefault();k.onselectstart=function(){return t}}function Ya(a){Sa();ya=a;p.addEventListener("mouseup",O,t)}function Sa(){p.removeEventListener("mouseup", O);ya=v}function Ta(){E.timeRail.className="jwrail";J.jwGetState()!=e.IDLE&&(J.jwSeekDrag(D),Ya("time"),za(),Ma.sendEvent(c.JWPLAYER_USER_ACTION))}function Na(b){if(ya){var d=(new Date).getTime();50<d-lb&&(Za(b),lb=d);var e=E[ya].querySelector(".jwrail"),e=a.bounds(e),e=b.x/e.width;100<e&&(e=100);b.type==a.touchEvents.DRAG_END?(J.jwSeekDrag(t),E.timeRail.className="jwrail jwsmooth",Sa(),$a.time(e),ua()):(X(e),500<d-mb&&(mb=d,$a.time(e)));Ma.sendEvent(c.JWPLAYER_USER_ACTION)}}function U(b){var d=E.time.querySelector(".jwrail"), d=a.bounds(d);b=b.x/d.width;100<b&&(b=100);J.jwGetState()!=e.IDLE&&($a.time(b),Ma.sendEvent(c.JWPLAYER_USER_ACTION))}function L(a){return function(b){b.button||(E[a+"Rail"].className="jwrail","time"==a?J.jwGetState()!=e.IDLE&&(J.jwSeekDrag(D),Ya(a)):Ya(a))}}function O(b){var c=(new Date).getTime();50<c-lb&&(Za(b),lb=c);if(ya&&!b.button){var d=E[ya].querySelector(".jwrail"),e=a.bounds(d),d=ya,e=E[d].vertical?(e.bottom-b.pageY)/e.height:(b.pageX-e.left)/e.width;"mouseup"==b.type?("time"==d&&J.jwSeekDrag(t), E[d+"Rail"].className="jwrail jwsmooth",Sa(),$a[d.replace("H","")](e)):("time"==ya?X(e):V(e),500<c-mb&&(mb=c,$a[ya.replace("H","")](e)));return!1}}function za(){pa&&(va&&!ta&&!f)&&(b.block($),pa.show(),Ca("time",pa))}function ua(){pa&&pa.hide()}function Za(b){ia=a.bounds(W);if((ab=a.bounds(sb))&&0!==ab.width){var c=b.x;b.pageX&&(c=b.pageX-ab.left);0<=c&&c<=ab.width&&(pa.positionX(Math.round(c)),Oa(va*c/ab.width))}}function Oa(c){var d=bb.updateTimeline(c,function(a){b.style(pa.element(),{width:a}); Ca("time",pa)});Ua?(c=Ua.text)&&b.style(pa.element(),{width:32<c.length?160:""}):(c=a.timeFormat(c),d||b.style(pa.element(),{width:""}));cb.innerHTML!==c&&(cb.innerHTML=c);Ca("time",pa)}function Aa(){a.foreach(db,function(a,c){var d={};d.left=-1<c.position.toString().search(/^[\d\.]+%$/)?c.position:(100*c.position/va).toFixed(2)+"%";b.style(c.element,d)})}function nb(){jb=setTimeout(na.hide,500)}function ja(){ib=setTimeout(ma.hide,500)}function ra(a,c,d,e){if(!f){var j=a.element();c.appendChild(j); c.addEventListener("mousemove",d,t);e?c.addEventListener("mouseout",e,t):c.addEventListener("mouseout",a.hide,t);b.style(j,{left:"50%"})}}function eb(b,d,e,j){if(f){var k=b.element();d.appendChild(k);(new a.touch(d)).addEventListener(a.touchEvents.TAP,function(){var a=e;"cc"==j?(2==ga.length&&(a=ha),Da?(clearTimeout(Da),Da=x,b.hide()):(Da=setTimeout(function(){b.hide();Da=x},4E3),a()),Ma.sendEvent(c.JWPLAYER_USER_ACTION)):"hd"==j&&(2==fa.length&&(a=kb),Ea?(clearTimeout(Ea),Ea=x,b.hide()):(Ea=setTimeout(function(){b.hide(); Ea=x},4E3),a()),Ma.sendEvent(c.JWPLAYER_USER_ACTION))})}}function Va(c){var d=M();d.className="jwgroup jw"+c;Fa[c]=d;if(Ga[c]){var d=Ga[c],e=Fa[c];if(d&&0<d.elements.length)for(var I=0;I<d.elements.length;I++){var p;a:{p=d.elements[I];var g=c;switch(p.type){case m:g=void 0;p=p.name;var g={},G=N(("alt"==p?"elapsed":p)+"Background");if(G.src){var q=M();q.id=$+"_"+p;"elapsed"==p||"duration"==p?(q.className="jwtext jw"+p+" jwhidden",pb.push(q)):q.className="jwtext jw"+p;g.background="url("+G.src+") repeat-x center"; g["background-size"]=aa(N("background"));b.style(q,g);q.innerHTML="alt"!=p?"00:00":"";g=E[p]=q}else g=null;p=g;break a;case l:if("blank"!=p.name){p=p.name;G=g;if(!N(p+"Button").src||f&&("mute"==p||0===p.indexOf("volume"))||u&&/hd|cc/.test(p))p=v;else{var g=M(),q=M(),A=void 0,A=ka,s=y(A.name);s||(s=M(),s.className="jwblankDivider");A.className&&(s.className+=" "+A.className);A=s;s=k.createElement("button");g.style+=" display:inline-block";g.className="jw"+p+" jwbuttoncontainer";"left"==G?(g.appendChild(q), g.appendChild(A)):(g.appendChild(A),g.appendChild(q));f?"hd"!=p&&"cc"!=p&&(new a.touch(s)).addEventListener(a.touchEvents.TAP,T(p)):s.addEventListener("click",T(p),t);s.innerHTML="\x26nbsp;";q.appendChild(s);G=N(p+"Button");q=N(p+"ButtonOver");A=N(p+"ButtonOff");R(Q(".jw"+p+" button"),G,q,A);(G=xb[p])&&R(Q(".jw"+p+".jwtoggle button"),N(G+"Button"),N(G+"ButtonOver"));p=E[p]=g}break a}break;case r:g=void 0;A=p.name;if(f&&0===A.indexOf("volume"))g=void 0;else{p=M();var q="volume"==A,w=A+("time"==A?"Slider": "")+"Cap",G=q?"Top":"Left",g=q?"Bottom":"Right",s=y(w+G,v,t,t,q),B=y(w+g,v,t,t,q),C;C=A;var H=q,D=G,Ka=g,ha=M(),K=["Rail","Buffer","Progress"],F=void 0,ca=void 0;ha.className="jwrail jwsmooth";for(var da=0;da<K.length;da++){var ca="time"==C?"Slider":"",P=C+ca+K[da],Y=y(P,v,!H,0===C.indexOf("volume"),H),ba=y(P+"Cap"+D,v,t,t,H),J=y(P+"Cap"+Ka,v,t,t,H),S=N(P+"Cap"+D),O=N(P+"Cap"+Ka);if(Y){var ia=M();ia.className="jwrailgroup "+K[da];ba&&ia.appendChild(ba);ia.appendChild(Y);J&&(ia.appendChild(J),J.className+= " jwcap"+(H?"Bottom":"Right"));b(Q(".jwrailgroup."+K[da]),{"min-width":H?x:S.width+O.width});ia.capSize=H?S.height+O.height:S.width+O.width;b(Q("."+Y.className),{left:H?x:S.width,right:H?x:O.width,top:H?S.height:x,bottom:H?O.height:x,height:H?"auto":x});2==da&&(F=ia);2==da&&!H?(Y=M(),Y.className="jwprogressOverflow",Y.appendChild(ia),E[P]=Y,ha.appendChild(Y)):(E[P]=ia,ha.appendChild(ia))}}if(D=y(C+ca+"Thumb",v,t,t,H))b(Q("."+D.className),{opacity:"time"==C?0:1,"margin-top":H?D.skin.height/-2:x}), D.className+=" jwthumb",(H&&F?F:ha).appendChild(D);f?(H=new a.touch(ha),H.addEventListener(a.touchEvents.DRAG_START,Ta),H.addEventListener(a.touchEvents.DRAG,Na),H.addEventListener(a.touchEvents.DRAG_END,Na),H.addEventListener(a.touchEvents.TAP,U)):(F=C,"volume"==F&&!H&&(F+="H"),ha.addEventListener("mousedown",L(F),t));"time"==C&&!f&&(ha.addEventListener("mousemove",za,t),ha.addEventListener("mouseout",ua,t));C=E[C+"Rail"]=ha;ha=N(w+G);w=N(w+G);p.className="jwslider jw"+A;s&&p.appendChild(s);p.appendChild(C); B&&(q&&(B.className+=" jwcapBottom"),p.appendChild(B));b(Q(".jw"+A+" .jwrail"),{left:q?x:ha.width,right:q?x:w.width,top:q?ha.height:x,bottom:q?w.height:x,width:q?z:x,height:q?"auto":x});E[A]=p;p.vertical=q;"time"==A?(pa=new h.overlay($+"_timetooltip",oa),bb=new h.thumbs($+"_thumb"),cb=k.createElement("div"),cb.className="jwoverlaytext",ob=k.createElement("div"),g=bb.element(),ob.appendChild(g),ob.appendChild(cb),pa.setContents(ob),sb=C,Oa(0),g=pa.element(),C.appendChild(g),E.timeSliderRail||b.style(E.time, j),E.timeSliderThumb&&b.style(E.timeSliderThumb,{"margin-left":N("timeSliderThumb").width/-2}),g=N("timeSliderCue"),G={"z-index":1},g&&g.src?(y("timeSliderCue"),G["margin-left"]=g.width/-2):G.display=n,b(Q(".jwtimeSliderCue"),G),Ja(0),X(0),X(0),Ja(0)):0===A.indexOf("volume")&&(A=p,s="volume"+(q?"":"H"),B=q?"vertical":"horizontal",b(Q(".jw"+s+".jw"+B),{width:N(s+"Rail",q).width+(q?0:N(s+"Cap"+G).width+N(s+"RailCap"+G).width+N(s+"RailCap"+g).width+N(s+"Cap"+g).width),height:q?N(s+"Cap"+G).height+N(s+ "Rail").height+N(s+"RailCap"+G).height+N(s+"RailCap"+g).height+N(s+"Cap"+g).height:x}),A.className+=" jw"+B);g=p}p=g;break a}p=void 0}p&&("volume"==d.elements[I].name&&p.vertical?(Ha=new h.overlay($+"_volumeOverlay",oa),Ha.setContents(p)):e.appendChild(p))}}}function sa(){clearTimeout(tb);tb=setTimeout(Z.redraw,0)}function Pa(){1<J.jwGetPlaylist().length&&(!k.querySelector("#"+J.id+" .jwplaylist")||J.jwGetFullscreen())?(b.style(E.next,C),b.style(E.prev,C)):(b.style(E.next,j),b.style(E.prev,j))}function Ca(b, c){ia||(ia=a.bounds(W));c.constrainX(ia,!0)}function Ja(a){E.timeSliderBuffer&&(a=Math.min(Math.max(0,a),1),b.style(E.timeSliderBuffer,{width:(100*a).toFixed(1)+"%",opacity:0<a?1:0}))}function Ba(a,c){if(E[a]){var d=E[a].vertical,e=a+("time"===a?"Slider":""),j=100*Math.min(Math.max(0,c),1)+"%",k=E[e+"Progress"],e=E[e+"Thumb"],f;k&&(f={},d?(f.height=j,f.bottom=0):f.width=j,"volume"!==a&&(f.opacity=0<c||ya?1:0),b.style(k,f));e&&(f={},d?f.top=0:f.left=j,b.style(e,f))}}function V(a){Ba("volume",a);Ba("volumeH", a)}function X(a){Ba("time",a)}function N(a){var b="controlbar",c=a;0===a.indexOf("volume")&&(0===a.indexOf("volumeH")?c=a.replace("volumeH","volume"):b="tooltip");return(a=oa.getSkinElement(b,c))?a:{width:0,height:0,src:"",image:x,ready:t}}function ea(b){b=(new g.parsers.srt).parse(b.responseText,!0);if(a.typeOf(b)!==w)return fb("Invalid data");Z.addCues(b)}function fb(b){a.log("Cues failed to load: "+b)}var J,oa,ka=s("divider","divider"),Xa={margin:8,maxwidth:800,font:"Arial,sans-serif",fontsize:11, fontcolor:15658734,fontweight:"bold",layout:{left:{position:"left",elements:[s("play",l),s("prev",l),s("next",l),s("elapsed",m)]},center:{position:"center",elements:[s("time",r),s("alt",m)]},right:{position:"right",elements:[s("duration",m),s("hd",l),s("cc",l),s("mute",l),s("volume",r),s("volumeH",r),s("fullscreen",l)]}}},la,Ga,E,xa,W,$,va,fa,Qa,ga,La,Ka,Ha,ia,sb,ab,pa,ob,bb,cb,ib,Ea,ma,jb,Da,na,tb,Wa=-1,ta=t,qb=t,ya=v,mb=0,lb=0,db=[],Ua,wa=t,Ma=new c.eventdispatcher,xb={play:"pause",mute:"unmute", fullscreen:"normalscreen"},hb={play:t,mute:t,fullscreen:t},rb={play:function(){hb.play?J.jwPause():J.jwPlay()},mute:function(){var a=!hb.mute;J.jwSetMute(a);!a&&0===Ka&&J.jwSetVolume(20);K()},fullscreen:function(){J.jwSetFullscreen()},next:function(){J.jwPlaylistNext()},prev:function(){J.jwPlaylistPrev()},hd:kb,cc:ha},$a={time:function(a){J.jwSeek(Ua?Ua.position:a*va)},volume:function(a){V(a);0.1>a&&(a=0);0.9<a&&(a=1);J.jwSetVolume(100*a)}},gb={},pb=[],Z=this;a.extend(Z,Ma);Z.setText=function(a){b.block($); var c=E.alt,d=E.time;E.timeSliderRail?b.style(d,a?j:q):b.style(d,j);c&&(b.style(c,a?q:j),c.innerHTML=a||"");sa()};var Fa={};Z.redraw=function(c){b.block($);c&&Z.visible&&Z.show(D);P();c=top!==window.self&&a.isMSIE();b.style(E.fullscreen,{display:ta||qb||c?n:""});b(Q(".jwvolumeH"),{display:ta||wa?"block":n});b(Q(".jwmute .jwoverlay"),{display:!ta&&!wa?"block":n});b.style(E.hd,{display:!ta&&!wa&&fa&&1<fa.length&&ma?"":n});b.style(E.cc,{display:!ta&&!wa&&ga&&1<ga.length&&na?"":n});Aa();b.unblock($); if(Z.visible){c=N("capLeft");var d=N("capRight");c={left:Math.round(a.parseDimension(Fa.left.offsetWidth)+c.width),right:Math.round(a.parseDimension(Fa.right.offsetWidth)+d.width)};b.style(Fa.center,c)}};Z.audioMode=function(a){a!=ta&&(ta=a,sa())};Z.instreamMode=function(a){a!=wa&&(wa=a)};Z.hideFullscreen=function(a){a!=qb&&(qb=a,sa())};Z.element=function(){return W};Z.margin=function(){return parseInt(la.margin,10)};Z.height=function(){return xa};Z.show=function(c){if(!Z.visible||c){Z.visible=!0; c={display:"inline-block"};var d=la.maxwidth|0;!ta&&d&&(W.parentNode&&a.isIETrident())&&(c.width=W.parentNode.clientWidth>d+(la.margin|0)?d:"");b.style(W,c);ia=a.bounds(W);W&&E.alt&&(W.parentNode&&320<=W.parentNode.clientWidth?b.style(pb,C):b.style(pb,j));b.block($);K();sa();clearTimeout(Wa);Wa=-1;Wa=setTimeout(function(){b.style(W,{opacity:1})},0)}};Z.showTemp=function(){this.visible||(W.style.opacity=0,W.style.display="inline-block")};Z.hideTemp=function(){this.visible||(W.style.display=n)};Z.addCues= function(b){a.foreach(b,function(a,b){if(b.text){var c=b.begin,d=b.text;if(0<=c.toString().search(/^[\d\.]+%?$/)){var e=y("timeSliderCue"),j=E.timeSliderRail,k={position:c,text:d,element:e};e&&j&&(j.appendChild(e),e.addEventListener("mouseover",function(){Ua=k},!1),e.addEventListener("mouseout",function(){Ua=v},!1),db.push(k))}Aa()}})};Z.hide=function(){Z.visible&&(Z.visible=!1,b.style(W,{opacity:0}),clearTimeout(Wa),Wa=-1,Wa=setTimeout(function(){b.style(W,{display:n})},250))};E={};J=d;$=J.id+"_controlbar"; va=0;W=M();W.id=$;W.className="jwcontrolbar";oa=J.skin;Ga=oa.getComponentLayout("controlbar");Ga||(Ga=Xa.layout);a.clearCss(Q());b.block($+"build");P();var ub=y("capLeft"),vb=y("capRight"),wb=y("background",{position:"absolute",left:N("capLeft").width,right:N("capRight").width,"background-repeat":"repeat-x"},D);wb&&W.appendChild(wb);ub&&W.appendChild(ub);Va("left");Va("center");Va("right");W.appendChild(Fa.left);W.appendChild(Fa.center);W.appendChild(Fa.right);E.hd&&(ma=new h.menu("hd",$+"_hd",oa, da),f?eb(ma,E.hd,Y,"hd"):ra(ma,E.hd,Y,ja),gb.hd=ma);E.cc&&(na=new h.menu("cc",$+"_cc",oa,Ra),f?eb(na,E.cc,qa,"cc"):ra(na,E.cc,qa,nb),gb.cc=na);E.mute&&(E.volume&&E.volume.vertical)&&(Ha=new h.overlay($+"_volumeoverlay",oa),Ha.setContents(E.volume),ra(Ha,E.mute,ba),gb.volume=Ha);b.style(Fa.right,{right:N("capRight").width});vb&&W.appendChild(vb);b.unblock($+"build");J.jwAddEventListener(c.JWPLAYER_MEDIA_TIME,A);J.jwAddEventListener(c.JWPLAYER_PLAYER_STATE,function(a){switch(a.newstate){case e.BUFFERING:case e.PLAYING:E.timeSliderThumb&& b.style(E.timeSliderThumb,{opacity:1});S("play",D);break;case e.PAUSED:ya||S("play",t);break;case e.IDLE:S("play",t),E.timeSliderThumb&&b.style(E.timeSliderThumb,{opacity:0}),E.timeRail&&(E.timeRail.className="jwrail",setTimeout(function(){E.timeRail.className+=" jwsmooth"},100)),Ja(0),A({position:0,duration:0})}});J.jwAddEventListener(c.JWPLAYER_PLAYLIST_ITEM,function(b){if(!wa){b=J.jwGetPlaylist()[b.index].tracks;var c=t,d=E.timeSliderRail;a.foreach(db,function(a,b){d.removeChild(b.element)});db.length= 0;if(a.typeOf(b)==w&&!f)for(var e=0;e<b.length;e++)if(!c&&(b[e].file&&b[e].kind&&"thumbnails"==b[e].kind.toLowerCase())&&(bb.load(b[e].file),c=D),b[e].file&&b[e].kind&&"chapters"==b[e].kind.toLowerCase()){var j=b[e].file;j?a.ajax(j,ea,fb,D):db.length=0}c||bb.load()}});J.jwAddEventListener(c.JWPLAYER_MEDIA_MUTE,K);J.jwAddEventListener(c.JWPLAYER_MEDIA_VOLUME,K);J.jwAddEventListener(c.JWPLAYER_MEDIA_BUFFER,function(a){Ja(a.bufferPercent/100)});J.jwAddEventListener(c.JWPLAYER_FULLSCREEN,function(a){S("fullscreen", a.fullscreen);Pa();Z.visible&&Z.show(D)});J.jwAddEventListener(c.JWPLAYER_PLAYLIST_LOADED,I);J.jwAddEventListener(c.JWPLAYER_MEDIA_LEVELS,function(a){fa=a.levels;if(!wa&&fa&&1<fa.length&&ma){b.style(E.hd,C);ma.clearOptions();for(var c=0;c<fa.length;c++)ma.addOption(fa[c].label,c);G(a)}else b.style(E.hd,j);sa()});J.jwAddEventListener(c.JWPLAYER_MEDIA_LEVEL_CHANGED,G);J.jwAddEventListener(c.JWPLAYER_CAPTIONS_LIST,function(a){ga=a.tracks;if(!wa&&ga&&1<ga.length&&na){b.style(E.cc,C);na.clearOptions(); for(var c=0;c<ga.length;c++)na.addOption(ga[c].label,c);H(a)}else b.style(E.cc,j);sa()});J.jwAddEventListener(c.JWPLAYER_CAPTIONS_CHANGED,H);J.jwAddEventListener(c.JWPLAYER_RESIZE,function(){ia=a.bounds(W);0<ia.width&&Z.show(D)});f||(W.addEventListener("mouseover",function(){p.addEventListener("mousemove",O,t);p.addEventListener("mousedown",Ia,t)},!1),W.addEventListener("mouseout",function(){p.removeEventListener("mousemove",O);p.removeEventListener("mousedown",Ia);k.onselectstart=null},!1));setTimeout(K, 0);I();Z.visible=!1};b("span.jwcontrolbar",{position:"absolute",margin:"auto",opacity:0,display:n});b("span.jwcontrolbar span",{height:z});a.dragStyle("span.jwcontrolbar span",n);b("span.jwcontrolbar .jwgroup",{display:"inline"});b("span.jwcontrolbar span, span.jwcontrolbar .jwgroup button,span.jwcontrolbar .jwleft",{position:"relative","float":"left"});b("span.jwcontrolbar .jwright",{position:"relative","float":"right"});b("span.jwcontrolbar .jwcenter",{position:"absolute"});b("span.jwcontrolbar buttoncontainer,span.jwcontrolbar button", {display:"inline-block",height:z,border:n,cursor:"pointer"});b("span.jwcontrolbar .jwcapRight,span.jwcontrolbar .jwtimeSliderCapRight,span.jwcontrolbar .jwvolumeCapRight",{right:0,position:"absolute"});b("span.jwcontrolbar .jwcapBottom",{bottom:0,position:"absolute"});b("span.jwcontrolbar .jwtime",{position:"absolute",height:z,width:z,left:0});b("span.jwcontrolbar .jwthumb",{position:"absolute",height:z,cursor:"pointer"});b("span.jwcontrolbar .jwrail",{position:"absolute",cursor:"pointer"});b("span.jwcontrolbar .jwrailgroup", {position:"absolute",width:z});b("span.jwcontrolbar .jwrailgroup span",{position:"absolute"});b("span.jwcontrolbar .jwdivider+.jwdivider",{display:n});b("span.jwcontrolbar .jwtext",{padding:"0 5px","text-align":"center"});b("span.jwcontrolbar .jwalt",{display:n,overflow:"hidden"});b("span.jwcontrolbar .jwalt",{position:"absolute",left:0,right:0,"text-align":"left"},D);b("span.jwcontrolbar .jwoverlaytext",{padding:3,"text-align":"center"});b("span.jwcontrolbar .jwvertical *",{display:"block"});b("span.jwcontrolbar .jwvertical .jwvolumeProgress", {height:"auto"},D);b("span.jwcontrolbar .jwprogressOverflow",{position:"absolute",overflow:"hidden"});d("span.jwcontrolbar","opacity .25s, background .25s, visibility .25s");d("span.jwcontrolbar button","opacity .25s, background .25s, visibility .25s");d("span.jwcontrolbar .jwtime .jwsmooth span","opacity .25s, background .25s, visibility .25s, width .25s linear, left .05s linear");d("span.jwcontrolbar .jwtoggling",n)})(window.jwplayer); (function(g){var h=g.utils,a=g.events,c=a.state,e=g.playlist,b=!0,d=!1;g.html5.controller=function(f,u){function l(){return f.getVideo()}function m(a){x.sendEvent(a.type,a)}function r(c){z(b);switch(h.typeOf(c)){case "string":var d=new e.loader;d.addEventListener(a.JWPLAYER_PLAYLIST_LOADED,function(a){r(a.playlist)});d.addEventListener(a.JWPLAYER_ERROR,function(a){r([]);a.message="Could not load playlist: "+a.message;m(a)});d.load(c);break;case "object":case "array":v.setPlaylist(new g.playlist(c)); break;case "number":v.setItem(c)}}function n(e){h.exists(e)||(e=b);if(!e)return j();try{0<=k&&(r(k),k=-1);if(!B&&(B=b,x.sendEvent(a.JWPLAYER_MEDIA_BEFOREPLAY),B=d,A)){A=d;F=null;return}if(v.state==c.IDLE){if(0===v.playlist.length)return d;l().load(v.playlist[v.item])}else v.state==c.PAUSED&&l().play();return b}catch(f){x.sendEvent(a.JWPLAYER_ERROR,f),F=null}return d}function z(e){F=null;try{return v.state!=c.IDLE?l().stop():e||(s=b),B&&(A=b),b}catch(j){x.sendEvent(a.JWPLAYER_ERROR,j)}return d}function j(e){F= null;h.exists(e)||(e=b);if(!e)return n();try{switch(v.state){case c.PLAYING:case c.BUFFERING:l().pause();break;default:B&&(A=b)}return b}catch(j){x.sendEvent(a.JWPLAYER_ERROR,j)}return d}function q(a){h.css.block(v.id+"_next");r(a);n();h.css.unblock(v.id+"_next")}function C(){q(v.item+1)}function w(){v.state==c.IDLE&&(s?s=d:(F=w,v.repeat?C():v.item==v.playlist.length-1?(k=0,z(b),setTimeout(function(){x.sendEvent(a.JWPLAYER_PLAYLIST_COMPLETE)},0)):C()))}function t(a){return function(){p?D(a,arguments): K.push({method:a,arguments:arguments})}}function D(a,b){var c=[],d;for(d=0;d<b.length;d++)c.push(b[d]);a.apply(this,c)}var v=f,x=new a.eventdispatcher(v.id,v.config.debug),p=d,k=-1,B,F,s=d,A,K=[];h.extend(this,x);this.play=t(n);this.pause=t(j);this.seek=t(function(a){v.state!=c.PLAYING&&n(b);l().seek(a)});this.stop=function(){s=b;t(z)()};this.load=t(r);this.next=t(C);this.prev=t(function(){q(v.item-1)});this.item=t(q);this.setVolume=t(v.setVolume);this.setMute=t(v.setMute);this.setFullscreen=t(function(a){u.fullscreen(a)}); this.detachMedia=function(){try{return v.getVideo().detachMedia()}catch(a){return null}};this.attachMedia=function(a){try{v.getVideo().attachMedia(a),"function"==typeof F&&F()}catch(b){return null}};this.setCurrentQuality=t(function(a){l().setCurrentQuality(a)});this.getCurrentQuality=function(){return l()?l().getCurrentQuality():-1};this.getQualityLevels=function(){return l()?l().getQualityLevels():null};this.setCurrentCaptions=t(function(a){u.setCurrentCaptions(a)});this.getCurrentCaptions=function(){return u.getCurrentCaptions()}; this.getCaptionsList=function(){return u.getCaptionsList()};this.checkBeforePlay=function(){return B};this.playerReady=function(a){if(!p){u.completeSetup();x.sendEvent(a.type,a);g.utils.exists(window.jwplayer.playerReady)&&g.playerReady(a);v.addGlobalListener(m);u.addGlobalListener(m);x.sendEvent(g.events.JWPLAYER_PLAYLIST_LOADED,{playlist:g(v.id).getPlaylist()});x.sendEvent(g.events.JWPLAYER_PLAYLIST_ITEM,{index:v.item});r();v.autostart&&!h.isMobile()&&n();for(p=b;0<K.length;)a=K.shift(),D(a.method, a.arguments)}};v.addEventListener(a.JWPLAYER_MEDIA_BUFFER_FULL,function(){l().play()});v.addEventListener(a.JWPLAYER_MEDIA_COMPLETE,function(){setTimeout(w,25)});v.addEventListener(a.JWPLAYER_MEDIA_ERROR,function(b){b=h.extend({},b);b.type=a.JWPLAYER_ERROR;x.sendEvent(b.type,b)})}})(jwplayer); (function(g){g.html5.defaultskin=function(){this.text='\x3c?xml version\x3d"1.0" ?\x3e\x3cskin author\x3d"JW Player" name\x3d"Six" target\x3d"6.7" version\x3d"3.0"\x3e\x3ccomponents\x3e\x3ccomponent name\x3d"controlbar"\x3e\x3csettings\x3e\x3csetting name\x3d"margin" value\x3d"10"/\x3e\x3csetting name\x3d"maxwidth" value\x3d"800"/\x3e\x3csetting name\x3d"fontsize" value\x3d"11"/\x3e\x3csetting name\x3d"fontweight" value\x3d"normal"/\x3e\x3csetting name\x3d"fontcase" value\x3d"normal"/\x3e\x3csetting name\x3d"fontcolor" value\x3d"0xd2d2d2"/\x3e\x3c/settings\x3e\x3celements\x3e\x3celement name\x3d"background" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAeCAYAAADtlXTHAAAAN0lEQVR42mMQFRW/x2RiYqLI9O3bNwam////MzAxAAESARQCsf6jcmFiOLkIoxAGEGIBmSAHAQBWYyX2FoQvwgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"capLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAeCAYAAAARgF8NAAAAtElEQVR42tWRQQrCMBBFvzDJRltcmDTURYO3kHoK71K8hGfxFh7DnS2atXSRpozbViwVRNS3frw/MMTM0NpYADsAOYAZOpDWZgXgEMfxwlqrpJSyJwAooihSWZalbduirms8CnmSJCqEgGcQgJkQQmAAwgivCcyjBf78xLs3/MUEM3/9WT9QuDVNE4gEDQlH564mTZdqSNh779dVVU6U0nMi6pXIuctJa7P13hdled4AmHaFO61WQkab+AHPAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"capRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAeCAYAAAARgF8NAAAAtklEQVR42tWTMQrCUBBE35evhX2UYJGTeACx8y4eQvRW6jWSVBJ/BCXEFMmStRISNKQSdWCrnZ0ZdlnjedOQNnLgCGycS2KzWCy12S3LsozjOM2y7AKsbFEUrXFjzCgIglkUReR5vh6oKs2q6xoRwff9CTAf0AFr7RAYdxKe6CVY1R4C6Ict+hX6MvyHhap++1g/rSBSCVB0KpzPyRXYv2xSRCRN3a2qqhOwM2+e9w4cgK1zSfgA16hp3sNEmiwAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"playButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAeCAYAAAA2Lt7lAAABIklEQVR42u3VoWqFUBjAcWFpaWn11qULew8RmQg+wnwAH0NBQYPFcosXdooYTH7FZhIEDQoaDIJJVDQ5bTeIHO8UFjzwR9sPPcdPYhxH4siIEziB/YFpvU69T71NvRAbFw5wybLsJgjC93T/sRXCAa5VVcEwDBCG4c9WCAf4zPMc5sqyhL7vN0FYQJIk8FhRFNB1HRaEBURRBEvNT9W27SqEBQRBAGulaQpN0yxCWIDv+4BTHMdQ1/V8vWua9jUfcSzA8zzYkm3bd0mSGGzAdV3AyTAMxHEcv/kVOY4Da+m6jliW5Z/eZMuyYClVVRHDMPyfjylCCB6TZRnRNM3v9aFdTdOEOVEUEUVR/N6j4qIoyo0kSf6oYXfsuD5/mSfw/4BfzM60PxpdNhsAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"playButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAeCAYAAAA2Lt7lAAABIklEQVR42u3VoWqFUBjAccPi4uIe4D7A4g3rIoIIvsRd8ymmgoIGi9liEYPJZDMJgm4o6MCJYBIVTd+03SByzqaw4IE/2n7oOX4SAEAcGXECJ7A/MK/Huee5p7kHAnOhAJc8zz94nn+f719wIRTg2jQNTNMEURR940IowGtRFLBU1zWM44gFIQFpmsJ9ZVnCMAxIEBIQxzGstTxV3/ebEBIQhiFslWUZdF23CiEBQRAASkmSQNu2y7XQNO22HHEkwPd9wMlxnC9Jkt6QAc/zACXDMCqO4wTsV+S6Lmyl63rFsqzw6022bRvWUlW1YhhG+PMxtSwL7pNluaJpWtjrQ7uapglLoihWFEUJe4+Ki6IonyRJCkcNu2PH9fnLPIH/B/wA5fzQF959z6UAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"pauseButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAeCAYAAAA2Lt7lAAAAmUlEQVR42u2WTQoCMQxGX8RlDzAX9FRezXXxAN30B+KmIDilmQHLKNNsCt8jPAg0RFSVkXVhcE3BCQTXVigiDlgAV6MAPOtLzVdcVcMmAbCo6v1DegMeG7kpcN77VbaDmwJKKd3ZWtwU5Jy7jRY/XpBS6jZa/HhBjLHbaPETjGi44O//QWisgrCDv5dg66r45rqWebZMwe8LXlPydRVUwjqdAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"pauseButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAeCAYAAAA2Lt7lAAAAn0lEQVR42u2VSwrFIAxFr9AFuIRuoftxz+0SOnLs1A/cN3H0WhILlVJqJkIO4ZCIcSKJnjGhcwzBVwXGGAtgBmBrKgDY64maP3CSobWDmeT6J10AbI1cFVjv/SF3get3UEoRZ6txVZBzFgs1/rwgpSQWavx5QYxRLNT4B0bUXfD6dxBOVkG4wFXB7pxbTtZ1K5cFda9vQucaH3/yENwYP2sBdLsTPIMJAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"prevButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAeCAYAAAAhDE4sAAAA6UlEQVR42mP4//8/AzUww6hBowYNaoOAgAeIJaA0OmAGYn4gFgViTkIGqQDp/SAaiwHqJSUl6Q8ePFgMZMsRMsjg0aNHIIMM0A24cuXKmh8/fux/+fIlSF6XoEG3bt0CKbRHNuDbt2/7Hz9+vB8kB5U3IGjQ+fPn96enp5feuHFj5efPn/ffvn17P0gMGRNl0JEjR/YnJSWVbdmyZSWIjQ0TZdCuXbvgXgsNDc2YPXv2WpAYMibKoPXr12MEdkBAQMbEiRPXguSg8gQDW2X58uU4o9/X1zdj8uTJREU/dRLkaO4fNWhYGAQACIKTdMKw1gUAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"prevButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAeCAYAAAAhDE4sAAAA6UlEQVR42mP4//8/AzUww6hBowYNaoOAQACIFaA0OmABYhEglgFiHkIGGfyHMAywGGBSUlLS9eDBg5tAtgYhgxwePXoEYjigG3DlypVnP378+P/y5UuQvA1Bg27dugVihCAb8O3bt/+PHz/+D5KDyjsQNOj8+fP/09PT59y4cePh58+f/9++ffs/SAwZE2XQkSNH/iclJc3dsmXLIxAbGybKoF27dsG9Fhoa2j179uznIDFkTJRB69evxwjsgICA7okTJz4HyUHlCQa2wfLly3FGv6+vb/fkyZNvERP91EmQo7l/1KBhYRAAuDSgTOE1ffsAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"nextButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAeCAYAAADKO/UvAAAA6klEQVR42mP4//8/A6WYYdSQUUMGxBAg4ARiUSDmB2JmBkzAA8QSIBqfIXIPHjxYXFJSkg5kq2MxTAWobj+UxmmI7suXL/f/+PFj/5UrV9ZgMczg0aNHIEMM8BlicOvWrf0g/Pjx4/3fvn1DN8weJEfQkPPnz+9Hxrdv397/+fPn/Tdu3FiZnp5eChIjaMiRI0f2Y8NbtmxZmZSUVAZiEzRk165d+5Hx7Nmz14aGhmbAvAMSI2SI7vr16/eD8MSJE9cGBARkoAcsSI6QIXKTJ09e7Ovrm4EripcvX04wiilPbKO5eNSQQW8IAG8yOc7bkjJcAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"nextButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAeCAYAAADKO/UvAAAA6klEQVR42mP4//8/A6WYYdSQUUMGxBAg4AFiGSAWAWIWBkwgAMQKIBqfIRoPHjy4WVJS0gVkm2AxzOA/RKEBPkNsXr58+f/Hjx//r1y58gyLYQ6PHj0CKXTAZ4jDrVu3/oPw48eP/3/79g3dsBCQHEFDzp8//x8Z3759+//nz5//37hx42F6evockBhBQ44cOfIfG96yZcujpKSkuSA2QUN27dr1HxnPnj37eWhoaDfMOyAxQobYrF+//j8IT5w48XlAQEA3esCC5AgZojF58uRbvr6+3biiePny5QSjmPLENpqLRw0Z9IYAAGB2RqagdTNIAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"elapsedBackground" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAeCAYAAAAPSW++AAAAFklEQVR42mP4//8/AzbMMCoxKjHcJAArFxoDYgoNvgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"durationBackground" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAeCAYAAAAPSW++AAAAFklEQVR42mP4//8/AzbMMCoxKjHcJAArFxoDYgoNvgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"timeSliderCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAeCAYAAADpYKT6AAAAFElEQVR42mP4//8/AwwzjHIGhgMAcFgNAkNCQTAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"timeSliderCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAeCAYAAADpYKT6AAAAFElEQVR42mP4//8/AwwzjHIGhgMAcFgNAkNCQTAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"timeSliderRail" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAeCAYAAADtlXTHAAAAM0lEQVR42pWNIRLAIADD0vrJwv9f2gkONJhcokJbDFyDZNbJwLYPhKWdkpaRzNL242X0A7ayDBvOWGKEAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"timeSliderRailCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAoUlEQVR42t3RTQrCMBCG4SwKgrhttaSkFAppS9Mk/VEPoTvBC7nyUIpnKq4/JwGDeANdPJt3MZMhDAD7xv4ixvH6SG5kfocL5wJlKVHXrQ+HLBNoGoW21R5Lks1dyhpdZwMXZ60tjOkDH40ZYO0YsDTlDzdvGLYBq6rmJESBvp8wjjvPPSnK8+JKoJTGNO3DFQsKZzeKdjw/z4vIkqx++o9eChh4OrGutekAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"timeSliderRailCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAqElEQVR42t3RTQrCMBCG4VkIgritWlpaCoW2oc1Pf9RD6E48kSsPpXim6vpzphAX3kAXz+ZNMiSEANA3+ukYBOuR3djhE6uqRp4XiKIEvHCZYl0bCKUaxPG0cCStHbyiUFitNneytoVnjJM4knM9PGs7iU/qui08mRuG0YP6fgfRtgOSJENZqhMNwx5NY5CmmbjylWbEM15yRGt75jD3z1yyhez4iz96A9GweD4LqeZmAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"timeSliderBuffer" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAeCAYAAADtlXTHAAAALUlEQVR42mP+//8/A3NDQwOJxNy58/8zCwkJNyARwsJglgiIBSPevn3TSLrxAICJLIFssC4FAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"timeSliderBufferCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAbElEQVR42mP8//8/AzpgHL6CMjJyvoyMDJlAIVuwoKysvA8TE9NCRkZGISCGqJSXV9wKFPQCC8AElZRUPgEFeVHMVFFR/QRUgSqoqqq+Dcj2RBFUU9PwBbIXALEQipOAEn5ACugkBlvGkREdAE2UZQboCcvbAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"timeSliderBufferCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAaUlEQVR42t3QuxGAIBBFUfoA+S1oM1KudkUi5s8VwXEcKzC4yXlLggAg3on/oVK6KDUsUg7zjdZ6GOOgtc18kCp6H+Ac4Rx5WCsSRfR43CqGENEjCqXhiEfX8xgntDKXOu7c2uGnP/+FB8gXjGr6cT/xAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"timeSliderProgress" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAeCAYAAADtlXTHAAAALklEQVR42p3MsQ0AQAjDQCv7z8gakCo0LPDfnFyZJAh4J6oqZBt19zEzV7bhb792VRs5A8JlWAAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"timeSliderProgressCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAYklEQVR42mP8//8/AzpgHNaCvkCcCcS2MEGfb9++Lfz48aPQz58/ISpfv3699c2bN14o2s+dO/cJyOZFETx69Cim4N69e7cB2Z4oglu2bAHZvACIhVCctHbtWj90Jw3z6AAAdAV63jcCcQsAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"timeSliderProgressCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAeCAYAAADkftS9AAAAZUlEQVR42t3QIQ7AIAyFYQ44boojQ1VisVgcggQzhn5ryraQ7QaIz/xJ85IqAOpLLRkb29n2xpQScs7ovVcOWmKMEY9SipMYQsDkkOi9x6RJJCJMxrm1FrfKxpAx5mSO6bU//3MBeArIus+/eXoAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"timeSliderThumb" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAeCAYAAAAl+Z4RAAABm0lEQVR42u2UTUsCURSGJ0kNV1MghjuhVhYEbSPoY5WbWhV90pd/SfwPulDc6c6vvYrjQl2kLdQ/IDhwe8/wTsQ04ZSbFg48Mtzzvsdzz71nNKWUtgjaMsF/SOB4VoAPrIIAWCMBrvmocX0k6Afr4BBcgRdyCQ4Y81P7zRwEO+CpUCjkJpPJ0DTNmTAejweyhtgjNcGvSWzzLkh2u11jNBqpXq+nDMOw6Pf7CkmUxERD7WcSKSki/9xqtYxOp6Pa7bYrEhONaMEmvVoIHGUymfxPRifZbDYPzzG9mg6ua7XawGuCer0+hOeGXi0snW42mzOvCbCNGTyv9Fp7+VWCRqMxheeZXuvntlKpeN5CtVodwHPH5ltlnKXTac9NFC08CXsL0oi4lFQsFo15ZtGw/LjdRDmKqBylXJJSqWTMMSepjdrH6GemGDiVhqZSqRz2+Y5um2jutFwuv8ka5+KEWt2+SPZV3mBgH1yABx6VcA/OGYtR6zoPOkvb5tDsEXnfYkx3mp3jHKIozCOO8F1nzHWc//5BWX6VF0/wATCN7PmY+qrmAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"timeSliderCue" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAeCAYAAAAl+Z4RAAAAfElEQVR42mP4//8/AyWYYdSAUQOGuQGiouJZQHwEirNIMgCkwcbG7klra/tvEAaxcRmCy4Aj1dV1v3Nz8/+DMIgNEiPJgLS0jN+ZmTn/QRjEBoodJckLRkYmT5KSUn8nJqb8BrGBYtmkBmI2yFYgPgTEmaMpcdSAUQPwYwAtmWpcwU8bfwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"hdButtonOff" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAeCAYAAADQBxWhAAABiElEQVR42u2Vu0oDQRSGF1SwiIVCspfZnb1rEcxFCOmNzdb2PoIvpCCxEyJYqdU+gbVtKmMeQavx/KMDg4I4GxACU/wcZjL/+ebMzNk4Qgjnv+VYqIVa6HpC2223Ii1IYgXBX5lAF0HARBjyxoIfeUygIo5TkSQZmUO5c8TvY70yzwskDGsg+DFvBE3TXGRZoYw7jIWPnCcCEWM1D9V1vTcajSvX9edRFEsf/MZQGBWU5Pg+eyAJRIzVPOmS9ESw8XB4dIKKda8RNM9LKZW81xtMut3DM0QdSpB7xiJBVd5Mp9dbNPeme42gRVFKqeR0h+cEuEDUoag8ijhO4I7GG6R33WsI3ZfSK8JDQdShtIkrqvKZTgFtNsHx6l4jaFkeSOkVcR7/uFNavz2b3e7Sho5pPMdj072NoLgv1SK4p99aBi8XFTaCdjreK3oNRtwNXiKASIioXifaAus+2yuXvykg5inP8s/Qfn9wCsMqn0HyvyCPyQd/k9RSzd9Qra889q/NQi10DaEfbVCWtJniLegAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"hdButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAeCAYAAADQBxWhAAABwklEQVR4nO2Uz0oCURTGXZigT+Br+ALiKyi4UAMJDAaEFkGLVrkM3BjkQiSFGElE0IUIIgrCLERUEkFJyD+ghLS1aVWn88kEg7i4KcwiRvhxzvngOx/cuV4LEVmMxvBAM9QM/Weh/DthnIyLcTOeA3Brfuw5EQl1xmKx+HK5VDebDR0K/NiDfSKhrul0qq5WKxgPBn7swT6RUPdisaDZbHY02IN9IqGeyWRCeli7y+fza/SomDX9mjmz2+2Xfr//UVEUdY/XIxQ6HA5JD2vnlUplgh4Vs6aHa7Wa0u/33wKBwK3X633Y4xUL7Xa7pIe1QCQSuZEk6QkVs6ZHi8XifDAYULlcHlmt1mi73f7a8YqF8jGRHtZOE4mEnM1mn1Exa3o0l8vN0cuy/GKz2S5ardb3jlcstNFokB7WpEKh8NrpdAgVs6aHM5mMwto7H+99KBSSm83mrlcstFqtkh5cnGQyuUaPilnTtxfJ4XBc+Xw+mUM+93iFQt2lUon0jMdjqtfr2x4V868ORqMR9Xo9XDLa9Yr+ZVz87VQ+MjoW7BF9HJz8beLpdFrlS0KHkkqlPoLBoPAzaPyDbwRmqBlqhv6JH8CLXqCC55PmAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"ccButtonOff" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAeCAYAAADQBxWhAAAB10lEQVR42u1Vu0oDQRQNmEZQSGHMYzebZHcTg0IeFlZaCIpGRI2itb+hEOMnWEasbGLlo/EHJDY21jYWvhURH5UijudMEomI4CQgBLY4zMxhzj1z78zddQkhXP8Nl2PqmDqmrWnq9fqywBUgmgD1WRXTq2BQE7puNAzqGUfFVITDURGJmBKhUFj4/UGZQXe3X2ha6Afv8wW+eIJ68kqm0aglTNMWhhGh0XUymV4olba8udxsn6bpOzSA0Vk6nZnZ3t7pmpycSoHfJ08d9cqmFBKBgCYQeBrmE+DPYbRRLK57cJD7TKZ/FNnOgb8Av1YorHaBf64dWNnUsmISmL/l8yvtCHZQd1cPWN9ibxvGI/LgPsgD73VaNVPbjklg/gq4cXdlwwjL4CjjLjI74V6Mx1X+nWXHIR4ty65pVU3jEtWHMpxI9M4j4A2y2qyW8Qn8QDyeWMT8DuUvLi0tezF/YZbUKpvGYj0SfEi8S4zZcvnQMzY2HsVaPiSMpzAYIT84OGRjvcdS17QNm/LELF99y+h65YV+bxm/7E/ub8iULcJeq4lZLtO0ZBsQlTuL/8pTQz2v48+mqVR6joJmPoPQXzKOygffDXQAnU2goxrH+bU5po5pC5p+AoMCobNnBGFcAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"ccButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB0AAAAeCAYAAADQBxWhAAACIklEQVR42u2VO4saURiGbVZERC39AVZ2U9jK/gERCxG1sdIiAZukCWSxs1hZlE0jLtEQb9FCUfF+v4DXFTR4KxSDE9ikSDM72WTRk3OGGIatDgpLihGewo953+c4Z+bIAwDwnhseJ+WknPQkKfycQWQQAqKCnB+B6m8e9ZzhSGV2u/1yu93SFEWBY0F51IP6cKTEarWiSZJEwaNBedSD+nCkqs1mA9br9cmgHtSHIz1fLpeATa/X+2U2m+NisfiCIAhXIBD4gubtdvunyWSKiUSit0ql8joSiZBPs6gPSzqZTAAbg8HwyWKxvJ/P51Q4HP4sFAo9nU7nQavV+m0228fFYkH5/f5biURy0+12d+wstnQwGIADsGQPJa+LxSI5Go3AdDoFUPLYaDTQfr2s1Wp3hzlc1GO/3wfsPLa01WqBA/V6fS8QCF7FYrGv6Huz2QRut/sulUr9gNe+SCQS39EcLmLvcrm+5fP5HTuPLS2Xy+BApVIBer0+BPf0QzKZvHc6nRN4G68LhcJvtVp9Y7VaI3ABtMPhuJVKpe+y2eyOnceWZjIZwKZarT7odLoon89/I5fLnaFQaJvL5dCCaI1GE0ZzhUJxBR8kZs7O4kpV8XgcsIG/hNmf2WzGPBylUomZp9NpMBwOmfl4PP43Z4P7yhA+n4+ORqPgVFAP7uEgg+/epdfrpYPBIDgWj8dzbzQasY/B5z/wuT9xTspJ/zvpH7Snd5Nr6YMeAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"muteButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAeCAYAAAAy2w7YAAACPUlEQVR42mP4//8/Az0ww6hFoxYNvEVkAiYgZgZiRpgALSxijIuL4zt58qQNkM0Fs4xci0CaWYCYHUoji7G4u7sLv337dtaKFStsoWrIsghkILu1tbXCixcvmoBsXqg4C9AXphs3bjQEsvnKysr0gZYtlJaWFgUFJakWgcKet7Oz0/bdu3crX758uR/IF4f6hHXmzJna79+/X+Dl5SUD5AsdP368+uDBgwEghxFjERtIExBLALHMjh070r58+bL7zp07+69evQqySPbChQu2ycnJIAsFNm3alHDt2rUcEHvq1KnWt2/fbgX5kBiLhID0fhgGBsf+ixcv7j9//jwYA+Xljh49Gvb48eN6kOGenp7yQEfMA7KFOTk5xYCWLgKxibFI4sSJE/txYaC8FCj4rly5shhkIAifOnVqAYwNjLcFRFsEDOf9uDBQXpqDg0Pi8OHDMItEgGy4RTA2UUG3a9eu/bgwUF7+5s2b8evXr68EBV1kZKTSvn375oIMFxQUFNu/f/9CaPCTlhgaGxtTgEl495YtW/aDMCgxbNiwwdDU1BSkRgAYfxmLFy9OA7HXrFljv27duiZiEwN68uaJjo62Ahq2EmgILHmDihtWIN8QaNE8PT09SZDjLl++3DBjxgwvYpM31gyroaEhDzSkHjnDbtu2Ta+qqkoT5IMJEyaYHjp0aC4w5QmTk2EJFUEgn7EkJiaKAUuN+SUlJZaUFEEEC1UzMzOurq4uM2oUqgQtI7maGK3KRy0aPhYBAK/+y9iyNfpJAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"muteButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAeCAYAAAAy2w7YAAACW0lEQVR42mP4//8/Az0ww6hFoxYNvEVkAlYg5gBiFpgALSxitLOzk122bFkikC0NxMyUWMQIxNxALALEXFAxFiibS1tbW+vx48fX6urqcqFqyLII5EIRJSUlr8uXL+8HslWg4pwrVqwI7ezsDAGyVf38/OKBlj3k5+c3BgUlqRaxAbFiXFxc+YMHD96/fPkSpMAOZAkQ8+Xm5gY+e/bsvo6OjgOQr79p06btc+bMaQE5jBiLBIDYAIhBmn0mTJiw9uPHj3/u3Lnz/+rVqyAFfkADE4DxYghka02dOnXmnj17lgLZOvn5+VnHjx8/BGSrEWORwX8k8Pbt2/8XL178f/78eTAGygesXLmy/cKFCzuBbE1g/HhcunTpLpBtyMrKanHu3LmHIDYxFjmcOHHiPy4MlHcDYtszZ848AdJGQGxy8ODBB0AaFDfGBw4cALOJsgio8T8uDJR3Z2Fhsd+9ezfIIlDwmQLZcItgbKKCbteuXf9xYaB84L59+ybOnz9/EyjozMzMvLds2QIOOk5OTqtt27Y9hAY/aYkhNTV19fr16/8ADfsPwkAx3/7+/kAFBQUNIFt748aNi7u7u+eDEkNTU1M+0AH7QMmdnOStYGtrWzJr1qz369atAymwBWJ2IOYFGhwBjLc7UlJS1iDH7d+/f29FRUUtkC1MboYVFhMT8wS6fDeQrQzLsMCk7RMdHe0F8kFKSkrazp077wBTngE5GRZfEcQMLUg5gT7Wu3fv3t2wsLB0kKNoVqjKy8tLFhQURALZUpQWqoQACzTemImuJkar8lGLho9FAFfb1pYP/NUtAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"unmuteButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAeCAYAAAAy2w7YAAAA2klEQVR42mP4//8/Az0ww6hFoxaNWkR9i3AARiBmAWJ2EE0ri0CWsFtbWys8e/asCcjmpYVFTCCD29rabN69e7cSiPcD+WLUsogNiIWAWAKIZbZv357y9evX3Y8ePdp/584dkEUS1LJICEjvh2GQL65evbr/8uXLYExNiyROnjy5HxemqkUHDhzYjwtTNei2bdu2HxempkUoiaG6ujpl1apVO9euXbsfhKlpEXry5gkPD7eaM2fOymXLllE1eWPNsMrKynITJ06sp1WGpV0RNFpNjFo0atHgtQgANKFe0TzIhR0AAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"unmuteButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAeCAYAAAAy2w7YAAAA2klEQVR42mP4//8/Az0ww6hFoxaNWkR9i3AARiDmBmIRIOailUXMIAuUlJS8Ll26tBfIVqaFRWxArBgTE1P64MGD9+/evQMpsKKWRQJAbADEDkDs09/fv/rTp09/Hj169P/OnTsgBQ7UssjgPxIA+eLq1av/L1++DMbUtMjh5MmT/3Fhqlp04MCB/7gwVYNu27Zt/3FhalqEkhgSExNXLV++/M/atWv/gzA1LUJP3grW1tbFkyZNer9s2TKQAktaZlhhIPBoaWnZTasMS7siaLSaGLVo1KLBaxEAvQpqyzzc7aAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"fullscreenButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAeCAYAAAAo5+5WAAABX0lEQVR42u2UQYuCQBTHFTxJUJ0LJWiPQp/Dm126+x3yLi3YKU/dO+ilgx2iyETesXuelESNuvcN3HkwLh6WRXZYlgUHfoyg/ObN/43DlWXJ/QZcK27Ffyj+ZvAEkSATFMKEMiZ0mMSz2Ux+PB4O+Q7qoJy14p4kSdPL5eKTBaACK2cRCxjDarVa3O93yLLsE1Zxd7PZzF+vFyRJAnEcAxk+PmPmLOK+53lWFEVwvV7BMIz34XA4DcPQwZ00EfM1cPtdzBY7T3hbr9eWaZoGPR09VVVxFpuIRU3TZCqTcfun08lCKZX36TuhXkQTsVwUhTMajaa2bS+ezyekaQrn89mi0i9HE7FCjhPcbjcfu388HuFwOMByuZzTWH4snux2OwiCAHAmDQNd1xc0U4FJvN1uoYI0yx8MBhrNlWcRj13XhYr9fg95njv4O7OKO/RiqS4ZhcYgMonbi74V/0PxB6RCFmvPDfJxAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"fullscreenButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAeCAYAAAAo5+5WAAABaklEQVR42u2UIWzCQBSGAYFsEGwISBNkp5hHoHFV9dXD1tehiqpjSQ0GwS2hNE0bUokHBYUUmtbXVb7dS66IZVkaLsuypJd86aXiu3f/u7saANR+g1olrsR/KP5h1CkCRaIMKSPGgNLiETcURZGSJAnhy0A5b8XPoihOdrtdTheAAqycR9zEGAzDIHEcQxRFd3jFbcuy5lmWwel0guPxCEEQ5DjHzHnEndVqZR8OB9jv96Bp2kev15tst9sQd1JGjFk22Be338ZssfOUV9M0bV3X3+n8Bf+Px2M8JUIZsSDLssRkEm7fdV0bpUzeoTyxRe9FlBFLt9st7Pf7k9lsRtI0hcvlAp7n2Uz67SgjHtLjBOfzOcfuO44Dm80GptPpnMXysHhECAHf9wG/tGGgqiphN67JJV4ul1BAm5V3u903lnmdRzxYLBZQsF6v4Xq9hnidWaMeFrfYw1I8MkMWg8BVcfXQV+J/KP4EGwslGEtzWUAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"normalscreenButton" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAeCAYAAAAo5+5WAAABX0lEQVR42u3VMYvCMBQHcPXw1K3oKfclzqGlU7+MWye3c3Lph+gmdHGuW8WpGUrrarEIrlZEBKEtdPbegxeQG3pHglsDf0hJ+6N5adLG4/FovCKNGq7havgfrfmUFqQD6ULecFAGbs/n8w/ClCAIJofD4Rv6A8RlYCXLsoVhGOP1em2WZekXRcEAn8FYTwYe3W43dr/fXUTP5zOD+JvNZoJlkYE/Ebter4yjy+XSxJlgzaXgNE0ZT5Ikrq7rX1TzpgzcP51OjOdyuTCsuWVZQ1n4HXF8c8qIytD+C27STQo9xIE+oZWtEsZp5Xm+gGv2HMLFYVwITdPGURS5sDiMh95cGMZtqnieZx6PR3+/3zMeWbiD2xQ2gB/HMYP4cO1in2ouDPe22+1st9sxiG/btqmq6jgMwwUtqDCMp9RgtVrNHMeZENadTqdD+lqEYY736Ehs/ToqxeD611TDr4V/ALfMb7vGw5DiAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"normalscreenButtonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAeCAYAAAAo5+5WAAABbklEQVR42u3VMauCUBQH8GqIN8UbImlocHSrPeR9haYWV7fX6NRniIbCqUDQwRpycVC/hFMNXSKzoD0Cx/PugeMbGnwPL21e+KOg/jj36L3WAKD2jtQquIKL4X+MOk+Djk2eNk+H5wMvisCt0WikEKZYlrUKgsDn5wPERWDler0yWZYn8/ncez6f8Hg8IIoixCUReHi/3+F0OmUIJkkC5/MZTNNcYVtE4C/GGFwuF8Dj8XiE6XTq4Uyw50Lwfr+HPLwFWa/X+6ae10XgfhzHkOdwOECapmw8HmPFDRH4E3GsnDKkNrT+qrhONyn0UA70CS0cRXADp3W73Ri8DMJLw1hxp9vtTtbrdeb7PuShykvDuEyV2WzmhWEIu93uN6JwG5cpXwCw3W7BdV1YLpfZZrMB6nlpWOKw7zgO2LYNmqZ5kiRNFosFoxdaGsZdamAYhq/r+oqwjqqq+SdVGs5xibbE5stWWQ6ufk0V/F74Bzh6cDMaFwHFAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"volumeCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAeCAYAAADpYKT6AAAAFElEQVR42mP4//8/AwwzjHIGhgMAcFgNAkNCQTAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"volumeCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAeCAYAAADpYKT6AAAAFElEQVR42mP4//8/AwwzjHIGhgMAcFgNAkNCQTAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"volumeRail" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAAeCAYAAABaKIzgAAAAWElEQVR42u3VsQ3AIBBDUW4ASpQGIRS4sP+EzgzpYun/CV5lh6TiUAAFChQoUKD/grZ2WUij9+EBnfP2gK6VHtC9baCPBzTzeEBt5klS5ZmAAgUKFCjQr71HYkzTWoeyuwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeRailCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAeCAYAAAALvL+DAAAAgUlEQVR42tXQQQqDMBAF0MFdwa02xBDTSWK3dW+X9rYt9GTV9gDfmUDBK7h4kPn5kCEEgPboOEHTnFUWT7HqcBUfYyyc86C2NS9rHfr+ghAY2lj1wJwQYy6NL3NESrmgrnNv74MMQ0HTdL9Ja/mH+nY1z49Rm3LxK3toKE6iPs4XboLWK4v24Kf0AAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"volumeRailCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAeCAYAAAALvL+DAAAAgUlEQVR42tWQTQrCMBCFB3dCt60hDWmcJHWr+7qst1XwZCp1/3wjCF6hiw/m/cAMIwDkH1mP0ba7F7mS+jVCiHDOg8aDHCQlxTDs4X1A17mb5FyhWmABG4uUUmGoZmu8aYwwYkzo+3CXn2D6nKbzUTgslszz5cS1GzumIVsT63rhB+kPMQcishPoAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"volumeProgress" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAAeCAYAAABaKIzgAAAASElEQVR42u3UsQnAQAwEwRe4/wLVh5TqWzDGiWC2guGCi5k5GwpQUFBQUFDQr9AV0sjMFdCnqg7on9DutqgfBQUFBQUFBX3bBU4WWutcf3kcAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"volumeProgressCapLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAeCAYAAAALvL+DAAAATklEQVR42mP8//8/AzJgHB4CfUCcDBb4/fv3hDdv3uR/+/YNouLy5csf//79ywfXcvTo0Y9ANkJg9+7dE4HsPBRDN2zYMAFIJTEOoxADAG38dDtrd5P1AAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"volumeProgressCapRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAeCAYAAAALvL+DAAAAT0lEQVR42t3QIQ6AMAxG4d5fkHGS+un6JtXV84Cr+TfKQuAIID7z5CMA9ETfDtuw3MHd0VpDRJQMqoqTmR0ZRATTFWqtmNYMzLwP5SeDXjqg+Gveu5kMqgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3c/elements\x3e\x3c/component\x3e\x3ccomponent name\x3d"display"\x3e\x3csettings\x3e\x3csetting name\x3d"bufferrotation" value\x3d"90"/\x3e\x3csetting name\x3d"bufferinterval" value\x3d"125"/\x3e\x3csetting name\x3d"fontcase" value\x3d"normal"/\x3e\x3csetting name\x3d"fontcolor" value\x3d"0xffffff"/\x3e\x3csetting name\x3d"fontsize" value\x3d"11"/\x3e\x3csetting name\x3d"fontweight" value\x3d"normal"/\x3e\x3c/settings\x3e\x3celements\x3e\x3celement name\x3d"background" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAA0CAYAAACQGfi1AAAAZUlEQVR42u2VwQ3AMAgDebBClEUYt8NV+XUBvnQKq0UcC1jYZ9nX2pcJzyNiSwUy06QCJj6vMvUH1dwiBEZgSg+gCIv6Y0rIAygi5D8UjUUjA/aAyZwwOPIP2mMKRd9bdM79KAVee0AqrmZ58iQAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"backgroundOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAA0CAYAAACQGfi1AAAAZklEQVR42u2VsQ3AQAgDKVjhlS5TsH+dMV4MQUumsBL0xwIW9ln2ta7HhOcRcUsFqsqkAiY+7zb1Bz3cIgSOwJQeQBEWzceUkA+giJD/UDQWjQzYAybzhMGRfzAeUyj63qLMnUqBF2JaKtp629puAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"capLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAA0CAYAAACHO2h8AAAA7ElEQVR42u3XvQqDMBQFYCPYWLWIiNFFUePvUju2e/sA9Vnsmzj2WbXXQktxkWgoIjlwudtH7pDhoL7vpSGEeBWsG0wEgyXGoAEC5G5ZVk0I0XRdV2RZRsyQ47hHQB6+75td173hzytZoYbS+IyxynzOGGrzvAjmnDOGnmVZutLCCOjfUFGsDyoENAHBp90ulK8MyjIBTUMZHyhNBTQFJUkqoAmI0mSrUBxzg+jKoChaHxTzgUJuUMgNirhAbRCEAYIshRrX9S6qut8thSpN0xvbts0lxeZb/ACrDeOgYYyVOWeinyp6gnWdW0Vft69cndg2ea8AAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"capLeftOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAA0CAYAAACHO2h8AAAA50lEQVR42mP8//8/AwiIiUnYAKlIINYCYk4GEgEL1JAMQUHBTDExMV5ubm42JiAg2SCQS0CGyMrKCv/794/p58+fDDBXkuqiSCEhQZ4/f/6Q7Ap0gzRZWNjYyXAEhkFcTEyMQNdQZhITA5XAqEFEpmxKo576LqI0DY3G2pD22qCK/mEc2IMv1kYDm+gwGi0hR2YYUS2LjBa1dC/YqOai/4PMa9/+/fv/j5GRkYnSWLv+8+ePX9SI/uWfgeDfv7//IF4kDzO9evXiyLdvX6e/BYLv33/8AHoTXKqQihmRuqK2QCqC3K4oAL0UgwtgxUxZAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"capRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAA0CAYAAACHO2h8AAAA8klEQVR42u1XQQ6CQAwEUlfjTRLAC4k/8MIX/IDv8w16l1foA9RwUjhw2JW4IWFt9QPAokHcJk2zPUw6nWyTAc8LNlbzkJhnzH2aXo/UgCiKgqYoVVUpIUSQZdnS9+dbBNtBURSNx7ExGGPjMAwZPtcIdoIWtCyl1CtxMtt1Z9M8z1eAb60AYCMsC5xID8lxbBvLBKyOwgDVANKV/xPUlFHtB1UbrPyDXnbfVDPLrrMjcyH/eEcdfhFzar932DqbqHfy66qm3p9Vaqsm5aMk76ZFjXwb55x8WtyKGtGRUpZCcLR7dzJ+B0iSy03DisYEQo0nc8B4p9SUlywAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"capRightOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAA0CAYAAACHO2h8AAAA7klEQVR42u1XMQ6CMBSF5qdGEwdJQBfY3Rm9iEfwRHoDL8LgAYyzYTIwMFCrOFBfPQFQNKh9yU/TDi///Zf+5JHvzw9Oe9xQJ9Q+yy6JfqA4jqO2LDUghIjyPF8FwWILsh1JKVu347ou45yPwzAc4boB2ZE6yHKUUq9CY8zzZtOiKNaEuxGIOMexREdmTIy5DMeEnJ5giRoQmdr/DmnKuvaFrv2s/T897KG5ZofdZEZ2Q/7xjHr8InbVfm6x9dbR4Ow3dQ1/tdaxy9i1qro/dHYzkqZzWwnoANhJGuSoChCiLKW86uCXUJqe0z6i6BMdqXhIR7IE5AAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"bufferIcon" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAABTElEQVR42u3WPUtCURzH8Xt92HRwCJokNAOJqKVcitBF0pr0FfRAay+gqDFobXaoKXsD6SY4Nbk7CA4OUa/h9jvwjy6XfDjdw+UIP+EzXfR+z/3fc9DxPM+xicMgBjGIQQxiEIPsC6rAGD6gYUPQ0Pv9fIIbVVAcknOCvqIKOoaBqP8xshFMoBm45soilJjJoHd5EkpfY8UJX1DSZFDPF9S1IagEHXiDXY0gV6ISpkfGg3EpgnbgCdpwYOBmKSiI1H+CWvISK69hDzzYgKJYDxvUtiFoG57hBfYNjCwddmTcZUsdtAW3cA15jRtk4BDKsGIy6B4exY1GkIo5EVVTQWq7P/iC7jT/3v4EHS1ydCz6w3sSpZ7UZuBaDi5EcJyrElKDrOmXetrqzuBKXE75XizKXXbqCzq3YdtnJUpZ48HIIAYxiEEMYhCDZvsG/QUNjWGQyWIAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"bufferIconOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAABTElEQVR42u3WPUtCURzH8Xt92HRwCJokNAOJqKVcitBF0pr0FfRAay+gqDFobXaoKXsD6SY4Nbk7CA4OUa/h9jvwjy6XfDjdw+UIP+EzXfR+z/3fc9DxPM+xicMgBjGIQQxiEIPsC6rAGD6gYUPQ0Pv9fIIbVVAcknOCvqIKOoaBqP8xshFMoBm45soilJjJoHd5EkpfY8UJX1DSZFDPF9S1IagEHXiDXY0gV6ISpkfGg3EpgnbgCdpwYOBmKSiI1H+CWvISK69hDzzYgKJYDxvUtiFoG57hBfYNjCwddmTcZUsdtAW3cA15jRtk4BDKsGIy6B4exY1GkIo5EVVTQWq7P/iC7jT/3v4EHS1ydCz6w3sSpZ7UZuBaDi5EcJyrElKDrOmXetrqzuBKXE75XizKXXbqCzq3YdtnJUpZ48HIIAYxiEEMYhCDZvsG/QUNjWGQyWIAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"errorIcon" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAACs0lEQVR42u2XTWsaURSGbWtKqbQULJiGbrppN666K3EhNF11IYhZJnSrCO0P6MKG/gEX7SKbiKKCEUQEC4pCIKCoqPUThJDqSg1C6CoQwu15B0fMdBzHkDEhXOGB8dxz7zzOdeZVHWNMd5vQcSEuxIW4EBfiQndJ6IqvFeLpmJXbILS6u7v7FeD4poUeGY3G991u97TX652aTKYN1G5K6D7xyufzJfv9PgN7e3u/UMPYTQg9sVqtnwaDwTldHQZwjBrGli30gDBns9kmbRc7Pj4WwDFqGEPPMoWMTqfzG10RdnR0dAnU3G73DnqWJfRQr9e/q9Vqw06nw+TAGHrQq7XQPeKl1+sNY4tarZaAzWbzA/E9xtCDXszRUuix2Wy20wnP6vU6E6H6RzBdQw96qW7QSgi3+etYLJZrNBqsUqlMoLoVTNfQE4/H81R/s8hjYBGhZ5ubm5/pk1+USiU2jSgkraMXczD3uoWQV29zudyfQqHA8vn8JUQhaR29mIO5anNOrdCqx+P50Ww22eHh4X+IQnJjmENzf6rNOTVCyKsNunv+HhwcMDlEoVnjmLu2tvZBTc7NE5rkFV16lslkZBGFZo1jrtqcmyck5FW73T5PpVJsFuJtr9SDNdTknJKQkFfpdLqJBZPJ5Ey2t7f9W1tbfqUerIG1xjmnv4qQ0eVy7ZTLZZZIJBQZjUYC8/qwFuXcd1r7+aJCQl4Vi8UhPQjZdUKPAsWckxOa5BX9lGDRaHQuFotlH6jpxZpKOScnJORVtVo9i0QiTA12u32fiKjtx9qzck4qNMkrXN5wOKyK4XDITk5OVPePt08256RCQl7RPl8Eg0GmJfT9vHA4HF+kOScVevGbXqFQiAUCAU2BFM6FcyoJGbBlxLr49NWQ9fG5DPy/PRfiQlyIC3EhLqQh/wBHF7waCbYO0QAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"errorIconOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAACs0lEQVR42u2XTWsaURSGbWtKqbQULJiGbrppN666K3EhNF11IYhZJnSrCO0P6MKG/gEX7SKbiKKCEUQEC4pCIKCoqPUThJDqSg1C6CoQwu15B0fMdBzHkDEhXOGB8dxz7zzOdeZVHWNMd5vQcSEuxIW4EBfiQndJ6IqvFeLpmJXbILS6u7v7FeD4poUeGY3G991u97TX652aTKYN1G5K6D7xyufzJfv9PgN7e3u/UMPYTQg9sVqtnwaDwTldHQZwjBrGli30gDBns9kmbRc7Pj4WwDFqGEPPMoWMTqfzG10RdnR0dAnU3G73DnqWJfRQr9e/q9Vqw06nw+TAGHrQq7XQPeKl1+sNY4tarZaAzWbzA/E9xtCDXszRUuix2Wy20wnP6vU6E6H6RzBdQw96qW7QSgi3+etYLJZrNBqsUqlMoLoVTNfQE4/H81R/s8hjYBGhZ5ubm5/pk1+USiU2jSgkraMXczD3uoWQV29zudyfQqHA8vn8JUQhaR29mIO5anNOrdCqx+P50Ww22eHh4X+IQnJjmENzf6rNOTVCyKsNunv+HhwcMDlEoVnjmLu2tvZBTc7NE5rkFV16lslkZBGFZo1jrtqcmyck5FW73T5PpVJsFuJtr9SDNdTknJKQkFfpdLqJBZPJ5Ey2t7f9W1tbfqUerIG1xjmnv4qQ0eVy7ZTLZZZIJBQZjUYC8/qwFuXcd1r7+aJCQl4Vi8UhPQjZdUKPAsWckxOa5BX9lGDRaHQuFotlH6jpxZpKOScnJORVtVo9i0QiTA12u32fiKjtx9qzck4qNMkrXN5wOKyK4XDITk5OVPePt08256RCQl7RPl8Eg0GmJfT9vHA4HF+kOScVevGbXqFQiAUCAU2BFM6FcyoJGbBlxLr49NWQ9fG5DPy/PRfiQlyIC3EhLqQh/wBHF7waCbYO0QAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"playIcon" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAABzElEQVR42u3XTYtBURjA8VuzmdWsZmk7GzWfxL1IJMs5n8GXkISFzCQz5pSUlMUjC2WhLCyUBclLXkIkNt5ZmXt3FpLn3nPRdE796y5/dc+rcDwehUdK4CAO4iAO4iAO+o8geTzLvcq9yD0JOg0MyNDv9z/dbveH/P2mFwwDMs7nczgcDlCr1X71gmFA76PRCJRmsxns93tdYCjQYDCA06bTKXMYCtTr9eBck8kEdrsdExgK1Ol04FLj8VgzDAVqtVpwTcPhELbbrSoYClSv1wGTvE3AZrNBwVCgarUKaup2u7Ber6+CoUCVSgW01G63YbVaXYShQOVyGVjUbDZhuVyehaFApVIJWKbMs8ViAY1G4zsUConKeYkCFYtF0KNMJvPj8/kkNKhQKADLYrEYdblcRPUvy+fzwKJoNEqdTifRPKlzuRxoKRKJUIfDQZgt+2w2C2oKh8PUbrcT5hsjIIe8cqjNZiO6HR3pdBquKRgMUqvVSnQ/XFOpFFzK7/dTi8VCbnb9SCaTcC55D6Fms5nc/IKWSCTgNK/XSyVJIve6whrj8TgoeTweKooiufcl3xAIBL5MJhN5lGfQYz0U+duegziIgziIgzhIfX+1FIqPwZcb/gAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"playIconOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAAByklEQVR42u3XuWoCQRzHcYuUKVPmAXyAlBbpPRFFfIek8yXMIGohFiLYiCCChWIhWAgWFoKFIh54RGUH0cZbq192OwsR/+uuSpiBL2z5gZ3TAMDwTBkESIAESIAESID+I0ger3Lvcm9yLwadBgVkHI1GHZ/P9yN/f+gFo4BMi8UCx+MRzWZT0gtGAX1Op1MozedzHA4HXWAk0Hg8xmmz2UxzGAk0HA5xLs459vu9JjASqN/v41KSJN0MI4G63S6uaTKZYLfbqYKRQK1WC5TkbQLb7ZYEI4EajQbUNBgMsNlsroKRQPV6HbfU6/WwXq8vwkigWq0GLep0OlitVmdhJFC1WoWWKfNsuVyi3W7/RiKRL+W8JIEqlQr0KJ/PjwOBwDcZVC6XoWWJRIJ7vV6m+peVSiVoUTwe5x6Ph908qYvFIm4pFotxt9vNNFv2hUIBaopGo9zlcjHNN8ZcLgdK8srhTqeT6XZ0ZLNZXFM4HOYOh4PpfrhmMhlcKhgMcrvdzu52/Uin0ziXvIdwm83G7n5BS6VSOI0xxq1WK3vUFdaUTCah5Pf7ucViYY++5BtDoVDXbDazZ3kGPddDUbztBUiABEiABEiA1PcHSCzm64IZEhcAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"replayIcon" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAAEwUlEQVR42u1YW0icRxR2o6k2pmyMa0NJjRrRtWgp3rA00ifJpuqqL1FEpGLxQQVJIaUVgnZViqIglHh5UHej4mXpqruj4v2CFwTxLgjiFRUUUby8KCL2fMv8QYKa/Lsb0sL+8OHvzJxvvn/OmTln1ubi4sLmvwQbqyCrIKsgqyCroP+jIBMeB8J9wheEWx9q9DEFPVxeXi5JSUmJo3c3wh2C5FMK+mZ/f5+dnJywoaGhsvDw8J8gkq+c5FMI+nZra4sBXJiBMVYUEhLyI/U9IHx2lTBLCZLwL5cR3AlygnJjY4MJ2NzcZAcHB+zo6Ki5pqYmx83NLYjGOBPsLClIwmPDNTIyUlFXV6eanp5W7+7u6k5PTw3r6+vsXUDc4eEh29nZ+ae0tPSlo6PjY75aZgvCl8mUSuXT4eHhcgjACmxvbxsnXVtbY6urq9cCY46Pj9n4+Hgm8dw1V9BtBGhubm46uaAFIpaWlkRhcHCwPiMjIwWra+4KYWVcNRrNKxJjJF9cXDSitbX1jUqlylQoFEpyxXOh/TJoRXTZ2dm/29vb+xKP1NwYQsy4FBUVvdjb22MLCwtG9Pf3a5OTk3+hPm8eqAjw74R+YGpqSl9cXPyXh4dHCA9+O0ts+zsIXnKRfn5+ngEtLS3VNMkT6rtHsL18DqF/dnaWVVVVvabtHkZtX13a7sKG+FIqlT7gHyFKEAhcBwYGyubm5tjMzAzr6urSent7h1K74xVnysO2trbXUVFRz+n9EeHzS2PwVxodHR1GG+LvycnJYvr/a7SLEeRA5M9WVlYMRMAmJiZYfHz8zzwOJDfksrtX5LJbCQkJ/rTLWrAbwQlu2IgRJKuurv6TghKByejMeUNtXu+46UMffMDjhoYGjcAHbswhRpA7uUg9NjbGgKysrEwewKY+zuAQ+MCNOcQIklOS1JHPGRAREaEUAtHExwEcAh+4MYcYQb5kaKADDYcac3Z2DjbRXW/jSCaTBQl8IyMjBswhSlBPT4+hr6+PAT4+Pj+YK8jFxSVI4Ovt7RUtSN7U1KTr7u5mQFxcXLSZLrOnbR8p8IFbrMvcKysr1R0dHQwoKCj4jW9rU5/7hYWFLwW+iooK0UEty8nJUdFhxwAi0Zix7WHj1dnZqRH4KFGL3vYOYWFhz/R6vYEeNjo6ytLS0m46GG86g6SwBQe4wAlusQcjiB7l5+eXNzc3M4BSiNbPz++61HGdGEfYUI5rFHjAydOLRHRyDQ0NVdTX1+t1Oh0OM0YVYrVcLn/CV8r2PW6SYixsYAsOcIGTJ1rTyo+kpKQXjY2NTKvVovRABajl7vPige7A85ctf8eJ7oUxGAsb2IIDXOAUVtjkAi01NfUVfR2jfMTa29sZ1dGoeTRlZWV/xMTEKJ2cnII9PT2/pwQcQ7VzJvowBmNhA9v09PQsXjHaWaSEjY2NTafKsYUSLZKt8YBDBYla+fz8nJ2dnRkLerShTxhHNvrExMRfuZjblrp1GIv8wMDAp1SSltPVxlBbW8tuAo1hGBsQEKDgbrKz9L3s7TXI399fQW5U5eXlqUtKSnRqtdoA4B1t6AsODg7nu+naa/XHvCj6csh5m+x912hRgqy/D1kFWQVZBVkFWQVdj38BAk7AFyu8ie8AAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"replayIconOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAA0CAYAAADi1poDAAAE2ElEQVR42u1YaUhcVxi1xirttDHWpbQxtSKoSRTiVoUaKFQquBOCVkQwkmmrVqH9FyiKC1TRYv+o+eFWNW513zruiguCdRcUcWXGRhFFR1q143j7neG+IMFJ88YJaWEuHHze5bzz7v22O0aMMaP/EowMggyCDIIMggyC/o+CdGjvED4kvEe48rKLXqUgp5WVlXmpVPoDPbsQrhKMX6egT/f29tjx8TEbGhpaCAgI+Ib6HAkSwhuvQ9Bnm5ubDODC1K2trWPe3t5f0pg94a2LhOlLkDH/cluCK8GbkCiXy5kAhULB9vf3mVKp/Lu8vLzTzs4ugOZcJ5jqU5Axt41bQUFB0srKStn09LR8Z2fnr5OTk7ONjQ32PCDu4OCAbW9v/5mfn/9EIpHc4bt1aUFvEm4EBwc/HB4eXoQA7MDW1pbmpevr62xtbU0rMOfw8JCNj4/XE4/FZQWZwYvS09Mf0xGoIGJ5eVkUBgcH95KSkn7G7l52h7AzN0tLS5tJjIZ8aWlJg7a2tj9SU1Pr/P39k+goHgn950E7cpSSklJjZmZ2l3hsOJ/ONgSb+SgnJ6dkd3eXLSwsaNDf36+MjY39icY+4YYKA/9cGAempqZOc3Nz++3t7UO58Zvqw+2vwnjpiE7n5+cZ0NTU9JRecp/G3ieYnI9DGJ+dnWXFxcVz5O4PqM/hnLsLDvGxubm5Pf8IUYJAcGtgYGBhbm6OzczMsK6uLqWjo2M49V+7IKY4tbe3z4WEhDyi59uEd89Favy1CQ0NfUAOMT05Ofk7/e+MfjGCJET+1erq6hkRsImJCRYZGfkjt4OLIq+E5zKLC3LZlaioqC/Iy1TwRnCCG2vECLItKyv7jYwShsko5mxSn9dzx/SyDTt0p7q6WiHwgRvvECPIlY5IPjY2xoDk5OQ6bsC6tuvgEPjAjXeIEeRDSfKIzpwBgYGBiYIh6tgk4BD4wI13iBF0lxaqKaAhqDFLS8tAHY/rmR1ZWVkFCHwjIyNqvEOUoJ6eHnVfXx8DnJ2d711WkLW1dYDA19vbK1qQT0NDw1F3dzcDIiIivuNVoa7tbXL7bwU+cIs9MteioiK5TCZjQFZWViV3a13bB9nZ2U8EvsLCQtFGbZuWliajYMcAIlFQn6eOx4Y1np2dnQqBjxK1aLeX+Pn5fd3c3HzW0tLCRkdHWXx8/IsCo7aGuTZYCw5wgRPcYgMjgtntzMzMxcbGRgZQClG6uLhoSx3axFzDGspxBwIPOHl6MRadXH19faVVVVWn9fX1CGaMKsSnTk5O9/lOmfzLMdlgLtZgLTjABU6eaHUrP2JiYkpqampYbW0tSg9UgEp+fJ7c0CU8f5lwT0RE98QczMUarAUHuMApJF5dCjTUMTfj4uKa6esY5SPW0dHBqI5GzaMoKCj4NSwsLNHCwiLQwcEhjBLw91Q712EMczAXa7A2ISGhDVzna6NLlbDh4eGPqXJUUaJFstUEOFSQqJXVajVTqVSagh59GBPm0ZrT6OjoX3j5aqavW4emyPfw8HhIJekiXW3OKioq2ItAcxjmuru7S/kxmer7XvbsGuTm5ialY5RlZGTI8/LyjkpKSs4APKMPY15eXnHcm7Req1/VRdEHeYnDh/fd4AZurJe7veH3IYMggyCDIIMggyDt+AeCTA8AFSrCbwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3c/elements\x3e\x3c/component\x3e\x3ccomponent name\x3d"dock"\x3e\x3csettings\x3e\x3csetting name\x3d"iconalpha" value\x3d"1"/\x3e\x3csetting name\x3d"iconalphaactive" value\x3d"1"/\x3e\x3csetting name\x3d"iconalphaover" value\x3d"1"/\x3e\x3c/settings\x3e\x3celements\x3e\x3celement name\x3d"button" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAgCAYAAABpRpp6AAAAzUlEQVR42u2YMQ7CMAxF7aRiSQckWtGOHKMLR2DimFyAE3CUdqWiQ4ucYANXqIiRv+T96ek7kYx1vS8A4MzT8QTIMxPPjefyhm2a5tS2bem9xxxpiSj1fV8Pw/AU4K6qduWyLJhSylIvcoSRgY8CHIgiQsb5ihTG4EBZDHjtFJ+OKANmZKuEAWvtsE7DmpbOKmGVsEr8xrB9zSsbVvdKWCVs6cywGf4bwwI8EcXknMv6+hNjFKuTD6HcIsJhw5EbVq6w43h/zPN8RW3n1hcs+1ICqMmZZQAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"buttonOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAgCAYAAABpRpp6AAAA1UlEQVR42u2YMQ4CIRBFgV1LoXA3snoht/MOtnoarbyF1R5ptxRsDAngTKKtnWbYzE8+oXz8/IGEum3XCyHECbwDa0FTD/AAPtewHK21h67rTFVViiJtjDGN47iZpumJwH3TrEwIQeWcScYrpVTICMB7BNZwACUI6x0kMupaFCYG/gsw0Vn7lnDmSjBw4R3moeNKcCW4EjO7h/lp/nHCxd0SXAkeOk6YE55Vwj7GlBSIMmgCISsCD97ft1obQxUaYb13DrY3BL445yS4h/2SaMCf79brC0M0WI9LC6AuAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"buttonActive" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACwAAAAgCAYAAABpRpp6AAAAyklEQVR42u2YPQ4CIRSEccF2fwIbKz2T23kKaz2BVt7Dai9G4kJls+CbRDtbzWPzJhlCqL5MBkie6fvNWil1Ju/JreKpQB7JF0PLyTl3tNZ2WuuKI20iee+35CeAB86wUEUCIwEfANziIOesOAuMYDWqMAnwX4CZ1/dbwlkqIcCFd1gunVRCKiGVWNg7LF/zjxMu7pWQSsilk4Ql4UUlPM1zSu/JClthvgZWAI8xTru6bjqu0ICNMTxoewfwNYSwIg+0b5gG/Bm33l7CZ0/XNL9BmAAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"divider" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAgCAYAAAA1zNleAAAAFUlEQVR42mP4//8/AzJmGBUYFUBgAEE5fpDLFJZbAAAAAElFTkSuQmCC"/\x3e\x3c/elements\x3e\x3c/component\x3e\x3ccomponent name\x3d"playlist"\x3e\x3csettings\x3e\x3csetting name\x3d"backgroundcolor" value\x3d"0x3c3c3e"/\x3e\x3csetting name\x3d"fontcolor" value\x3d"0x848489"/\x3e\x3csetting name\x3d"fontsize" value\x3d"11"/\x3e\x3csetting name\x3d"fontweight" value\x3d"normal"/\x3e\x3csetting name\x3d"activecolor" value\x3d"0xb2b2b6"/\x3e\x3csetting name\x3d"overcolor" value\x3d"0xb2b2b6"/\x3e\x3csetting name\x3d"titlecolor" value\x3d"0xb9b9be"/\x3e\x3csetting name\x3d"titlesize" value\x3d"12"/\x3e\x3csetting name\x3d"titleweight" value\x3d"bold"/\x3e\x3csetting name\x3d"titleactivecolor" value\x3d"0xececf4"/\x3e\x3csetting name\x3d"titleovercolor" value\x3d"0xececf4"/\x3e\x3c/settings\x3e\x3celements\x3e\x3celement name\x3d"item" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABMCAIAAACnG28HAAAAoElEQVR42u3SQQkAAAwDsQor8y9rJvYZBKLguLQD5yIBxsJYGAuMhbEwFhgLY2EsMBbGwlhgLIyFscBYGAtjgbEwFsYCY2EsjAXGwlgYC4yFsTAWGAtjYSwwFsbCWGAsjIWxwFgYC2OBsTAWxgJjYSyMBcbCWBgLjIWxMBYYC2NhLDAWxsJYYCyMhbHAWBgLY4GxMBbGAmNhLIwFxsJY/LSgjDi3dpmB4AAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"itemActive" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAABMCAIAAACnG28HAAAAoElEQVR42u3SQQkAAAwDsToq829uJvYZBKLguLQD5yIBxsJYGAuMhbEwFhgLY2EsMBbGwlhgLIyFscBYGAtjgbEwFsYCY2EsjAXGwlgYC4yFsTAWGAtjYSwwFsbCWGAsjIWxwFgYC2OBsTAWxgJjYSyMBcbCWBgLjIWxMBYYC2NhLDAWxsJYYCyMhbHAWBgLY4GxMBbGAmNhLIwFxsJY/LRBziyQuYSeagAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"itemImage" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2CAIAAAC3LQuFAAAB9UlEQVR42u3ZiWrCQBAGYF9CzWnu05hDbX3/N+tfBqdrjEIptNL9YQo5hKQfuzM7m9V6vWU8iRX+zucLYzEIRCACEYhABCIQgQjEIBCBCEQgAv0s6nrveQGBHgZ0CHSpqtZ1fc8Lu24wr+MUr5qmudVAbXvQrbzt1j0e3/RWHKe4iB9YDeT7obndud/3ch1Sm42DKybZ/wfK8wr/dlFUcjoMx9l+cNN013nX4NT3dxZVMeWAkYwLeD0CQkrCaZ6XFgFlWaEQko9dN1gEOhxG82e2AKFUKUTbdn0/3n9yEaAkyWSgnU7vtgANw4TnOo4nqRcQWVYuAml6DsPYipV0GEZ9PxVFjedilqGW40DWPlcXxwTCLTkuy9oKIIyaNC2CIMJzISVAcZwpCu6aQFr4MQctGUExjPBQaRpmcwocOmRkiOmi0ZZmVXONLH9mQHXdmkCSfRBRlNoChMWxJJpxPM2AMExQp2RNOAuo2QIEAnRVZdnoGxgT6nMdKPl7FqJp436QTiIcTNN5EQgFzt4NMy1S6DOuDdp8QfTLWxyvBYSUhKK228W6Sr4H0p6eW643Zc7M3AT6CnOhiEiS/A9f5hWBZkkarTyBbsJs69G48bPP8iBC6kG/JoWfQPxwSCACEYhBIAIRiEAEIhCBCMQg0HeBGE/iA2Oi1tFMiSX7AAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"divider" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANIAAAABCAIAAAAkUWeUAAAAEUlEQVR42mPQ1zccRaOIzggAmuR1T+nadMkAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"sliderRail" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAABCAYAAADErm6rAAAAIklEQVR42mP6//8/Az4sKir+X0lJ5b+ysioKBomB5AjpBwAxrjrJQvfEawAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"sliderCapTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAKCAYAAACuaZ5oAAAAGUlEQVR42mP4//8/Ay0xw6gFoxaMWkB7CwB2As1P8WmmAwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"sliderCapBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAKCAYAAACuaZ5oAAAAGUlEQVR42mP4//8/Ay0xw6gFoxaMWkB7CwB2As1P8WmmAwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"sliderRailCapTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAECAYAAACUY/8YAAAAYUlEQVR42q2PSwqAMBBDe4mqrVL7sXh6vZoUDxAnxX0LungQEpJhFADVQusxC4dQXqhzT7dnfBcuY2Y4t1ao6TH7fGAYptPaBd5HhJAq1PSY/fFB4WCMG1LKFWp6kt2t/gOk+eeZy1KEHQAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"sliderRailCapBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAECAYAAACUY/8YAAAAYElEQVR42mP4//8/Az4sJibxSUlJ5b+ysioKBokB5b4Q0s9ASIG0tMxGWVl5DAtAYiA5ii2wsbE1ALr0A8hAkKtBGMQGiYHkKLYAiJlcXd0MQa4FGvoZhEFskBhIjpB+AF4F6qfhUR58AAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"sliderThumb" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAABCAYAAADErm6rAAAAKElEQVR4XmP8//8/AyHw+PHj/z9+/GD4+vUrGH/79g1MBwQEMBLSCwC4sRX/S7kwJwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"sliderThumbCapBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAECAYAAACUY/8YAAAASElEQVR42q3NoQ0AMAgFUfYXrIJH4/FIFmg6wS/1TUqaipOXRwDoVmbOiIC7w8ygqhCR2XmpCfAB4G/ArgAuYBQwCuDu1wZeW0osItX5QArCAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"sliderThumbCapTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAECAYAAACUY/8YAAAAWUlEQVR42rWNoQ1AIQwF2V8QHAJJKlAoSHVJ6qpI2IMwwPsrIPji3F3OAXB/ci221nytdRPRTin5p4MxRlBViAiYGaUUxBjDs8Gcc6+1YGYQEfTekXM+N+0HR/gfgjnWeYEAAAAASUVORK5CYII\x3d"/\x3e\x3c/elements\x3e\x3c/component\x3e\x3ccomponent name\x3d"tooltip"\x3e\x3csettings\x3e\x3csetting name\x3d"fontcase" value\x3d"normal"/\x3e\x3csetting name\x3d"fontcolor" value\x3d"0xacacac"/\x3e\x3csetting name\x3d"fontsize" value\x3d"11"/\x3e\x3csetting name\x3d"fontweight" value\x3d"normal"/\x3e\x3csetting name\x3d"activecolor" value\x3d"0xffffff"/\x3e\x3csetting name\x3d"overcolor" value\x3d"0xffffff"/\x3e\x3c/settings\x3e\x3celements\x3e\x3celement name\x3d"background" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAACCAYAAABsfz2XAAAAEklEQVR42mOwtnV8RgpmIFUDAFr3JukT6L+UAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"arrow" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAADCAYAAACnI+4yAAAAEklEQVR42mP4//8/AymYgeYaABssa5WUTzsyAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"capTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAECAYAAAC6Jt6KAAAAHUlEQVR42mMUFRU/wUACYHR1935GkgZrW0faagAAqHQGCWgiU9QAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"capBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAECAYAAAC6Jt6KAAAAGElEQVR42mOwtnV8RgpmoL0GUVHxE6RgAO7IRsl4Cw8cAAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"capLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAACCAYAAACUn8ZgAAAAFklEQVR42mMQFRU/YW3r+AwbZsAnCQBUPRWHq8l/fAAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"capRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAACCAYAAACUn8ZgAAAAFklEQVR42mOwtnV8hg2LioqfYMAnCQBwXRWHw2Rr1wAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"capTopLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAECAYAAABCxiV9AAAAPklEQVR4XmMQFRVnBeIiIN4FxCeQMQOQU6ijq3/VycXjiau79zNkDJLcZWvv9MTGzumZta0jCgZJnkAXhPEBnhkmTDF7/FAAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"capTopRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAECAYAAABCxiV9AAAAPklEQVR42mMQFRU/gYZ3A3ERELMyuLp7P0PGTi4eT3R09a8CJbMYrG0dnyFjGzunZ7b2Tk+AkrswJGEYZAUA8XwmRnLnEVMAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"capBottomLeft" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAECAYAAABCxiV9AAAAMklEQVR42mMQFRU/YW3r+AwbZgBK7rK0snuCS7JQXUP7qqW1/RNskqxAXATEu0FWIGMAFlYlnOJtim4AAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"capBottomRight" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAECAYAAABCxiV9AAAANUlEQVR42mOwtnV8hg2LioqfYMAmYWll9wQouQtD0tLa/om6hvZVoGQ2A0g7Gt4NxEVAzAoAZzolltlSH50AAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"menuOption" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAARCAYAAADkIz3lAAAAdklEQVR42mP4//8/AzGYYdgpFBUVlwPiXUD8GUrLYVUoJiaxR1JS+r+srNx/EA3kH8Bl4md5ecX/iorK/xUUlP4D+T+xKgSask9GRu6/srLqfxAN5B/CqtDb21cdpBho5VcQ7enprYHL10xAzAXEPFCaaVhHIQBeKc15eWl8jgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"menuOptionOver" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAARCAYAAADkIz3lAAAAdklEQVR42mP4//8/AzGYYdgpFBUVlwPiXUD8GUrLYVUoJiaxR1JS+r+srNx/EA3kH8Bl4md5ecX/iorK/xUUlP4D+T+xKgSask9GRu6/srLqfxAN5B/CqtDb21cdpBho5VcQ7enprYHL10xAzAXEPFCaaVhHIQBeKc15eWl8jgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"menuOptionActive" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAARCAYAAADkIz3lAAAAqklEQVR42mP4//8/AzGYYSgohAIZIHYE4lAoDeJjKJR1c3PLffTo0aXfv39/B9EgPlBcDl2h0/379y+/fv36/9OnT/+DaKDiq0BxF3SFoc+ePQOZ9B+Gnz9//hsoHo6u0GX//v2Xr1279h+GDx48CDLRDV2hkq2tbe6uXbsunz9//geItre3B7lRGV0hMxCrAbEHEIdBaRCfGVvwgBRzADE3lGbGCJ4hENcAI1indUdh01cAAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"volumeCapTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAFCAYAAAB1j90SAAAAE0lEQVR42mP4//8/AzmYYQRoBADgm9EvDrkmuwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeCapBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAFCAYAAAB1j90SAAAAE0lEQVR42mP4//8/AzmYYQRoBADgm9EvDrkmuwAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeRailCapTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAECAYAAAC+0w63AAAAXklEQVR42n2NWwqAIBRE3YSmJT4KafW1tZAWMN2RPkSojwPDPO5VAFSP1lMRDqG+UJexN4524bJ2hvehQU2P2efQGHs6tyCEhBhzg5oes7+PlcWUVuS8Nah5QLK77z7Bcm/CZuJM1AAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeRailCapBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAECAYAAAC+0w63AAAAXklEQVR42mP4//8/AwyLiUl8UlVV/6+mpoGCQWJAuS/IahmQOdLSMhvl5RUxNILEQHI4NdrY2BoATf4AUgiyBYRBbJAYSA6nRiBmcnV1MwSZDlT8GYRBbJAYSA5ZLQArC3Oj7DuqswAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeRail" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAA0CAYAAAC6qQkaAAAAXklEQVR42mP5//8/AwyIiUn85+bmZmBkZGRABiA1X79+ZXj16gVcgoUBDaBrwiWGoZFYMCg0MpKnkZFxCPlxVONw0MjIyDgaOCM7AdC7lBuNjtGiY1TjqMbRwooijQBUhw3jnmCdzgAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeProgress" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAA0CAYAAAC6qQkaAAAAT0lEQVR42u3LIQ4AQQhDUe5/FjJ4NH48ggQu0rWbGbEH2Iqanz4BIO9VFTITe29EBNwdqorzJ2fo7guutb7hzFzQzAgJCQkJCQkJCQn/AR/HKvJmqR7XwAAAAABJRU5ErkJggg\x3d\x3d"/\x3e\x3celement name\x3d"volumeProgressCapTop" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAECAYAAAC+0w63AAAAWUlEQVR42p2LoQoAIRAF/f8gNsNGMZhMK+YVtpkW/A/xA9714+COC1OGGQfA/eFRMrOvte6c8yYi/2kcYwRVhYig945SCmKM4XU0s73WwpwTIoLWGlJK595da8On65TYLg8AAAAASUVORK5CYII\x3d"/\x3e\x3celement name\x3d"volumeProgressCapBottom" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAECAYAAAC+0w63AAAASElEQVR42o3LIQ4AMQgFUe6v6EnwaDweyQ3aPcBf6poNyVaMm0cA6CwzZ0TA3WFmUFWIyPP9qIGjgeMX7gpywVVwFeTuaeFNL2bLq1AT4lm+AAAAAElFTkSuQmCC"/\x3e\x3celement name\x3d"volumeThumb" src\x3d"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAYAAAAmlE46AAABQElEQVR42p2SsWqDUBSGTYgpEqlLqNCxdHMoGTp079Y1kFJohrR5mzyCm4PpA2Rw1MlZg7gk6eSWXcxgzy//BWkbLBU+uZzz/derHq2ua+0/tK+e0BcGwlC4IEPW+nR+hNAcCffCVFiQKWsjOr12SBeuhJnv++uiKHZVVZUAa9TQo6OrMHa5FJ6DINgcj8f6cDjUeZ43YI0aenAEixnNEB48z/P3+32dZdmvoAcHLjPNDrM4jnfnQgo4PDIy2lhYbrfbU1cwTdOTuO/MaPZfg0mSlOK+MdPcXsIw7DwqHLgqiMc+rlardVcQDlx1VLzorfDquu7mXAg9ceZ0LfU78OgJGrLrRxRFn/IhSoA1agxN6BpqAEzhWnCEJ0pLMmfNoWOqAVAjZ3K3G0p3xGHNpqN/n9cBj2Dx5W0yZs1oD/kXpOphz005RgUAAAAASUVORK5CYII\x3d"/\x3e\x3c/elements\x3e\x3c/component\x3e\x3c/components\x3e\x3c/skin\x3e';this.xml= g.utils.parseXML(this.text);return this}})(jwplayer); (function(g){var h=g.html5,a=g.utils,c=g.events,e=c.state,b=a.css,d=a.isMobile(),f=document,u=".jwpreview",l=!0,m=!1;h.display=function(r,g){function z(b){if(aa&&(r.jwGetControls()||r.jwGetState()==e.PLAYING))aa(b);else if((!d||!r.jwGetControls())&&S.sendEvent(c.JWPLAYER_DISPLAY_CLICK),r.jwGetControls()){var j=(new Date).getTime();Y&&500>j-Y?(r.jwSetFullscreen(),Y=void 0):Y=(new Date).getTime();var k=a.bounds(p.parentNode.querySelector(".jwcontrolbar")),f=a.bounds(p),j=k.left-10-f.left,h=k.left+30- f.left,g=f.bottom-40,l=f.bottom,n=k.right-30-f.left,k=k.right+10-f.left;if(d&&!(b.x>=j&&b.x<=h&&b.y>=g&&b.y<=l)){if(b.x>=n&&b.x<=k&&b.y>=g&&b.y<=l){r.jwSetFullscreen();return}S.sendEvent(c.JWPLAYER_DISPLAY_CLICK);if(M)return}switch(r.jwGetState()){case e.PLAYING:case e.BUFFERING:r.jwPause();break;default:r.jwPlay()}}}function j(a,b){ba.showicons&&(a||b?(R.setRotation("buffer"==a?parseInt(ba.bufferrotation,10):0,parseInt(ba.bufferinterval,10)),R.setIcon(a),R.setText(b)):R.hide())}function q(a){s!= a?(s&&x(u,m),(s=a)?(a=new Image,a.addEventListener("load",t,m),a.src=s):(b("#"+p.id+" "+u,{"background-image":void 0}),x(u,m),A=K=0)):s&&!M&&x(u,l);w(r.jwGetState())}function C(a){clearTimeout(qa);qa=setTimeout(function(){w(a.newstate)},100)}function w(a){a=T?T:r?r.jwGetState():e.IDLE;if(a!=ca)switch(ca=a,R&&R.setRotation(0),a){case e.IDLE:!H&&!P&&(s&&!I&&x(u,l),a=!0,r._model&&!1===r._model.config.displaytitle&&(a=!1),j("play",F&&a?F.title:""));break;case e.BUFFERING:H=m;G.error&&G.error.setText(); P=m;j("buffer");break;case e.PLAYING:j();break;case e.PAUSED:j("play")}}function t(){A=this.width;K=this.height;w(r.jwGetState());v();s&&b("#"+p.id+" "+u,{"background-image":"url("+s+")"})}function D(a){H=l;j("error",a.message)}function v(){0<p.clientWidth*p.clientHeight&&a.stretch(r.jwGetStretching(),k,p.clientWidth,p.clientHeight,A,K)}function x(c,d){a.exists(Q[c])||(Q[c]=!1);Q[c]!=d&&(Q[c]=d,b("#"+p.id+" "+c,{opacity:d?1:0,visibility:d?"visible":"hidden"}))}var p,k,B,F,s,A,K,I=m,G={},H=m,P=m,Q= {},M,y,R,T,ca,ba=a.extend({showicons:l,bufferrotation:45,bufferinterval:100,fontcolor:"#ccc",overcolor:"#fff",fontsize:15,fontweight:""},r.skin.getComponentSettings("display"),g),S=new c.eventdispatcher,aa,Y;a.extend(this,S);this.clickHandler=z;var qa;this.forceState=function(a){T=a;w(a);this.show()};this.releaseState=function(a){T=null;w(a);this.show()};this.hidePreview=function(a){I=a;x(u,!a);a&&(M=!0)};this.setHiding=function(){M=!0};this.element=function(){return p};this.redraw=v;this.show=function(a){if(R&& (a||(T?T:r?r.jwGetState():e.IDLE)!=e.PLAYING))clearTimeout(y),y=void 0,p.style.display="block",R.show(),M=!1};this.hide=function(){R&&(R.hide(),M=!0)};this.setAlternateClickHandler=function(a){aa=a};this.revertAlternateClickHandler=function(){aa=void 0};p=f.createElement("div");p.id=r.id+"_display";p.className="jwdisplay";k=f.createElement("div");k.className="jwpreview jw"+r.jwGetStretching();p.appendChild(k);r.jwAddEventListener(c.JWPLAYER_PLAYER_STATE,C);r.jwAddEventListener(c.JWPLAYER_PLAYLIST_ITEM, function(){H=m;G.error&&G.error.setText();var a=(F=r.jwGetPlaylist()[r.jwGetPlaylistIndex()])?F.image:"";ca=void 0;q(a)});r.jwAddEventListener(c.JWPLAYER_PLAYLIST_COMPLETE,function(){P=l;j("replay");var a=r.jwGetPlaylist()[0];q(a.image)});r.jwAddEventListener(c.JWPLAYER_MEDIA_ERROR,D);r.jwAddEventListener(c.JWPLAYER_ERROR,D);d?(B=new a.touch(p),B.addEventListener(a.touchEvents.TAP,z)):p.addEventListener("click",z,m);B={font:ba.fontweight+" "+ba.fontsize+"px/"+(parseInt(ba.fontsize,10)+3)+"px Arial, Helvetica, sans-serif", color:ba.fontcolor};R=new h.displayicon(p.id+"_button",r,B,{color:ba.overcolor});p.appendChild(R.element());C({newstate:e.IDLE})};b(".jwdisplay",{position:"absolute",cursor:"pointer",width:"100%",height:"100%",overflow:"hidden"});b(".jwdisplay .jwpreview",{position:"absolute",width:"100%",height:"100%",background:"no-repeat center",overflow:"hidden",opacity:0});b(".jwdisplay, .jwdisplay *",{"-webkit-transition":"opacity .25s, background-image .25s, color .25s","-moz-transition":"opacity .25s, background-image .25s, color .25s", "-o-transition":"opacity .25s, background-image .25s, color .25s"})})(jwplayer); (function(g){var h=g.utils,a=h.css,c=document,e="none",b="100%";g.html5.displayicon=function(d,f,u,l){function m(a,b,d,e){var j=c.createElement("div");j.className=a;b&&b.appendChild(j);w&&r(j,a,"."+a,d,e);return j}function r(b,c,d,e,j){var k=n(c);"replayIcon"==c&&!k.src&&(k=n("playIcon"));k.src?(e=h.extend({},e),0<c.indexOf("Icon")&&(s=k.width|0),e.width=k.width,e["background-image"]="url("+k.src+")",e["background-size"]=k.width+"px "+k.height+"px",j=h.extend({},j),k.overSrc&&(j["background-image"]= "url("+k.overSrc+")"),h.isMobile()||a("#"+f.id+" .jwdisplay:hover "+d,j),a.style(w,{display:"table"})):a.style(w,{display:"none"});e&&a.style(b,e);F=k}function n(a){var b=C.getSkinElement("display",a);a=C.getSkinElement("display",a+"Over");return b?(b.overSrc=a&&a.src?a.src:"",b):{src:"",overSrc:"",width:0,height:0}}function z(){var b=x||0===s;a.style(p,{display:p.innerHTML&&b?"":e});K=b?30:0;j()}function j(){clearTimeout(A);0<K--&&(A=setTimeout(j,33));var c="px "+b,d=Math.ceil(Math.max(F.width,h.bounds(w).width- v.width-D.width)),c={"background-size":[D.width+c,d+c,v.width+c].join(", ")};w.parentNode&&(c.left=1==w.parentNode.clientWidth%2?"0.5px":"");a.style(w,c)}function q(){H=(H+G)%360;h.rotate(k,H)}var C=f.skin,w,t,D,v,x,p,k,B={},F,s=0,A=-1,K=0;this.element=function(){return w};this.setText=function(a){var b=p.style;p.innerHTML=a?a.replace(":",":\x3cbr\x3e"):"";b.height="0";b.display="block";if(a)for(;2<Math.floor(p.scrollHeight/c.defaultView.getComputedStyle(p,null).lineHeight.replace("px",""));)p.innerHTML= p.innerHTML.replace(/(.*) .*$/,"$1...");b.height="";b.display="";z()};this.setIcon=function(a){var b=B[a];b||(b=m("jwicon"),b.id=w.id+"_"+a);r(b,a+"Icon","#"+b.id);w.contains(k)?w.replaceChild(b,k):w.appendChild(b);k=b};var I,G=0,H;this.setRotation=function(a,b){clearInterval(I);H=0;G=a|0;0===G?q():I=setInterval(q,b)};var P=this.hide=function(){w.style.opacity=0};this.show=function(){w.style.opacity=1};w=m("jwdisplayIcon");w.id=d;t=n("background");D=n("capLeft");v=n("capRight");x=0<D.width*v.width; var Q={"background-image":"url("+D.src+"), url("+t.src+"), url("+v.src+")","background-position":"left,center,right","background-repeat":"no-repeat",padding:"0 "+v.width+"px 0 "+D.width+"px",height:t.height,"margin-top":t.height/-2};a("#"+d+" ",Q);h.isMobile()||(t.overSrc&&(Q["background-image"]="url("+D.overSrc+"), url("+t.overSrc+"), url("+v.overSrc+")"),a("#"+f.id+" .jwdisplay:hover "+("#"+d+" "),Q));p=m("jwtext",w,u,l);k=m("jwicon",w);f.jwAddEventListener(g.events.JWPLAYER_RESIZE,j);P();z()}; a(".jwplayer .jwdisplayIcon",{display:"table",cursor:"pointer",position:"relative","margin-left":"auto","margin-right":"auto",top:"50%"});a(".jwplayer .jwdisplayIcon div",{position:"relative",display:"table-cell","vertical-align":"middle","background-repeat":"no-repeat","background-position":"center"});a(".jwplayer .jwdisplayIcon div",{"vertical-align":"middle"},!0);a(".jwplayer .jwdisplayIcon .jwtext",{color:"#fff",padding:"0 1px","max-width":"300px","overflow-y":"hidden","text-align":"center","-webkit-user-select":e, "-moz-user-select":e,"-ms-user-select":e,"user-select":e})})(jwplayer); (function(g){var h=g.html5,a=g.utils,c=a.css,e=a.bounds,b=".jwdockbuttons",d=document,f="none",u="block";h.dock=function(g,m){function r(a){return!a||!a.src?{}:{background:"url("+a.src+") center","background-size":a.width+"px "+a.height+"px"}}function n(b,d){var e=q(b);c(z("."+b),a.extend(r(e),{width:e.width}));return j("div",b,d)}function z(a){return"#"+t+" "+(a?a:"")}function j(a,b,c){a=d.createElement(a);b&&(a.className=b);c&&c.appendChild(a);return a}function q(a){return(a=D.getSkinElement("dock", a))?a:{width:0,height:0,src:""}}function C(){c(b+" .capLeft, "+b+" .capRight",{display:v?u:f})}var w=a.extend({},{iconalpha:0.75,iconalphaactive:0.5,iconalphaover:1,margin:8},m),t=g.id+"_dock",D=g.skin,v=0,x={},p={},k,B,F,s=this;s.redraw=function(){e(k)};s.element=function(){return k};s.offset=function(a){c(z(),{"margin-left":a})};s.hide=function(){s.visible&&(s.visible=!1,k.style.opacity=0,clearTimeout(F),F=setTimeout(function(){k.style.display=f},250))};s.showTemp=function(){s.visible||(k.style.opacity= 0,k.style.display=u)};s.hideTemp=function(){s.visible||(k.style.display=f)};s.show=function(){!s.visible&&v&&(s.visible=!0,k.style.display=u,clearTimeout(F),F=setTimeout(function(){k.style.opacity=1},0))};s.addButton=function(b,d,f,g){if(!x[g]){var r=j("div","divider",B),l=j("button",null,B),n=j("div",null,l);n.id=t+"_"+g;n.innerHTML="\x26nbsp;";c("#"+n.id,{"background-image":b});"string"==typeof f&&(f=new Function(f));a.isMobile()?(new a.touch(l)).addEventListener(a.touchEvents.TAP,function(a){f(a)}): l.addEventListener("click",function(a){f(a);a.preventDefault()});x[g]={element:l,label:d,divider:r,icon:n};if(d){var q=new h.overlay(n.id+"_tooltip",D,!0);b=j("div");b.id=n.id+"_label";b.innerHTML=d;c("#"+b.id,{padding:3});q.setContents(b);if(!a.isMobile()){var m;l.addEventListener("mouseover",function(){clearTimeout(m);var b=p[g],d,j;d=e(x[g].icon);b.offsetX(0);j=e(k);c("#"+b.element().id,{left:d.left-j.left+d.width/2});d=e(b.element());j.left>d.left&&b.offsetX(j.left-d.left+8);q.show();a.foreach(p, function(a,b){a!=g&&b.hide()})},!1);l.addEventListener("mouseout",function(){m=setTimeout(q.hide,100)},!1);k.appendChild(q.element());p[g]=q}}v++;C()}};s.removeButton=function(a){if(x[a]){B.removeChild(x[a].element);B.removeChild(x[a].divider);var b=document.getElementById(""+t+"_"+a+"_tooltip");b&&k.removeChild(b);delete x[a];v--;C()}};s.numButtons=function(){return v};s.visible=!1;k=j("div","jwdock");B=j("div","jwdockbuttons");k.appendChild(B);k.id=t;var A=q("button"),K=q("buttonOver"),I=q("buttonActive"); A&&(c(z(),{height:A.height,padding:w.margin}),c(b,{height:A.height}),c(z("button"),a.extend(r(A),{width:A.width,cursor:"pointer",border:f})),c(z("button:hover"),r(K)),c(z("button:active"),r(I)),c(z("button\x3ediv"),{opacity:w.iconalpha}),c(z("button:hover\x3ediv"),{opacity:w.iconalphaover}),c(z("button:active\x3ediv"),{opacity:w.iconalphaactive}),c(z(".jwoverlay"),{top:w.margin+A.height}),n("capLeft",B),n("capRight",B),n("divider"));setTimeout(function(){e(k)})};c(".jwdock",{opacity:0,display:f}); c(".jwdock \x3e *",{height:"100%","float":"left"});c(".jwdock \x3e .jwoverlay",{height:"auto","float":f,"z-index":99});c(b+" button",{position:"relative"});c(b+" \x3e *",{height:"100%","float":"left"});c(b+" .divider",{display:f});c(b+" button ~ .divider",{display:u});c(b+" .capLeft, "+b+" .capRight",{display:f});c(b+" .capRight",{"float":"right"});c(b+" button \x3e div",{left:0,right:0,top:0,bottom:0,margin:5,position:"absolute","background-position":"center","background-repeat":"no-repeat"});a.transitionStyle(".jwdock", "background .25s, opacity .25s");a.transitionStyle(".jwdock .jwoverlay","opacity .25s");a.transitionStyle(b+" button div","opacity .25s")})(jwplayer); (function(g){var h=g.html5,a=g.utils,c=g.events,e=c.state,b=g.playlist;h.instream=function(d,f,g,l){function m(a){C(a.type,a);M&&d.jwInstreamDestroy(!1,y)}function r(a){C(a.type,a);j(null)}function n(a){C(a.type,a)}function z(){H&&H.releaseState(y.jwGetState());I.play()}function j(){if(v&&x+1<v.length){x++;var e=v[x];D=new b.item(e);M.setPlaylist([e]);var j;p&&(j=p[x]);k=a.extend(t,j);I.load(M.playlist[0]);B.reset(k.skipoffset||-1);T=setTimeout(function(){C(c.JWPLAYER_PLAYLIST_ITEM,{index:x},!0)}, 0)}else T=setTimeout(function(){C(c.JWPLAYER_PLAYLIST_COMPLETE,{},!0);d.jwInstreamDestroy(!0,y)},0)}function q(a){a.width&&a.height&&(H&&H.releaseState(y.jwGetState()),g.resizeMedia())}function C(a,b){b=b||{};t.tag&&!b.tag&&(b.tag=t.tag);P.sendEvent(a,b)}function w(){G&&G.redraw();H&&H.redraw()}var t={controlbarseekable:"never",controlbarpausable:!0,controlbarstoppable:!0,loadingmessage:"Loading ad",playlistclickable:!0,skipoffset:null,tag:null},D,v,x=0,p,k={controlbarseekable:"never",controlbarpausable:!1, controlbarstoppable:!1},B,F,s,A,K,I,G,H,P=new c.eventdispatcher,Q,M,y=this,R=!0,T=-1;d.jwAddEventListener(c.JWPLAYER_RESIZE,w);d.jwAddEventListener(c.JWPLAYER_FULLSCREEN,function(b){w();!b.fullscreen&&a.isIPad()&&(M.state===e.PAUSED?H.show(!0):M.state===e.PLAYING&&H.hide())});y.init=function(){F=l.detachMedia();I=new h.video(F);I.addGlobalListener(n);I.addEventListener(c.JWPLAYER_MEDIA_META,q);I.addEventListener(c.JWPLAYER_MEDIA_COMPLETE,j);I.addEventListener(c.JWPLAYER_MEDIA_BUFFER_FULL,z);I.addEventListener(c.JWPLAYER_MEDIA_ERROR, m);I.addEventListener(c.JWPLAYER_MEDIA_TIME,function(a){B&&B.updateSkipTime(a.position,a.duration)});I.attachMedia();I.mute(f.mute);I.volume(f.volume);M=new h.model({},I);M.setVolume(f.volume);M.setMute(f.mute);K=f.playlist[f.item];s=F.currentTime;l.checkBeforePlay()||0===s?(A=e.PLAYING,R=!1):A=d.jwGetState()===e.IDLE||f.getVideo().checkComplete()?e.IDLE:e.PLAYING;A==e.PLAYING&&F.pause();H=new h.display(y);H.forceState(e.BUFFERING);Q=document.createElement("div");Q.id=y.id+"_instream_container";Q.appendChild(H.element()); G=new h.controlbar(y);G.instreamMode(!0);Q.appendChild(G.element());d.jwGetControls()?(G.show(),H.show()):(G.hide(),H.hide());g.setupInstream(Q,G,H,M);w();y.jwInstreamSetText(t.loadingmessage)};y.load=function(j,f){if(a.isAndroid(2.3))m({type:c.JWPLAYER_ERROR,message:"Error loading instream: Cannot play instream on Android 2.3"});else{C(c.JWPLAYER_PLAYLIST_ITEM,{index:x},!0);var l=a.bounds(document.getElementById(d.id)),n=g.getSafeRegion();if("object"==a.typeOf(j))D=new b.item(j),M.setPlaylist([j]), k=a.extend(t,f),B=new h.adskipbutton(d,l.height-(n.y+n.height)+10,k.skipMessage,k.skipText),B.addEventListener(c.JWPLAYER_AD_SKIPPED,r),B.reset(k.skipoffset||-1);else if("array"==a.typeOf(j)){var q;f&&(p=f,q=f[x]);k=a.extend(t,q);B=new h.adskipbutton(d,l.height-(n.y+n.height)+10,k.skipMessage,k.skipText);B.addEventListener(c.JWPLAYER_AD_SKIPPED,r);B.reset(k.skipoffset||-1);v=j;j=v[x];D=new b.item(j);M.setPlaylist([j])}d.jwGetControls()?B.show():B.hide();l=B.element();Q.appendChild(l);M.addEventListener(c.JWPLAYER_ERROR, m);H.setAlternateClickHandler(function(a){d.jwGetControls()?(M.state==e.PAUSED?y.jwInstreamPlay():y.jwInstreamPause(),a.hasControls=!0):a.hasControls=!1;C(c.JWPLAYER_INSTREAM_CLICK,a)});a.isIE()&&F.parentElement.addEventListener("click",H.clickHandler);g.addEventListener(c.JWPLAYER_AD_SKIPPED,r);I.load(M.playlist[0])}};y.jwInstreamDestroy=function(a){if(M){clearTimeout(T);T=-1;I.detachMedia();l.attachMedia();A!=e.IDLE?f.getVideo().load(K,!1):f.getVideo().stop();P.resetEventListeners();I.resetEventListeners(); M.resetEventListeners();if(G)try{G.element().parentNode.removeChild(G.element())}catch(b){}H&&(F&&F.parentElement&&F.parentElement.removeEventListener("click",H.clickHandler),H.revertAlternateClickHandler());C(c.JWPLAYER_INSTREAM_DESTROYED,{reason:a?"complete":"destroyed"},!0);A==e.PLAYING&&(F.play(),f.playlist[f.item]==K&&R&&f.getVideo().seek(s));g.destroyInstream(I.audioMode());M=null}};y.jwInstreamAddEventListener=function(a,b){P.addEventListener(a,b)};y.jwInstreamRemoveEventListener=function(a, b){P.removeEventListener(a,b)};y.jwInstreamPlay=function(){I.play(!0);f.state=e.PLAYING;H.show()};y.jwInstreamPause=function(){I.pause(!0);f.state=e.PAUSED;d.jwGetControls()&&H.show()};y.jwInstreamSeek=function(a){I.seek(a)};y.jwInstreamSetText=function(a){G.setText(a)};y.jwInstreamState=function(){return f.state};y.setControls=function(a){a?B.show():B.hide()};y.jwPlay=function(){"true"==k.controlbarpausable.toString().toLowerCase()&&y.jwInstreamPlay()};y.jwPause=function(){"true"==k.controlbarpausable.toString().toLowerCase()&& y.jwInstreamPause()};y.jwStop=function(){"true"==k.controlbarstoppable.toString().toLowerCase()&&(d.jwInstreamDestroy(!1,y),d.jwStop())};y.jwSeek=function(a){switch(k.controlbarseekable.toLowerCase()){case "always":y.jwInstreamSeek(a);break;case "backwards":M.position>a&&y.jwInstreamSeek(a)}};y.jwSeekDrag=function(a){M.seekDrag(a)};y.jwGetPosition=function(){};y.jwGetDuration=function(){};y.jwGetWidth=d.jwGetWidth;y.jwGetHeight=d.jwGetHeight;y.jwGetFullscreen=d.jwGetFullscreen;y.jwSetFullscreen=d.jwSetFullscreen; y.jwGetVolume=function(){return f.volume};y.jwSetVolume=function(a){M.setVolume(a);d.jwSetVolume(a)};y.jwGetMute=function(){return f.mute};y.jwSetMute=function(a){M.setMute(a);d.jwSetMute(a)};y.jwGetState=function(){return!M?e.IDLE:M.state};y.jwGetPlaylist=function(){return[D]};y.jwGetPlaylistIndex=function(){return 0};y.jwGetStretching=function(){return f.config.stretching};y.jwAddEventListener=function(a,b){P.addEventListener(a,b)};y.jwRemoveEventListener=function(a,b){P.removeEventListener(a,b)}; y.jwSetCurrentQuality=function(){};y.jwGetQualityLevels=function(){return[]};y.jwGetControls=function(){return d.jwGetControls()};y.skin=d.skin;y.id=d.id+"_instream";return y}})(window.jwplayer); (function(g){var h=g.utils,a=h.css,c=g.events.state,e=g.html5.logo=function(b,d){function f(a){h.exists(a)&&a.stopPropagation&&a.stopPropagation();if(!z||!m.link)u.jwGetState()==c.IDLE||u.jwGetState()==c.PAUSED?u.jwPlay():u.jwPause();z&&m.link&&(u.jwPause(),u.jwSetFullscreen(!1),window.open(m.link,m.linktarget))}var u=b,l=u.id+"_logo",m,r,n=e.defaults,z=!1;this.resize=function(){};this.element=function(){return r};this.offset=function(b){a("#"+l+" ",{"margin-bottom":b})};this.position=function(){return m.position}; this.margin=function(){return parseInt(m.margin)};this.hide=function(a){if(m.hide||a)z=!1,r.style.visibility="hidden",r.style.opacity=0};this.show=function(){z=!0;r.style.visibility="visible";r.style.opacity=1};var j="o";u.edition&&(j=u.edition(),j="pro"==j?"p":"premium"==j?"r":"ads"==j?"a":"free"==j?"f":"o");if("o"==j||"f"==j)n.link="http://www.longtailvideo.com/jwpabout/?a\x3dl\x26v\x3d"+g.version+"\x26m\x3dh\x26e\x3d"+j;m=h.extend({},n,d);m.hide="true"==m.hide.toString();r=document.createElement("img"); r.className="jwlogo";r.id=l;if(m.file){var n=/(\w+)-(\w+)/.exec(m.position),j={},q=m.margin;3==n.length?(j[n[1]]=q,j[n[2]]=q):j.top=j.right=q;a("#"+l+" ",j);r.src=(m.prefix?m.prefix:"")+m.file;h.isMobile()?(new h.touch(r)).addEventListener(h.touchEvents.TAP,f):r.onclick=f}else r.style.display="none";return this};e.defaults={prefix:h.repo(),file:"logo.png",linktarget:"_top",margin:8,hide:!1,position:"top-right"};a(".jwlogo",{cursor:"pointer",position:"absolute","z-index":100,opacity:0});h.transitionStyle(".jwlogo", "visibility .25s, opacity .25s")})(jwplayer); (function(g){var h=g.html5,a=g.utils,c=a.css;h.menu=function(e,b,d,f){function g(a){return!a||!a.src?{}:{background:"url("+a.src+") no-repeat left","background-size":a.width+"px "+a.height+"px"}}function l(a,b){return function(){C(a);n&&n(b)}}function m(a,b){var c=document.createElement("div");a&&(c.className=a);b&&b.appendChild(c);return c}function r(a){return(a=d.getSkinElement("tooltip",a))?a:{width:0,height:0,src:void 0}}var n=f,z=new h.overlay(b+"_overlay",d);f=a.extend({fontcase:void 0,fontcolor:"#cccccc", fontsize:11,fontweight:void 0,activecolor:"#ffffff",overcolor:"#ffffff"},d.getComponentSettings("tooltip"));var j,q=[];this.element=function(){return z.element()};this.addOption=function(c,d){var e=m("jwoption",j);e.id=b+"_option_"+d;e.innerHTML=c;a.isMobile()?(new a.touch(e)).addEventListener(a.touchEvents.TAP,l(q.length,d)):e.addEventListener("click",l(q.length,d));q.push(e)};this.clearOptions=function(){for(;0<q.length;)j.removeChild(q.pop())};var C=this.setActive=function(a){for(var b=0;b<q.length;b++){var c= q[b];c.className=c.className.replace(" active","");b==a&&(c.className+=" active")}};this.show=z.show;this.hide=z.hide;this.offsetX=z.offsetX;this.positionX=z.positionX;this.constrainX=z.constrainX;j=m("jwmenu");j.id=b;var w=r("menuTop"+e);e=r("menuOption");var t=r("menuOptionOver"),D=r("menuOptionActive");if(w&&w.image){var v=new Image;v.src=w.src;v.width=w.width;v.height=w.height;j.appendChild(v)}e&&(w="#"+b+" .jwoption",c(w,a.extend(g(e),{height:e.height,color:f.fontcolor,"padding-left":e.width, font:f.fontweight+" "+f.fontsize+"px Arial,Helvetica,sans-serif","line-height":e.height,"text-transform":"upper"==f.fontcase?"uppercase":void 0})),c(w+":hover",a.extend(g(t),{color:f.overcolor})),c(w+".active",a.extend(g(D),{color:f.activecolor})));z.setContents(j)};c("."+"jwmenu jwoption".replace(/ /g," ."),{cursor:"pointer",position:"relative"})})(jwplayer); (function(g){var h=jwplayer.utils,a=jwplayer.events;g.model=function(c,e){function b(a){var b=r[a.type]?r[a.type].split(","):[],c,e;if(0<b.length){for(c=0;c<b.length;c++){var f=b[c].split("-\x3e"),h=f[0],f=f[1]?f[1]:h;d[f]!=a[h]&&(d[f]=a[h],e=!0)}e&&d.sendEvent(a.type,a)}else d.sendEvent(a.type,a)}var d=this,f,u=h.getCookies(),l={controlbar:{},display:{}},m={autostart:!1,controls:!0,debug:void 0,fullscreen:!1,height:320,mobilecontrols:!1,mute:!1,playlist:[],playlistposition:"none",playlistsize:180, playlistlayout:"extended",repeat:!1,skin:void 0,stretching:h.stretching.UNIFORM,width:480,volume:90},r={};r[a.JWPLAYER_MEDIA_MUTE]="mute";r[a.JWPLAYER_MEDIA_VOLUME]="volume";r[a.JWPLAYER_PLAYER_STATE]="newstate-\x3estate";r[a.JWPLAYER_MEDIA_BUFFER]="bufferPercent-\x3ebuffer";r[a.JWPLAYER_MEDIA_TIME]="position,duration";d.setVideo=function(a){f&&f.removeGlobalListener(b);f=a;f.getTag();f.volume(d.volume);f.mute(d.mute);f.addGlobalListener(b)};d.getVideo=function(){return f};d.seekDrag=function(a){f.seekDrag(a)}; d.setFullscreen=function(b){b!=d.fullscreen&&(d.fullscreen=b,d.sendEvent(a.JWPLAYER_FULLSCREEN,{fullscreen:b}))};d.setPlaylist=function(b){d.playlist=h.filterPlaylist(b);0==d.playlist.length?d.sendEvent(a.JWPLAYER_ERROR,{message:"Error loading playlist: No playable sources found"}):(d.sendEvent(a.JWPLAYER_PLAYLIST_LOADED,{playlist:jwplayer(d.id).getPlaylist()}),d.item=-1,d.setItem(0))};d.setItem=function(b){var c=!1;b==d.playlist.length||-1>b?(b=0,c=!0):b=-1==b||b>d.playlist.length?d.playlist.length- 1:b;if(c||b!=d.item)d.item=b,d.sendEvent(a.JWPLAYER_PLAYLIST_ITEM,{index:d.item})};d.setVolume=function(c){d.mute&&0<c&&d.setMute(!1);c=Math.round(c);d.mute||h.saveCookie("volume",c);b({type:a.JWPLAYER_MEDIA_VOLUME,volume:c});f.volume(c)};d.setMute=function(c){h.exists(c)||(c=!d.mute);h.saveCookie("mute",c);b({type:a.JWPLAYER_MEDIA_MUTE,mute:c});f.mute(c)};d.componentConfig=function(a){return l[a]};h.extend(d,new a.eventdispatcher);var n=d,z=h.extend({},m,u,c);h.foreach(z,function(a,b){z[a]=h.serialize(b)}); n.config=z;h.extend(d,{id:c.id,state:a.state.IDLE,duration:-1,position:0,buffer:0},d.config);d.playlist=[];d.setItem(0);d.setVideo(e?e:new g.video)}})(jwplayer.html5); (function(g){var h=g.utils,a=h.css,c=h.transitionStyle,e="top",b="bottom",d="right",f="left",u=document,l={fontcase:void 0,fontcolor:"#ffffff",fontsize:12,fontweight:void 0,activecolor:"#ffffff",overcolor:"#ffffff"};g.html5.overlay=function(c,g,n){function z(a){return"#"+D+(a?" ."+a:"")}function j(a,b){var c=u.createElement("div");a&&(c.className=a);b&&b.appendChild(c);return c}function q(b,c){var d;d=(d=v.getSkinElement("tooltip",b))?d:{width:0,height:0,src:"",image:void 0,ready:!1};var e=j(c,p); a.style(e,C(d));return[e,d]}function C(a){return{background:"url("+a.src+") center","background-size":a.width+"px "+a.height+"px"}}function w(c,k){k||(k="");var j=q("cap"+c+k,"jwborder jw"+c+(k?k:"")),g=j[0],j=j[1],l=h.extend(C(j),{width:c==f||k==f||c==d||k==d?j.width:void 0,height:c==e||k==e||c==b||k==b?j.height:void 0});l[c]=c==b&&!x||c==e&&x?B.height:0;k&&(l[k]=0);a.style(g,l);g={};l={};j={left:j.width,right:j.width,top:(x?B.height:0)+j.height,bottom:(x?0:B.height)+j.height};k&&(g[k]=j[k],g[c]= 0,l[c]=j[c],l[k]=0,a(z("jw"+c),g),a(z("jw"+k),l),s[c]=j[c],s[k]=j[k])}var t=this,D=c,v=g,x=n,p,k,B,F;c=h.extend({},l,v.getComponentSettings("tooltip"));var s={};t.element=function(){return p};t.setContents=function(a){h.empty(k);k.appendChild(a)};t.positionX=function(b){a.style(p,{left:Math.round(b)})};t.constrainX=function(b,c){if(t.showing&&0!==b.width&&t.offsetX(0)){c&&a.unblock();var d=h.bounds(p);0!==d.width&&(d.right>b.right?t.offsetX(b.right-d.right):d.left<b.left&&t.offsetX(b.left-d.left))}}; t.offsetX=function(b){b=Math.round(b);var c=p.clientWidth;0!==c&&(a.style(p,{"margin-left":Math.round(-c/2)+b}),a.style(F,{"margin-left":Math.round(-B.width/2)-b}));return c};t.borderWidth=function(){return s.left};t.show=function(){t.showing=!0;a.style(p,{opacity:1,visibility:"visible"})};t.hide=function(){t.showing=!1;a.style(p,{opacity:0,visibility:"hidden"})};p=j(".jwoverlay".replace(".",""));p.id=D;g=q("arrow","jwarrow");F=g[0];B=g[1];a.style(F,{position:"absolute",bottom:x?void 0:0,top:x?0: void 0,width:B.width,height:B.height,left:"50%"});w(e,f);w(b,f);w(e,d);w(b,d);w(f);w(d);w(e);w(b);g=q("background","jwback");a.style(g[0],{left:s.left,right:s.right,top:s.top,bottom:s.bottom});k=j("jwcontents",p);a(z("jwcontents")+" *",{color:c.fontcolor,font:c.fontweight+" "+c.fontsize+"px Arial,Helvetica,sans-serif","text-transform":"upper"==c.fontcase?"uppercase":void 0});x&&h.transform(z("jwarrow"),"rotate(180deg)");a.style(p,{padding:s.top+1+"px "+s.right+"px "+(s.bottom+1)+"px "+s.left+"px"}); t.showing=!1};a(".jwoverlay",{position:"absolute",visibility:"hidden",opacity:0});a(".jwoverlay .jwcontents",{position:"relative","z-index":1});a(".jwoverlay .jwborder",{position:"absolute","background-size":"100% 100%"},!0);a(".jwoverlay .jwback",{position:"absolute","background-size":"100% 100%"});c(".jwoverlay","opacity .25s, visibility .25s")})(jwplayer); (function(g){var h=g.html5,a=g.utils;h.player=function(c){function e(b){var c={description:b.description,file:b.file,image:b.image,mediaid:b.mediaid,title:b.title};a.foreach(b,function(a,b){c[a]=b});c.sources=[];c.tracks=[];0<b.sources.length&&a.foreach(b.sources,function(a,b){c.sources.push({file:b.file,type:b.type?b.type:void 0,label:b.label,"default":b["default"]?!0:!1})});0<b.tracks.length&&a.foreach(b.tracks,function(a,b){c.tracks.push({file:b.file,kind:b.kind?b.kind:void 0,label:b.label,"default":b["default"]? !0:!1})});!b.file&&0<b.sources.length&&(c.file=b.sources[0].file);return c}function b(a){return function(){return f[a]}}var d=this,f,u,l,m;f=new h.model(c);d.id=f.id;a.css.block(d.id);u=new h.view(d,f);l=new h.controller(f,u);d._model=f;d.jwPlay=l.play;d.jwPause=l.pause;d.jwStop=l.stop;d.jwSeek=l.seek;d.jwSetVolume=l.setVolume;d.jwSetMute=l.setMute;d.jwLoad=function(a){d.jwInstreamDestroy();l.load(a)};d.jwPlaylistNext=l.next;d.jwPlaylistPrev=l.prev;d.jwPlaylistItem=l.item;d.jwSetFullscreen=l.setFullscreen; d.jwResize=u.resize;d.jwSeekDrag=f.seekDrag;d.jwGetQualityLevels=l.getQualityLevels;d.jwGetCurrentQuality=l.getCurrentQuality;d.jwSetCurrentQuality=l.setCurrentQuality;d.jwGetCaptionsList=l.getCaptionsList;d.jwGetCurrentCaptions=l.getCurrentCaptions;d.jwSetCurrentCaptions=l.setCurrentCaptions;d.jwGetSafeRegion=u.getSafeRegion;d.jwForceState=u.forceState;d.jwReleaseState=u.releaseState;d.jwGetPlaylistIndex=b("item");d.jwGetPosition=b("position");d.jwGetDuration=b("duration");d.jwGetBuffer=b("buffer"); d.jwGetWidth=b("width");d.jwGetHeight=b("height");d.jwGetFullscreen=b("fullscreen");d.jwGetVolume=b("volume");d.jwGetMute=b("mute");d.jwGetState=b("state");d.jwGetStretching=b("stretching");d.jwGetPlaylist=function(){for(var a=f.playlist,b=[],c=0;c<a.length;c++)b.push(e(a[c]));return b};d.jwGetControls=b("controls");d.jwDetachMedia=l.detachMedia;d.jwAttachMedia=l.attachMedia;d.jwPlayAd=function(a){var b=g(d.id).plugins;b.vast&&b.vast.jwPlayAd(a)};d.jwPauseAd=function(){var a=g(d.id).plugins;a.googima&& a.googima.jwPauseAd()};d.jwInitInstream=function(){d.jwInstreamDestroy();m=new h.instream(d,f,u,l);m.init()};d.jwLoadItemInstream=function(a,b){if(!m)throw"Instream player undefined";m.load(a,b)};d.jwLoadArrayInstream=function(a,b){if(!m)throw"Instream player undefined";m.load(a,b)};d.jwSetControls=function(a){u.setControls(a);m&&m.setControls(a)};d.jwInstreamPlay=function(){m&&m.jwInstreamPlay()};d.jwInstreamPause=function(){m&&m.jwInstreamPause()};d.jwInstreamState=function(){return m?m.jwInstreamState(): ""};d.jwInstreamDestroy=function(a,b){if(b=b||m)b.jwInstreamDestroy(a||!1),b===m&&(m=void 0)};d.jwInstreamAddEventListener=function(a,b){m&&m.jwInstreamAddEventListener(a,b)};d.jwInstreamRemoveEventListener=function(a,b){m&&m.jwInstreamRemoveEventListener(a,b)};d.jwPlayerDestroy=function(){u&&u.destroy()};d.jwInstreamSetText=function(a){m&&m.jwInstreamSetText(a)};d.jwIsBeforePlay=function(){return l.checkBeforePlay()};d.jwIsBeforeComplete=function(){return f.getVideo().checkComplete()};d.jwSetCues= u.addCues;d.jwAddEventListener=l.addEventListener;d.jwRemoveEventListener=l.removeEventListener;d.jwDockAddButton=u.addButton;d.jwDockRemoveButton=u.removeButton;c=new h.setup(f,u,l);c.addEventListener(g.events.JWPLAYER_READY,function(b){l.playerReady(b);a.css.unblock(d.id)});c.addEventListener(g.events.JWPLAYER_ERROR,function(b){a.log("There was a problem setting up the player: ",b);a.css.unblock(d.id)});c.start()}})(window.jwplayer); (function(g){var h={size:180,backgroundcolor:"#333333",fontcolor:"#999999",overcolor:"#CCCCCC",activecolor:"#CCCCCC",titlecolor:"#CCCCCC",titleovercolor:"#FFFFFF",titleactivecolor:"#FFFFFF",fontweight:"normal",titleweight:"normal",fontsize:11,titlesize:13},a=jwplayer.events,c=jwplayer.utils,e=c.css,b=c.isMobile(),d=document;g.playlistcomponent=function(f,u){function l(a){return"#"+q.id+(a?" ."+a:"")}function m(a,b){var c=d.createElement(a);b&&(c.className=b);return c}function r(a){return function(){v= a;n.jwPlaylistItem(a);n.jwPlay(!0)}}var n=f,z=n.skin,j=c.extend({},h,n.skin.getComponentSettings("playlist"),u),q,C,w,t,D=-1,v,x,p=76,k={background:void 0,divider:void 0,item:void 0,itemOver:void 0,itemImage:void 0,itemActive:void 0},B,F=this;F.element=function(){return q};F.redraw=function(){x&&x.redraw()};F.show=function(){c.show(q)};F.hide=function(){c.hide(q)};q=m("div","jwplaylist");q.id=n.id+"_jwplayer_playlistcomponent";B="basic"==n._model.playlistlayout;C=m("div","jwlistcontainer");q.appendChild(C); c.foreach(k,function(a){k[a]=z.getSkinElement("playlist",a)});B&&(p=32);k.divider&&(p+=k.divider.height);var s=0,A=0,K=0;c.clearCss(l());e(l(),{"background-color":j.backgroundcolor});e(l("jwlist"),{"background-image":k.background?" url("+k.background.src+")":""});e(l("jwlist *"),{color:j.fontcolor,font:j.fontweight+" "+j.fontsize+"px Arial, Helvetica, sans-serif"});k.itemImage?(s=(p-k.itemImage.height)/2+"px ",A=k.itemImage.width,K=k.itemImage.height):(A=4*p/3,K=p);k.divider&&e(l("jwplaylistdivider"), {"background-image":"url("+k.divider.src+")","background-size":"100% "+k.divider.height+"px",width:"100%",height:k.divider.height});e(l("jwplaylistimg"),{height:K,width:A,margin:s?s+"0 "+s+s:"0 5px 0 0"});e(l("jwlist li"),{"background-image":k.item?"url("+k.item.src+")":"",height:p,overflow:"hidden","background-size":"100% "+p+"px",cursor:"pointer"});s={overflow:"hidden"};""!==j.activecolor&&(s.color=j.activecolor);k.itemActive&&(s["background-image"]="url("+k.itemActive.src+")");e(l("jwlist li.active"), s);e(l("jwlist li.active .jwtitle"),{color:j.titleactivecolor});e(l("jwlist li.active .jwdescription"),{color:j.activecolor});s={overflow:"hidden"};""!==j.overcolor&&(s.color=j.overcolor);k.itemOver&&(s["background-image"]="url("+k.itemOver.src+")");b||(e(l("jwlist li:hover"),s),e(l("jwlist li:hover .jwtitle"),{color:j.titleovercolor}),e(l("jwlist li:hover .jwdescription"),{color:j.overcolor}));e(l("jwtextwrapper"),{height:p,position:"relative"});e(l("jwtitle"),{overflow:"hidden",display:"inline-block", height:B?p:20,color:j.titlecolor,"font-size":j.titlesize,"font-weight":j.titleweight,"margin-top":B?"0 10px":10,"margin-left":10,"margin-right":10,"line-height":B?p:20});e(l("jwdescription"),{display:"block","font-size":j.fontsize,"line-height":18,"margin-left":10,"margin-right":10,overflow:"hidden",height:36,position:"relative"});n.jwAddEventListener(a.JWPLAYER_PLAYLIST_LOADED,function(){C.innerHTML="";for(var a=n.jwGetPlaylist(),d=[],f=0;f<a.length;f++)a[f]["ova.hidden"]||d.push(a[f]);if(w=d){a= m("ul","jwlist");a.id=q.id+"_ul"+Math.round(1E7*Math.random());t=a;for(a=0;a<w.length;a++){var j=a,d=w[j],f=m("li","jwitem"),h=void 0;f.id=t.id+"_item_"+j;0<j?(h=m("div","jwplaylistdivider"),f.appendChild(h)):(j=k.divider?k.divider.height:0,f.style.height=p-j+"px",f.style["background-size"]="100% "+(p-j)+"px");j=m("div","jwplaylistimg jwfill");h=void 0;d["playlist.image"]&&k.itemImage?h=d["playlist.image"]:d.image&&k.itemImage?h=d.image:k.itemImage&&(h=k.itemImage.src);h&&!B&&(e("#"+f.id+" .jwplaylistimg", {"background-image":h}),f.appendChild(j));j=m("div","jwtextwrapper");h=m("span","jwtitle");h.innerHTML=d&&d.title?d.title:"";j.appendChild(h);d.description&&!B&&(h=m("span","jwdescription"),h.innerHTML=d.description,j.appendChild(h));f.appendChild(j);d=f;b?(new c.touch(d)).addEventListener(c.touchEvents.TAP,r(a)):d.onclick=r(a);t.appendChild(d)}D=n.jwGetPlaylistIndex();C.appendChild(t);x=new g.playlistslider(q.id+"_slider",n.skin,q,t)}});n.jwAddEventListener(a.JWPLAYER_PLAYLIST_ITEM,function(a){0<= D&&(d.getElementById(t.id+"_item_"+D).className="jwitem",D=a.index);d.getElementById(t.id+"_item_"+a.index).className="jwitem active";a=n.jwGetPlaylistIndex();a!=v&&(v=-1,x&&x.visible()&&x.thumbPosition(a/(n.jwGetPlaylist().length-1)))});n.jwAddEventListener(a.JWPLAYER_RESIZE,function(){F.redraw()});return this};e(".jwplaylist",{position:"absolute",width:"100%",height:"100%"});c.dragStyle(".jwplaylist","none");e(".jwplaylist .jwplaylistimg",{position:"relative",width:"100%","float":"left",margin:"0 5px 0 0", background:"#000",overflow:"hidden"});e(".jwplaylist .jwlist",{position:"absolute",width:"100%","list-style":"none",margin:0,padding:0,overflow:"hidden"});e(".jwplaylist .jwlistcontainer",{position:"absolute",overflow:"hidden",width:"100%",height:"100%"});e(".jwplaylist .jwlist li",{width:"100%"});e(".jwplaylist .jwtextwrapper",{overflow:"hidden"});e(".jwplaylist .jwplaylistdivider",{position:"absolute"});b&&c.transitionStyle(".jwplaylist .jwlist","top .35s")})(jwplayer.html5); (function(g){function h(){var a=[],b;for(b=0;b<arguments.length;b++)a.push(".jwplaylist ."+arguments[b]);return a.join(",")}var a=jwplayer.utils,c=a.touchEvents,e=a.css,b=document,d=window,f=void 0;g.playlistslider=function(h,g,m,r){function n(a){return"#"+k.id+(a?" ."+a:"")}function z(a,c,d,k){var j=b.createElement("div");a&&(j.className=a,c&&e(n(a),{"background-image":c.src?c.src:f,"background-repeat":k?"repeat-y":"no-repeat",height:k?f:c.height}));d&&d.appendChild(j);return j}function j(a){return(a= x.getSkinElement("playlist",a))?a:{width:0,height:0,src:f}}function q(a){if(G)return a=a?a:d.event,aa(A-(a.detail?-1*a.detail:a.wheelDelta/40)/10),a.stopPropagation&&a.stopPropagation(),a.preventDefault&&a.preventDefault(),a.cancelBubble=!0,a.cancel=!0,a.returnValue=!1}function C(a){0==a.button&&(s=!0);b.onselectstart=function(){return!1};d.addEventListener("mousemove",t,!1);d.addEventListener("mouseup",v,!1)}function w(a){aa(A-2*a.deltaY/p.clientHeight)}function t(b){if(s||"click"==b.type){var c= a.bounds(B),d=F.clientHeight/2;aa((b.pageY-c.top-d)/(c.height-d-d))}}function D(a){return function(b){0<b.button||(aa(A+0.05*a),K=setTimeout(function(){I=setInterval(function(){aa(A+0.05*a)},50)},500))}}function v(){s=!1;d.removeEventListener("mousemove",t);d.removeEventListener("mouseup",v);b.onselectstart=f;clearTimeout(K);clearInterval(I)}var x=g,p=r,k,B,F,s,A=0,K,I;g=a.isMobile();var G=!0,H,P,Q,M,y,R,T,ca,ba;this.element=function(){return k};this.visible=function(){return G};var S=this.redraw= function(){clearTimeout(ba);ba=setTimeout(function(){if(p&&p.clientHeight){var a=p.parentNode.clientHeight/p.clientHeight;0>a&&(a=0);1<a?G=!1:(G=!0,e(n("jwthumb"),{height:Math.max(B.clientHeight*a,y.height+R.height)}));e(n(),{visibility:G?"visible":"hidden"});p&&(p.style.width=G?p.parentElement.clientWidth-Q.width+"px":"")}else ba=setTimeout(S,10)},0)},aa=this.thumbPosition=function(a){isNaN(a)&&(a=0);A=Math.max(0,Math.min(1,a));e(n("jwthumb"),{top:T+(B.clientHeight-F.clientHeight)*A});r&&(r.style.top= Math.min(0,k.clientHeight-r.scrollHeight)*A+"px")};k=z("jwslider",null,m);k.id=h;h=new a.touch(p);g?h.addEventListener(c.DRAG,w):(k.addEventListener("mousedown",C,!1),k.addEventListener("click",t,!1));H=j("sliderCapTop");P=j("sliderCapBottom");Q=j("sliderRail");h=j("sliderRailCapTop");m=j("sliderRailCapBottom");M=j("sliderThumb");y=j("sliderThumbCapTop");R=j("sliderThumbCapBottom");T=H.height;ca=P.height;e(n(),{width:Q.width});e(n("jwrail"),{top:T,bottom:ca});e(n("jwthumb"),{top:T});H=z("jwslidertop", H,k);P=z("jwsliderbottom",P,k);B=z("jwrail",null,k);F=z("jwthumb",null,k);g||(H.addEventListener("mousedown",D(-1),!1),P.addEventListener("mousedown",D(1),!1));z("jwrailtop",h,B);z("jwrailback",Q,B,!0);z("jwrailbottom",m,B);e(n("jwrailback"),{top:h.height,bottom:m.height});z("jwthumbtop",y,F);z("jwthumbback",M,F,!0);z("jwthumbbottom",R,F);e(n("jwthumbback"),{top:y.height,bottom:R.height});S();p&&!g&&(p.addEventListener("mousewheel",q,!1),p.addEventListener("DOMMouseScroll",q,!1));return this};e(h("jwslider"), {position:"absolute",height:"100%",visibility:"hidden",right:0,top:0,cursor:"pointer","z-index":1,overflow:"hidden"});e(h("jwslider")+" *",{position:"absolute",width:"100%","background-position":"center","background-size":"100% 100%",overflow:"hidden"});e(h("jwslidertop","jwrailtop","jwthumbtop"),{top:0});e(h("jwsliderbottom","jwrailbottom","jwthumbbottom"),{bottom:0})})(jwplayer.html5); (function(g){var h=jwplayer.utils,a=h.css,c=document,e="none";g.rightclick=function(a,d){function f(a){var b=c.createElement("div");b.className=a.replace(".","");return b}function u(){r||(n.style.display=e)}var l,m=h.extend({aboutlink:"http://www.longtailvideo.com/jwpabout/?a\x3dr\x26v\x3d"+g.version+"\x26m\x3dh\x26e\x3do",abouttext:"About JW Player "+g.version+"..."},d),r=!1,n,z;this.element=function(){return n};this.destroy=function(){c.removeEventListener("mousedown",u,!1)};l=c.getElementById(a.id); n=f(".jwclick");n.id=a.id+"_menu";n.style.display=e;l.oncontextmenu=function(a){if(!r){null==a&&(a=window.event);var b=null!=a.target?a.target:a.srcElement,c=h.bounds(l),b=h.bounds(b);n.style.display=e;n.style.left=(a.offsetX?a.offsetX:a.layerX)+b.left-c.left+"px";n.style.top=(a.offsetY?a.offsetY:a.layerY)+b.top-c.top+"px";n.style.display="block";a.preventDefault()}};n.onmouseover=function(){r=!0};n.onmouseout=function(){r=!1};c.addEventListener("mousedown",u,!1);z=f(".jwclick_item");z.innerHTML= m.abouttext;z.onclick=function(){window.top.location=m.aboutlink};n.appendChild(z);l.appendChild(n)};a(".jwclick",{"background-color":"#FFF","-webkit-border-radius":5,"-moz-border-radius":5,"border-radius":5,height:"auto",border:"1px solid #bcbcbc","font-family":'"MS Sans Serif", "Geneva", sans-serif',"font-size":10,width:320,"-webkit-box-shadow":"5px 5px 7px rgba(0,0,0,.10), 0px 1px 0px rgba(255,255,255,.3) inset","-moz-box-shadow":"5px 5px 7px rgba(0,0,0,.10), 0px 1px 0px rgba(255,255,255,.3) inset", "box-shadow":"5px 5px 7px rgba(0,0,0,.10), 0px 1px 0px rgba(255,255,255,.3) inset",position:"absolute","z-index":999},!0);a(".jwclick div",{padding:"8px 21px",margin:"0px","background-color":"#FFF",border:"none","font-family":'"MS Sans Serif", "Geneva", sans-serif',"font-size":10,color:"inherit"},!0);a(".jwclick_item",{padding:"8px 21px","text-align":"left",cursor:"pointer"},!0);a(".jwclick_item:hover",{"background-color":"#595959",color:"#FFF"},!0);a(".jwclick_item a",{"text-decoration":e,color:"#000"}, !0);a(".jwclick hr",{width:"100%",padding:0,margin:0,border:"1px #e9e9e9 solid"},!0)})(jwplayer.html5); (function(g){var h=jwplayer,a=h.utils,c=h.events,e=h.playlist,b=2,d=4;g.setup=function(f,h){function l(a,b,c){v.push({name:a,method:b,depends:c})}function m(){for(var a=0;a<v.length;a++){var b=v[a],c;a:{if(c=b.depends){c=c.toString().split(",");for(var d=0;d<c.length;d++)if(!C[c[d]]){c=!1;break a}}c=!0}if(c){v.splice(a,1);try{b.method(),m()}catch(e){j(e.message)}return}}0<v.length&&!D&&setTimeout(m,500)}function r(){C[b]=!0}function n(a){j("Error loading skin: "+a)}function z(){C[d]=!0}function j(a){D= !0;t.sendEvent(c.JWPLAYER_ERROR,{message:a});q.setupError(a)}var q=h,C={},w,t=new c.eventdispatcher,D=!1,v=[];a.extend(this,t);this.start=m;l(1,function(){f.edition&&"invalid"==f.edition()?j("Error setting up player: Invalid license key"):C[1]=!0});l(b,function(){w=new g.skin;w.load(f.config.skin,r,n)},1);l(3,function(){switch(a.typeOf(f.config.playlist)){case "string":j("Can't load a playlist as a string anymore");case "array":var b=new e(f.config.playlist);f.setPlaylist(b);0==f.playlist[0].sources.length? j("Error loading playlist: No playable sources found"):C[3]=!0}},1);l(d,function(){var a=f.playlist[f.item].image;if(a){var b=new Image;b.addEventListener("load",z,!1);b.addEventListener("error",z,!1);b.src=a;setTimeout(z,500)}else C[d]=!0},3);l(5,function(){q.setup(w);C[5]=!0},d+","+b);l(6,function(){C[6]=!0},"5,3");l(7,function(){t.sendEvent(c.JWPLAYER_READY);C[7]=!0},6)}})(jwplayer.html5); (function(g){g.skin=function(){var h={},a=!1;this.load=function(c,e,b){new g.skinloader(c,function(b){a=!0;h=b;"function"==typeof e&&e()},function(a){"function"==typeof b&&b(a)})};this.getSkinElement=function(c,e){c=c.toLowerCase();e=e.toLowerCase();if(a)try{return h[c].elements[e]}catch(b){jwplayer.utils.log("No such skin component / element: ",[c,e])}return null};this.getComponentSettings=function(c){c=c.toLowerCase();return a&&h&&h[c]?h[c].settings:null};this.getComponentLayout=function(c){c=c.toLowerCase(); if(a){var e=h[c].layout;if(e&&(e.left||e.right||e.center))return h[c].layout}return null}}})(jwplayer.html5); (function(g){var h=jwplayer.utils,a=h.foreach,c="Skin formatting error";g.skinloader=function(e,b,d){function f(a){z=a;h.ajax(h.getAbsolutePath(t),function(a){try{h.exists(a.responseXML)&&l(a.responseXML)}catch(b){q(c)}},function(a){q(a)})}function u(a,b){return a?a.getElementsByTagName(b):null}function l(a){var b=u(a,"skin")[0];a=u(b,"component");var c=b.getAttribute("target"),b=parseFloat(b.getAttribute("pixelratio"));0<b&&(x=b);(!c||parseFloat(c)>parseFloat(jwplayer.version))&&q("Incompatible player version"); if(0===a.length)j(z);else for(c=0;c<a.length;c++){var d=n(a[c].getAttribute("name")),b={settings:{},elements:{},layout:{}},e=u(u(a[c],"elements")[0],"element");z[d]=b;for(var f=0;f<e.length;f++)r(e[f],d);if((d=u(a[c],"settings")[0])&&0<d.childNodes.length){d=u(d,"setting");for(e=0;e<d.length;e++){var f=d[e].getAttribute("name"),g=d[e].getAttribute("value");/color$/.test(f)&&(g=h.stringToColor(g));b.settings[n(f)]=g}}if((d=u(a[c],"layout")[0])&&0<d.childNodes.length){d=u(d,"group");for(e=0;e<d.length;e++){g= d[e];f={elements:[]};b.layout[n(g.getAttribute("position"))]=f;for(var l=0;l<g.attributes.length;l++){var t=g.attributes[l];f[t.name]=t.value}g=u(g,"*");for(l=0;l<g.length;l++){t=g[l];f.elements.push({type:t.tagName});for(var v=0;v<t.attributes.length;v++){var w=t.attributes[v];f.elements[l][n(w.name)]=w.value}h.exists(f.elements[l].name)||(f.elements[l].name=t.tagName)}}}C=!1;m()}}function m(){clearInterval(w);D||(w=setInterval(function(){var b=!0;a(z,function(c,d){"properties"!=c&&a(d.elements, function(a){(z[n(c)]?z[n(c)].elements[n(a)]:null).ready||(b=!1)})});b&&!1==C&&(clearInterval(w),j(z))},100))}function r(a,b){b=n(b);var c=new Image,d=n(a.getAttribute("name")),e=a.getAttribute("src");if(0!==e.indexOf("data:image/png;base64,"))var f=h.getAbsolutePath(t),e=[f.substr(0,f.lastIndexOf("/")),b,e].join("/");z[b].elements[d]={height:0,width:0,src:"",ready:!1,image:c};c.onload=function(){var a=b,e=z[n(a)]?z[n(a)].elements[n(d)]:null;e?(e.height=Math.round(c.height/x*v),e.width=Math.round(c.width/ x*v),e.src=c.src,e.ready=!0,m()):h.log("Loaded an image for a missing element: "+a+"."+d)};c.onerror=function(){D=!0;m();q("Skin image not found: "+this.src)};c.src=e}function n(a){return a?a.toLowerCase():""}var z={},j=b,q=d,C=!0,w,t=e,D=!1,v=(jwplayer.utils.isMobile(),1),x=1;"string"!=typeof t||""===t?l(g.defaultskin().xml):"xml"!=h.extension(t)?q("Skin not a valid file type"):new g.skinloader("",f,q)}})(jwplayer.html5); (function(g){var h=g.utils,a=g.events,c=h.css;g.html5.thumbs=function(e){function b(a){r=null;try{a=(new g.parsers.srt).parse(a.responseText,!0)}catch(b){d(b.message);return}if("array"!==h.typeOf(a))return d("Invalid data");l=a}function d(a){r=null;h.log("Thumbnails could not be loaded: "+a)}function f(a,b,d){a.onload=null;b.width||(b.width=a.width,b.height=a.height);b["background-image"]=a.src;c.style(u,b);d&&d(b.width)}var u,l,m,r,n,z={},j,q=new a.eventdispatcher;h.extend(this,q);u=document.createElement("div"); u.id=e;this.load=function(a){c.style(u,{display:"none"});r&&(r.onload=null,r.onreadystatechange=null,r.onerror=null,r.abort&&r.abort(),r=null);j&&(j.onload=null);a?(m=a.split("?")[0].split("/").slice(0,-1).join("/"),r=h.ajax(a,b,d,!0)):(l=n=j=null,z={})};this.element=function(){return u};this.updateTimeline=function(a,b){if(l){for(var c=0;c<l.length&&a>l[c].end;)c++;c===l.length&&c--;c=l[c].text;a:{var e=c;if(e&&e!==n){n=e;0>e.indexOf("://")&&(e=m?m+"/"+e:e);var h={display:"block",margin:"0 auto", "background-position":"0 0",width:0,height:0};if(0<e.indexOf("#xywh"))try{var g=/(.+)\#xywh=(\d+),(\d+),(\d+),(\d+)/.exec(e),e=g[1];h["background-position"]=-1*g[2]+"px "+-1*g[3]+"px";h.width=g[4];h.height=g[5]}catch(p){d("Could not parse thumbnail");break a}var k=z[e];k?f(k,h,b):(k=new Image,k.onload=function(){f(k,h,b)},z[e]=k,k.src=e);j&&(j.onload=null);j=k}}return c}}}})(jwplayer); (function(g){var h=g.utils,a=g.events,c=a.state,e=!0,b=!1;g.html5.video=function(d){function f(a,b){y&&M.sendEvent(a,b)}function g(){}function l(b){r(b);y&&(G==c.PLAYING&&!I)&&(F=Number(k.currentTime.toFixed(1)),f(a.JWPLAYER_MEDIA_TIME,{position:F,duration:B}))}function m(c){y&&(s||(s=e,n()),"loadedmetadata"==c.type&&(k.muted&&(k.muted=b,k.muted=e),f(a.JWPLAYER_MEDIA_META,{duration:k.duration,height:k.videoHeight,width:k.videoWidth})))}function r(){s&&(0<K&&!ca)&&(D?setTimeout(function(){0<K&&da(K)}, 200):da(K))}function n(){A||(A=e,f(a.JWPLAYER_MEDIA_BUFFER_FULL))}function z(a){y&&!I&&(k.paused?k.currentTime==k.duration&&3<k.duration||qa():(!h.isFF()||!("play"==a.type&&G==c.BUFFERING))&&w(c.PLAYING))}function j(){y&&(I||w(c.BUFFERING))}function q(a){var b;if("array"==h.typeOf(a)&&0<a.length){b=[];for(var c=0;c<a.length;c++){var d=a[c],e={};e.label=d.label&&d.label?d.label?d.label:0:c;b[c]=e}}return b}function C(){A=s=b;p=R[T];w(c.BUFFERING);k.src=p.file;k.load();P=setInterval(t,100);h.isMobile()&& n()}function w(b){if(!(b==c.PAUSED&&G==c.IDLE)&&!I&&G!=b){var d=G;G=b;f(a.JWPLAYER_PLAYER_STATE,{oldstate:d,newstate:b})}}function t(){if(y){var b;b=0==k.buffered.length||0==k.duration?0:k.buffered.end(k.buffered.length-1)/k.duration;b!=Q&&(Q=b,f(a.JWPLAYER_MEDIA_BUFFER,{bufferPercent:Math.round(100*Q)}));1<=b&&clearInterval(P)}}var D=h.isIE(),v={abort:g,canplay:m,canplaythrough:g,durationchange:function(){if(y){var a=Number(k.duration.toFixed(1));B!=a&&(B=a);ca&&(0<K&&a>K)&&da(K);l()}},emptied:g, ended:function(){y&&G!=c.IDLE&&(T=-1,Y=e,f(a.JWPLAYER_MEDIA_BEFORECOMPLETE),y&&(w(c.IDLE),Y=b,f(a.JWPLAYER_MEDIA_COMPLETE)))},error:function(){y&&(h.log("Error playing media: %o",k.error),M.sendEvent(a.JWPLAYER_MEDIA_ERROR,{message:"Error loading media: File could not be played"}),w(c.IDLE))},loadeddata:g,loadedmetadata:m,loadstart:g,pause:z,play:z,playing:z,progress:r,ratechange:g,readystatechange:g,seeked:function(){!I&&G!=c.PAUSED&&w(c.PLAYING)},seeking:D?j:g,stalled:g,suspend:g,timeupdate:l,volumechange:function(){f(a.JWPLAYER_MEDIA_VOLUME, {volume:Math.round(100*k.volume)});f(a.JWPLAYER_MEDIA_MUTE,{mute:k.muted})},waiting:j},x,p,k,B,F,s,A,K,I=b,G=c.IDLE,H,P=-1,Q=-1,M=new a.eventdispatcher,y=b,R,T=-1,ca=h.isAndroid(b,e),ba=h.isIOS(7),S=this,aa=[],Y=b;h.extend(S,M);S.load=function(b){if(y){x=b;K=0;B=b.duration?b.duration:-1;F=0;R=x.sources;0>T&&(T=0);for(b=0;b<R.length;b++)if(R[b]["default"]){T=b;break}var c=h.getCookies().qualityLabel;if(c)for(b=0;b<R.length;b++)if(R[b].label==c){T=b;break}(b=q(R))&&M.sendEvent(a.JWPLAYER_MEDIA_LEVELS, {levels:b,currentQuality:T});C()}};S.stop=function(){y&&(k.removeAttribute("src"),D||k.load(),T=-1,clearInterval(P),w(c.IDLE))};S.play=function(){y&&!I&&k.play()};var qa=S.pause=function(){y&&(k.pause(),w(c.PAUSED))};S.seekDrag=function(a){y&&((I=a)?k.pause():k.play())};var da=S.seek=function(b){y&&(!I&&0==K&&f(a.JWPLAYER_MEDIA_SEEK,{position:F,offset:b}),s?(K=0,k.currentTime=b):K=b)},Ra=S.volume=function(a){h.exists(a)&&(k.volume=Math.min(Math.max(0,a/100),1),H=100*k.volume)};S.mute=function(a){h.exists(a)|| (a=!k.muted);a?(H=100*k.volume,k.muted=e):(Ra(H),k.muted=b)};this.addCaptions=function(a,b,c){h.isIOS()&&k.addTextTrack&&(0<c&&(c=a[c-1].label),h.foreach(a,function(a,b){if(b.data){var c=k.addTextTrack(b.kind,b.label);h.foreach(b.data,function(a,d){1==a%2&&c.addCue(new TextTrackCue(d.begin,b.data[parseInt(a)+1].begin,d.text))});aa.push(c);c.mode="hidden"}}))};this.resetCaptions=function(){};this.fsCaptions=function(a){if(h.isIOS()&&k.addTextTrack){var b=null;h.foreach(aa,function(c,d){!a&&"showing"== d.mode&&(b=parseInt(c));a||(d.mode="hidden")});if(!a)return b}};this.checkComplete=function(){return Y};S.detachMedia=function(){y=b;return k};S.attachMedia=function(d){y=e;d||(s=b);Y&&(w(c.IDLE),f(a.JWPLAYER_MEDIA_COMPLETE),Y=b)};S.getTag=function(){return k};S.audioMode=function(){if(!R)return b;var a=R[0].type;return"aac"==a||"mp3"==a||"vorbis"==a};S.setCurrentQuality=function(b){T!=b&&(b=parseInt(b,10),0<=b&&(R&&R.length>b)&&(T=b,h.saveCookie("qualityLabel",R[b].label),f(a.JWPLAYER_MEDIA_LEVEL_CHANGED, {currentQuality:b,levels:q(R)}),b=k.currentTime,C(),S.seek(b)))};S.getCurrentQuality=function(){return T};S.getQualityLevels=function(){return q(R)};d||(d=document.createElement("video"));k=d;h.foreach(v,function(a,c){k.addEventListener(a,c,b)});ba||(k.controls=e,k.controls=b);k.setAttribute("x-webkit-airplay","allow");y=e}})(jwplayer); (function(g){var h=g.html5,a=g.utils,c=g.events,e=c.state,b=a.css,d=a.bounds,f=a.isMobile(),u=a.isIPad(),l=a.isIPod(),m=a.isAndroid(),r=a.isIOS(),n=document,z="aspectMode",j=!0,q=!1,C="hidden",w="none",t="block";h.view=function(D,v){function x(){var a=d(O),b=Math.round(a.width),e=Math.round(a.height);if(n.body.contains(O)){if(b&&e&&(b!==eb||e!==Va))eb=b,Va=e,X&&X.redraw(),clearTimeout(xa),xa=setTimeout(P,50),va.sendEvent(c.JWPLAYER_RESIZE,{width:b,height:e})}else window.removeEventListener("resize", x),f&&window.removeEventListener("orientationchange",x);return a}function p(a){a&&(a.element().addEventListener("mousemove",A,q),a.element().addEventListener("mouseout",K,q))}function k(){}function B(a,b){var c=n.createElement(a);b&&(c.className=b);return c}function F(){clearTimeout(Aa);Aa=setTimeout(Y,nb)}function s(){clearTimeout(Aa);if(U.jwGetState()==e.PAUSED||U.jwGetState()==e.PLAYING)qa(),W||(Aa=setTimeout(Y,nb))}function A(){clearTimeout(Aa);W=j}function K(){W=q}function I(a){va.sendEvent(a.type, a)}function G(c,d,e){var f=O.className,g,h,k=U.id+"_view";b.block(k);if(e=!!e)f=f.replace(/\s*aspectMode/,""),O.className!==f&&(O.className=f),b.style(O,{display:t},e);a.exists(c)&&a.exists(d)&&(L.width=c,L.height=d);e={width:c};-1==f.indexOf(z)&&(e.height=d);b.style(O,e,!0);X&&X.redraw();V&&V.redraw(j);ea&&(ea.offset(V&&0<=ea.position().indexOf("bottom")?V.height()+V.margin():0),setTimeout(function(){N&&N.offset("top-left"==ea.position()?ea.element().clientWidth+ea.margin():0)},500));H(d);g=L.playlistsize; h=L.playlistposition;if(oa&&g&&("right"==h||"bottom"==h))oa.redraw(),f={display:t},e={},f[h]=0,e[h]=g,"right"==h?f.width=g:f.height=g,b.style(Oa,f),b.style(za,e);P(c,d);b.unblock(k)}function H(a){var b=d(O);ka=0<a.toString().indexOf("%")||0===b.height?q:"bottom"==L.playlistposition?b.height<=40+L.playlistsize:40>=b.height;V&&(ka?(V.audioMode(j),qa(),X.hidePreview(j),X&&X.hide(),da(q)):(V.audioMode(q),Sa(U.jwGetState())));ea&&ka&&S();O.style.backgroundColor=ka?"transparent":"#000"}function P(b,c){if(ja){if(!b|| isNaN(Number(b)))b=ra.clientWidth;if(!c||isNaN(Number(c)))c=ra.clientHeight;a.stretch(L.stretching,ja,b,c,ja.videoWidth,ja.videoHeight)&&(clearTimeout(xa),xa=setTimeout(P,250))}}function Q(a){if(L.fullscreen)switch(a.keyCode){case 27:fa(q)}}function M(a){r||(a?(O.className+=" jwfullscreen",n.getElementsByTagName("body")[0].style["overflow-y"]=C):(O.className=O.className.replace(/\s+jwfullscreen/,""),n.getElementsByTagName("body")[0].style["overflow-y"]=""))}function y(){var a;a=n.mozFullScreenElement|| n.webkitCurrentFullScreenElement||n.msFullscreenElement||ja.webkitDisplayingFullscreen;a=!(!a||a.id&&a.id!=U.id);L.fullscreen!=a&&fa(a)}function R(){V&&(!ka&&!L.getVideo().audioMode())&&V.hide()}function T(){N&&(!ka&&L.controls)&&N.show()}function ca(){N&&(!Ga&&!L.getVideo().audioMode())&&N.hide()}function ba(){ea&&!ka&&ea.show()}function S(){ea&&!L.getVideo().audioMode()&&ea.hide(ka)}function aa(){X&&L.controls&&!ka&&(!l||U.jwGetState()==e.IDLE)&&X.show();if(!f||!L.fullscreen)ja.controls=q}function Y(){clearTimeout(Aa); la=q;var a=U.jwGetState();(!v.controls||a!=e.PAUSED)&&R();v.controls||ca();a!=e.IDLE&&a!=e.PAUSED&&(ca(),S())}function qa(){la=j;if((L.controls||ka)&&!(l&&$==e.PAUSED))(!l||ka)&&V&&V.show(),T();fb.hide&&ba()}function da(a){(a=a&&!ka)||m?b.style(ra,{visibility:"visible",opacity:1}):b.style(ra,{visibility:C,opacity:0})}function Ra(){Ga=j;fa(q);L.controls&&T()}function ha(){}function kb(){}function Ia(a){Ga=q;clearTimeout(ga);ga=setTimeout(function(){Sa(a.newstate)},100)}function Ya(){R()}function Sa(a){$= a;switch(a){case e.PLAYING:(Ba?Ja:L).getVideo().audioMode()?(da(q),X.hidePreview(ka),X.setHiding(j),V&&(qa(),V.hideFullscreen(j)),T(),ba()):(da(j),P(),X.hidePreview(j),V&&V.hideFullscreen(q),Y());break;case e.IDLE:da(q);ka||(X.hidePreview(q),aa(),T(),ba(),V&&V.hideFullscreen(q));break;case e.BUFFERING:aa();Y();f&&da(j);break;case e.PAUSED:aa(),qa()}}function Ta(a){return"#"+U.id+(a?" ."+a:"")}function Na(a,c){b(a,{display:c?t:w})}var U=D,L=v,O,za,ua,Za,Oa,Aa=-1,nb=f?4E3:2E3,ja,ra,eb,Va,sa,Pa,Ca,Ja, Ba=q,V,X,N,ea,fb=a.extend({},L.componentConfig("logo")),J,oa,ka,Xa=q,la=q,Ga,E,xa=-1,W=q,$,va=new c.eventdispatcher;a.extend(this,va);this.getCurrentCaptions=function(){return J.getCurrentCaptions()};this.setCurrentCaptions=function(a){J.setCurrentCaptions(a)};this.getCaptionsList=function(){return J.getCaptionsList()};this.setup=function(d){if(!Xa){U.skin=d;za=B("span","jwmain");za.id=U.id+"_view";ra=B("span","jwvideo");ja=L.getVideo().getTag();ra.appendChild(ja);ua=B("span","jwcontrols");sa=B("span", "jwinstream");Oa=B("span","jwplaylistcontainer");Za=B("span","jwaspect");d=L.height;var g=L.componentConfig("controlbar"),m=L.componentConfig("display");H(d);J=new h.captions(U,L.captions);J.addEventListener(c.JWPLAYER_CAPTIONS_LIST,I);J.addEventListener(c.JWPLAYER_CAPTIONS_CHANGED,I);J.addEventListener(c.JWPLAYER_CAPTIONS_LOADED,k);ua.appendChild(J.element());X=new h.display(U,m);X.addEventListener(c.JWPLAYER_DISPLAY_CLICK,function(a){I(a);f?la?Y():qa():Ia(U.jwGetState());la&&F()});ka&&X.hidePreview(j); ua.appendChild(X.element());ea=new h.logo(U,fb);ua.appendChild(ea.element());N=new h.dock(U,L.componentConfig("dock"));ua.appendChild(N.element());U.edition&&!f?E=new h.rightclick(U,{abouttext:L.abouttext,aboutlink:L.aboutlink}):f||(E=new h.rightclick(U,{}));L.playlistsize&&(L.playlistposition&&L.playlistposition!=w)&&(oa=new h.playlistcomponent(U,{}),Oa.appendChild(oa.element()));V=new h.controlbar(U,g);V.addEventListener(c.JWPLAYER_USER_ACTION,F);ua.appendChild(V.element());l&&R();za.appendChild(ra); za.appendChild(ua);za.appendChild(sa);O.appendChild(za);O.appendChild(Za);O.appendChild(Oa);n.addEventListener("webkitfullscreenchange",y,q);ja.addEventListener("webkitbeginfullscreen",y,q);ja.addEventListener("webkitendfullscreen",y,q);n.addEventListener("mozfullscreenchange",y,q);n.addEventListener("MSFullscreenChange",y,q);n.addEventListener("keydown",Q,q);window.removeEventListener("resize",x);window.addEventListener("resize",x,!1);f&&(window.removeEventListener("orientationchange",x),window.addEventListener("orientationchange", x,!1));U.jwAddEventListener(c.JWPLAYER_PLAYER_READY,kb);U.jwAddEventListener(c.JWPLAYER_PLAYER_STATE,Ia);U.jwAddEventListener(c.JWPLAYER_MEDIA_ERROR,Ya);U.jwAddEventListener(c.JWPLAYER_PLAYLIST_COMPLETE,Ra);U.jwAddEventListener(c.JWPLAYER_PLAYLIST_ITEM,ha);Ia({newstate:e.IDLE});f||(ua.addEventListener("mouseout",function(){clearTimeout(Aa);Aa=setTimeout(Y,10)},q),ua.addEventListener("mousemove",s,q),a.isIE()&&(ra.addEventListener("mousemove",s,q),ra.addEventListener("click",X.clickHandler)));p(V); p(N);p(ea);b("#"+O.id+"."+z+" .jwaspect",{"margin-top":L.aspectratio,display:t});d=a.exists(L.aspectratio)?parseFloat(L.aspectratio):100;g=L.playlistsize;b("#"+O.id+".playlist-right .jwaspect",{"margin-bottom":-1*g*(d/100)+"px"});b("#"+O.id+".playlist-right .jwplaylistcontainer",{width:g+"px",right:0,top:0,height:"100%"});b("#"+O.id+".playlist-bottom .jwaspect",{"padding-bottom":g+"px"});b("#"+O.id+".playlist-bottom .jwplaylistcontainer",{width:"100%",height:g+"px",bottom:0});b("#"+O.id+".playlist-right .jwmain", {right:g+"px"});b("#"+O.id+".playlist-bottom .jwmain",{bottom:g+"px"});setTimeout(function(){G(L.width,L.height)},0)}};var fa=this.fullscreen=function(b){a.exists(b)||(b=!L.fullscreen);if(b){if((Ba?Ja:L).getVideo().audioMode())return;if(f)try{ja.webkitEnterFullScreen(),L.setFullscreen(j)}catch(c){return}else L.fullscreen||(M(j),O.requestFullScreen?O.requestFullScreen():O.mozRequestFullScreen?O.mozRequestFullScreen():O.webkitRequestFullScreen?O.webkitRequestFullScreen():O.msRequestFullscreen&&O.msRequestFullscreen(), L.setFullscreen(j))}else f?(ja.webkitExitFullScreen(),L.setFullscreen(q),u&&(ja.controls=q)):L.fullscreen&&(M(q),L.setFullscreen(q),n.cancelFullScreen?n.cancelFullScreen():n.mozCancelFullScreen?n.mozCancelFullScreen():n.webkitCancelFullScreen?n.webkitCancelFullScreen():n.msExitFullscreen&&n.msExitFullscreen()),u&&U.jwGetState()==e.PAUSED&&setTimeout(aa,500);V&&V.redraw();X&&X.redraw();N&&N.redraw();P();L.fullscreen&&(clearTimeout(xa),xa=setTimeout(P,200))};this.resize=function(a,b){G(a,b,!0);x()}; this.resizeMedia=P;var Qa=this.completeSetup=function(){b.style(O,{opacity:1})},ga;this.setupInstream=function(a,c,d,f){b.unblock();Na(Ta("jwinstream"),j);Na(Ta("jwcontrols"),q);sa.appendChild(a);Pa=c;Ca=d;Ja=f;Ia({newstate:e.PLAYING});Ba=j};this.destroyInstream=function(){b.unblock();Na(Ta("jwinstream"),q);Na(Ta("jwcontrols"),j);sa.innerHTML="";Ba=q};this.setupError=function(a){Xa=j;g.embed.errorScreen(O,a,L);Qa()};this.addButton=function(a,b,c,d){N&&(N.addButton(a,b,c,d),U.jwGetState()==e.IDLE&& T())};this.removeButton=function(a){N&&N.removeButton(a)};this.setControls=function(a){var b=L.controls,d=a?j:q;L.controls=d;d!=b&&(Ba?a?(Pa.show(),Ca.show()):(Pa.hide(),Ca.hide()):d?Ia({newstate:U.jwGetState()}):(Y(),X&&X.hide()),va.sendEvent(c.JWPLAYER_CONTROLS,{controls:d}))};this.addCues=function(a){V&&V.addCues(a)};this.forceState=function(a){X.forceState(a)};this.releaseState=function(){X.releaseState(U.jwGetState())};this.getSafeRegion=function(){var a={x:0,y:0,width:0,height:0};if(!L.controls)return a; V.showTemp();N.showTemp();var b=d(za),c=b.top,e=Ba?d(n.getElementById(U.id+"_instream_controlbar")):d(V.element()),f=Ba?!1:0<N.numButtons(),g=0===ea.position().indexOf("top"),h=d(ea.element());f&&(f=d(N.element()),a.y=Math.max(0,f.bottom-c));g&&(a.y=Math.max(a.y,h.bottom-c));a.width=b.width;a.height=e.height?(g?e.top:h.top)-c-a.y:b.height-a.y;V.hideTemp();N.hideTemp();return a};this.destroy=function(){n.removeEventListener("webkitfullscreenchange",y,q);n.removeEventListener("mozfullscreenchange", y,q);n.removeEventListener("MSFullscreenChange",y,q);ja.removeEventListener("webkitbeginfullscreen",y,q);ja.removeEventListener("webkitendfullscreen",y,q);n.removeEventListener("keydown",Q,q);E&&E.destroy()};O=B("div","jwplayer playlist-"+L.playlistposition);O.id=U.id;L.aspectratio&&(b.style(O,{display:"inline-block"}),O.className=O.className.replace("jwplayer","jwplayer "+z));G(L.width,L.height);var La=n.getElementById(U.id);La.parentNode.replaceChild(O,La)};b(".jwplayer",{position:"relative",display:"block", opacity:0,"min-height":0,"-webkit-transition":"opacity .25s ease","-moz-transition":"opacity .25s ease","-o-transition":"opacity .25s ease"});b(".jwmain",{position:"absolute",left:0,right:0,top:0,bottom:0,"-webkit-transition":"opacity .25s ease","-moz-transition":"opacity .25s ease","-o-transition":"opacity .25s ease"});b(".jwvideo, .jwcontrols",{position:"absolute",height:"100%",width:"100%","-webkit-transition":"opacity .25s ease","-moz-transition":"opacity .25s ease","-o-transition":"opacity .25s ease"}); b(".jwvideo",{overflow:C,visibility:C,opacity:0,cursor:"pointer"});b(".jwvideo video",{background:"transparent",height:"100%",width:"100%",position:"absolute",margin:"auto",right:0,left:0,top:0,bottom:0});b(".jwplaylistcontainer",{position:"absolute",height:"100%",width:"100%",display:w});b(".jwinstream",{position:"absolute",top:0,left:0,bottom:0,right:0,display:"none"});b(".jwaspect",{display:"none"});b(".jwplayer."+z,{height:"auto"});b(".jwplayer.jwfullscreen",{width:"100%",height:"100%",left:0, right:0,top:0,bottom:0,"z-index":1E3,position:"fixed"},j);b(".jwplayer.jwfullscreen .jwmain",{left:0,right:0,top:0,bottom:0},j);b(".jwplayer.jwfullscreen .jwplaylistcontainer",{display:w},j);b(".jwplayer .jwuniform",{"background-size":"contain !important"});b(".jwplayer .jwfill",{"background-size":"cover !important","background-position":"center"});b(".jwplayer .jwexactfit",{"background-size":"100% 100% !important"})})(jwplayer); (function(g){var h=jwplayer.utils.extend,a=g.logo;a.defaults.prefix="";a.defaults.file="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHoAAAAyCAMAAACkjD/XAAACnVBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJCQkSEhIAAAAaGhoAAAAiIiIrKysAAAAxMTEAAAA4ODg+Pj4AAABEREQAAABJSUkAAABOTk5TU1NXV1dcXFxiYmJmZmZqamptbW1xcXF0dHR3d3d9fX2AgICHh4eKioqMjIyOjo6QkJCSkpKUlJSWlpaYmJidnZ2enp6ioqKjo6OlpaWmpqanp6epqamqqqqurq6vr6+wsLCxsbG0tLS1tbW2tra3t7e6urq7u7u8vLy9vb2+vr6/v7/AwMDCwsLFxcXFxcXHx8fIyMjJycnKysrNzc3Ozs7Ozs7Pz8/Pz8/Q0NDR0dHR0dHS0tLU1NTV1dXW1tbW1tbW1tbX19fX19fa2trb29vb29vc3Nzc3Nzf39/f39/f39/f39/g4ODh4eHj4+Pj4+Pk5OTk5OTk5OTk5OTl5eXn5+fn5+fn5+fn5+fn5+fo6Ojo6Ojq6urq6urq6urr6+vr6+vr6+vt7e3t7e3t7e3t7e3u7u7u7u7v7+/v7+/w8PDw8PDw8PDw8PDy8vLy8vLy8vLy8vLy8vLy8vLy8vLy8vL09PT09PT09PT09PT09PT09PT09PT29vb29vb29vb29vb29vb29vb29vb29vb39/f39/f39/f39/f39/f4+Pj4+Pj4+Pj5+fn5+fn5+fn5+fn5+fn5+fn5+fn6+vr6+vr6+vr6+vr6+vr6+vr8/Pz8/Pz8/Pz8/Pz8/Pz8/Pz9/f39/f39/f39/f39/f39/f39/f39/f39/f3+/v7+/v7+/v7+/v7+/v7+/v7+/v7+/v7///////////////9kpi5JAAAA33RSTlMAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhYWFxcYGBgZGRoaGhsbHBwdHR4eHx8gISIiIyQmJicoKSoqKywtLi4uMDEyMjM0NTU2Njc5Ojo7Ozw9Pj5AQUJCQ0ZGSElKSktMTU5PUFFRUlRVVlZXWFpbXV5eX2BhYmVmZ2hpamtsbW5vcHFyc3R2d3h5enx9fn+BgoKDhIWGiYmKi4yNjo+QkZKTlJWWl5eYmZqbnJ2enp+goaKkpaamp6ipqqusra6vsLKzs7W2t7i5uru8vb6/wMHCwsPExcbHyMnJysvMVK8y+QAAB5FJREFUeNrFmP2f3EQdx8kmm2yy2WQzmZkjl3bJ2Rb12mtp8SiKiBUUxVKFVisIihV62CKCIoK0UvVK1bP07mitBeVJUVso0Duw1Xo9ET0f6JN47bV3u9+/xe83kyzr0+vlL7t8Xq9ubpLpvHfm+7i54P+UVkBp2gWdFpGNYtFA+NtALpYcxzZ1rSM0TSvgv5xse0wwu1joxDYLulE0dKTTSLcqfOvMQ1WzoHXAtCadsGXqBCsUnWDxNBzmlq51wLSuz0LmOcTWClZFfA1ghLUbrUwbdq396kAvK5s6HoFdlb8FuLONB66RlGnD5S8BwKkNoVMsFEw3XIOj97hmoX2updP5kml7jgLp/Ec8yzBKntwDMCnwa7TPtUrkWLrliW2gtC+0TdNhvdMAu1hJ19plYNcP0LGKiJp/HJTeEI5V8sjJ4PZ2mTp1rb7Pf5C5JbvCN0Cuha7jpE5WX9oeU6us8YlTUH8grFQC+QzkWuKVvdTJXuWO0Z5Nk2tNkWNdzgLed+4tdNWrkpPBI20ytVYwK+LrQLpPcHk3vIVm1ZCcDD7jt8fUGmYNoeLpJzKW+1vQYSjJyc72ZKbWSOqqhpn+99r/rn99WDDLbJViHZbJirkWtJDkZPArbhta2jFg7LdKV1ID9aWaz5CTzTD0pvB2aypB9xYPKtaUXEC7bKKjeA1dHyJTU+xbFgY/RiAKP2lYsm28RaJmAtfTs6c4xP9g0gycUqKpeDGLegZPl3MqTL6oWCdl9EIrOol20/U6zyzgVJzpeV6l7Dhl18VP1/N8v1r1vQoNSziH1nPKKMdBChbAiprheygfL65tZmxazguYXDoL8BcyqlhRb0W/M3Wy412YRTUd7SKEFIKzIBQ8DBhHewgSjkLB7GwS54wxwcoORqYQ+QyhFGA9VIYxnfCKq2VtE3k3wTB1taLx+FVCNTRyxnU4YQ/8WEY9M7PvkvJHsEsAam5srRRwH0YBhml14Zv7pRz62+LAD/jWE0vHINU6OUGXyc0Mt5GiLW/+6blV8eO4tY8B6t3qvBsZOnUy+HJgFaiuMELfhQ6RrAe4JZGvwxcFPLx69YZDZ1ciOrB03ayEd52vr0x6/zokhbxs+p5o7Oc3kfrkxFOrV392d+NWFaeaXvK652Cw+xTAo9cS5ar0vKcfy9BrgNRfMVN0SOh+gPfWtgN8L7kM6pcI2FSrJUtm7kc0KxlF2xcHd/1xWxxvmv1QLB9/5cJobDiKIxklcmI4ShJ5eJ/qOTSqU6/BBC4JN6boQSAN71Doi1Mnm+B0Rjlavgabo/GZ2V/LL8FRSehkkfzzYIouoqXf31jz3de7kq5DB6JP1a+vSUQnOXrRoujpn2XogumJpwCeBfhDV4qeAdK1QwqdOhkMqdAyyyk6HoHR3tmD4/UlI/DDBNFxHK1tDBDaNrHODU7KDzTW16Lr6nccHZGxHNt3Jao/RrSU8pPTeX+JPYj4NpAGkxsg16FoWP1xP5Bu8UwdYxSXJXRyJ0zeCtsegdsm4QsLBBwcHf3l+fF5hHbscnDh1LeSaGwvModnTl7ChVRuNiblxIkjR6bq+9+R9RzkO7cBadWCdZBroDaq/jgDqHMLMYtSr8jkpwl9aaOxF9bdDHsb9T5Ev/rkk6N398SIDj3X5zfDzi1bDpxdHNWWwcOchS27funeR+EOyTI0RcyKLIM20VPzyOObeh4LJsZ/hYnaRpgRsTwG9TPzLz5XhyOSDlzykDEKLsEYl08cG0W9eW+U4B1eZZmtY7J13PXCeHeg0MrPjlH8yLiJ/mYtfqIFvQVNTaez/cMrfwHHpJC7APZH0csAP5ARokPPwXyIoEjKaOnM7UIIOfKKrJEJvEAguhZHUY1sHb3vH1tCxyS0OvGtAL+/iMubQOlMXyKfA6U8i+I0PqWyecA3AmyVEmPhczxEdBUbOKwCsHsAtfNUDyZNdiNcLQld8cTYgQHScjExjNPvOf9RSsrZtt3uB3f2s0Dku35MyiY6z6LYjbMdx+HvO7pd11/egBtCvh7mFvs+P70Rl8L0yU8r7WROyXb5b77Dxemv+I7L82wmxoeY53U9+/K8HE1ZvBq4eGQfh1SNa0Keo5tZVCXwXs7KluUwIZjrMsrHTsB95f4B50JwztGURtHywsBjvGphtIUiFeb9Kn4pjzHXUOhmlXPI3Ug/5QH6BjS1uWpRRdLNku3YWPNw4RKVSSqfpKLq3k3bIZXMvFha+NjQqXqlhYxKa9EgFJGVqKCrqD2ZloJrql7Qgq4vw9DKfn0ahp73B+ln3hPQY/xKJEO1CC2P6T49UOP/fD+R5qphSBvAslttQb8YZr1os7/5ry0P8VDNoZK6T8pnZpdW4bb9ZWPQ2NPtlhxf/A5yPUApt+0/MP2uqy5nLkaKLyZycuOKCp13u9mWXXasol4staAPYyprN1p5CvkR1nD5pxz9jQDPu1Pvbii3yklQmr2U/LtDUr9Fngelp0NqwDsmirPtoLRWJdxOiQrp9Yr8XGiTk3XyxF2eFuw3+ju5aRJl1Yu+f+LMM1eiexc6/lK0QuWpYhkd3XT+UsfOXhd2WKpO6W/TO3BUO8H/BB7RwuB6W7b7AAAAAElFTkSuQmCC"; g.logo=function(c,e){"free"==c.edition()?e=null:(a.defaults.file="",a.defaults.prefix="");h(this,new a(c,e))}})(jwplayer.html5);(function(g){var h=g.model;g.model=function(a,c){var e=new jwplayer.utils.key(a.key),b=new h(a,c),d=b.componentConfig;b.edition=function(){return e.edition()};b.componentConfig=function(a){return"logo"==a?b.logo:d(a)};return b}})(jwplayer.html5);(function(g){g.player.prototype.edition=function(){return this._model.edition()}})(jwplayer.html5); (function(g){var h=jwplayer.utils.extend,a=g.rightclick;g.rightclick=function(c,e){if("free"==c.edition())e.aboutlink="http://www.longtailvideo.com/jwpabout/?a\x3dr\x26v\x3d"+g.version+"\x26m\x3dh\x26e\x3df",delete e.abouttext;else{if(!e.aboutlink){var b="http://www.longtailvideo.com/jwpabout/?a\x3dr\x26v\x3d"+g.version+"\x26m\x3dh\x26e\x3d",d=c.edition();e.aboutlink=b+("pro"==d?"p":"premium"==d?"r":"ads"==d?"a":"f")}e.abouttext?e.abouttext+=" ...":(b=c.edition(),b=b.charAt(0).toUpperCase()+b.substr(1), e.abouttext="About JW Player "+g.version+" ("+b+" edition)")}h(this,new a(c,e))}})(jwplayer.html5);(function(g){var h=g.view;g.view=function(a,c){var e=new h(a,c);"invalid"==c.edition()&&e.setupError("Error setting up player: Invalid license key");return e}})(jwplayer.html5); "undefined"==typeof jwplayer&&(jwplayer=function(e){if(jwplayer.api)return jwplayer.api.selectPlayer(e)},jwplayer.version="6.8.4616",jwplayer.vid=document.createElement("video"),jwplayer.audio=document.createElement("audio"),jwplayer.source=document.createElement("source"),function(e){function a(h){return function(){return b(h)}}function l(h,b,a,k,j){return function(){var d,f;if(j)a(h);else{try{if(d=h.responseXML)if(f=d.firstChild,d.lastChild&&"parsererror"===d.lastChild.nodeName){k&&k("Invalid XML"); return}}catch(g){}if(d&&f)return a(h);(d=c.parseXML(h.responseText))&&d.firstChild?(h=c.extend({},h,{responseXML:d}),a(h)):k&&k(h.responseText?"Invalid XML":b)}}}var g=document,f=window,d=navigator,c=e.utils=function(){};c.exists=function(h){switch(typeof h){case "string":return 0<h.length;case "object":return null!==h;case "undefined":return!1}return!0};c.styleDimension=function(h){return h+(0<h.toString().indexOf("%")?"":"px")};c.getAbsolutePath=function(h,b){c.exists(b)||(b=g.location.href);if(c.exists(h)){var a; if(c.exists(h)){a=h.indexOf("://");var k=h.indexOf("?");a=0<a&&(0>k||k>a)}else a=void 0;if(a)return h;a=b.substring(0,b.indexOf("://")+3);var k=b.substring(a.length,b.indexOf("/",a.length+1)),j;0===h.indexOf("/")?j=h.split("/"):(j=b.split("?")[0],j=j.substring(a.length+k.length+1,j.lastIndexOf("/")),j=j.split("/").concat(h.split("/")));for(var d=[],f=0;f<j.length;f++)j[f]&&(c.exists(j[f])&&"."!=j[f])&&(".."==j[f]?d.pop():d.push(j[f]));return a+k+"/"+d.join("/")}};c.extend=function(){var h=c.extend.arguments; if(1<h.length){for(var a=1;a<h.length;a++)c.foreach(h[a],function(a,k){try{c.exists(k)&&(h[0][a]=k)}catch(b){}});return h[0]}return null};var m=window.console=window.console||{log:function(){}};c.log=function(){var h=Array.prototype.slice.call(arguments,0);"object"===typeof m.log?m.log(h):m.log.apply(m,h)};var b=c.userAgentMatch=function(h){return null!==d.userAgent.toLowerCase().match(h)};c.isIE=c.isMSIE=a(/msie/i);c.isFF=a(/firefox/i);c.isChrome=a(/chrome/i);c.isIPod=a(/iP(hone|od)/i);c.isIPad= a(/iPad/i);c.isSafari602=a(/Macintosh.*Mac OS X 10_8.*6\.0\.\d* Safari/i);c.isIETrident=function(h){return h?(h=parseFloat(h).toFixed(1),b(RegExp("msie\\s*"+h+"|trident/.+rv:\\s*"+h,"i"))):b(/msie|trident/i)};c.isSafari=function(){return b(/safari/i)&&!b(/chrome/i)&&!b(/chromium/i)&&!b(/android/i)};c.isIOS=function(h){return h?b(RegExp("iP(hone|ad|od).+\\sOS\\s"+h,"i")):b(/iP(hone|ad|od)/i)};c.isAndroid=function(h,a){var c=a?!b(/chrome\/[23456789]/i):!0;return h?c&&b(RegExp("android.*"+h,"i")):c&& b(/android/i)};c.isMobile=function(){return c.isIOS()||c.isAndroid()};c.saveCookie=function(h,a){g.cookie="jwplayer."+h+"\x3d"+a+"; path\x3d/"};c.getCookies=function(){for(var h={},a=g.cookie.split("; "),c=0;c<a.length;c++){var k=a[c].split("\x3d");0===k[0].indexOf("jwplayer.")&&(h[k[0].substring(9,k[0].length)]=k[1])}return h};c.typeOf=function(h){var a=typeof h;return"object"===a?!h?"null":h instanceof Array?"array":a:a};c.translateEventResponse=function(h,a){var b=c.extend({},a);if(h==e.events.JWPLAYER_FULLSCREEN&& !b.fullscreen)b.fullscreen="true"==b.message?!0:!1,delete b.message;else if("object"==typeof b.data){var k=b.data;delete b.data;b=c.extend(b,k)}else"object"==typeof b.metadata&&c.deepReplaceKeyName(b.metadata,["__dot__","__spc__","__dsh__","__default__"],["."," ","-","default"]);c.foreach(["position","duration","offset"],function(h,a){b[a]&&(b[a]=Math.round(1E3*b[a])/1E3)});return b};c.flashVersion=function(){if(c.isAndroid())return 0;var h=d.plugins,a;try{if("undefined"!==h&&(a=h["Shockwave Flash"]))return parseInt(a.description.replace(/\D+(\d+)\..*/, "$1"),10)}catch(b){}if("undefined"!=typeof f.ActiveXObject)try{if(a=new f.ActiveXObject("ShockwaveFlash.ShockwaveFlash"))return parseInt(a.GetVariable("$version").split(" ")[1].split(",")[0],10)}catch(k){}return 0};c.getScriptPath=function(h){for(var a=g.getElementsByTagName("script"),b=0;b<a.length;b++){var c=a[b].src;if(c&&0<=c.indexOf(h))return c.substr(0,c.indexOf(h))}return""};c.deepReplaceKeyName=function(h,a,b){switch(e.utils.typeOf(h)){case "array":for(var k=0;k<h.length;k++)h[k]=e.utils.deepReplaceKeyName(h[k], a,b);break;case "object":c.foreach(h,function(c,k){var d;if(a instanceof Array&&b instanceof Array){if(a.length!=b.length)return;d=a}else d=[a];for(var f=c,g=0;g<d.length;g++)f=f.replace(RegExp(a[g],"g"),b[g]);h[f]=e.utils.deepReplaceKeyName(k,a,b);c!=f&&delete h[c]})}return h};var p=c.pluginPathType={ABSOLUTE:0,RELATIVE:1,CDN:2};c.getPluginPathType=function(h){if("string"==typeof h){h=h.split("?")[0];var a=h.indexOf("://");if(0<a)return p.ABSOLUTE;var b=h.indexOf("/");h=c.extension(h);return 0>a&& 0>b&&(!h||!isNaN(h))?p.CDN:p.RELATIVE}};c.getPluginName=function(h){return h.replace(/^(.*\/)?([^-]*)-?.*\.(swf|js)$/,"$2")};c.getPluginVersion=function(h){return h.replace(/[^-]*-?([^\.]*).*$/,"$1")};c.isYouTube=function(h){return/^(http|\/\/).*(youtube\.com|youtu\.be)\/.+/.test(h)};c.youTubeID=function(h){try{return/v[=\/]([^?&]*)|youtu\.be\/([^?]*)|^([\w-]*)$/i.exec(h).slice(1).join("").replace("?","")}catch(a){return""}};c.isRtmp=function(h,a){return 0===h.indexOf("rtmp")||"rtmp"==a};c.foreach= function(a,b){var d,k;for(d in a)"function"==c.typeOf(a.hasOwnProperty)?a.hasOwnProperty(d)&&(k=a[d],b(d,k)):(k=a[d],b(d,k))};c.isHTTPS=function(){return 0===f.location.href.indexOf("https")};c.repo=function(){var a="http://p.jwpcdn.com/"+e.version.split(/\W/).splice(0,2).join("/")+"/";try{c.isHTTPS()&&(a=a.replace("http://","https://ssl."))}catch(b){}return a};c.ajax=function(a,b,d,k){var j;0<a.indexOf("#")&&(a=a.replace(/#.*$/,""));if(a&&0<=a.indexOf("://")&&a.split("/")[2]!=f.location.href.split("/")[2]&& c.exists(f.XDomainRequest))j=new f.XDomainRequest,j.onload=l(j,a,b,d,k),j.ontimeout=j.onprogress=function(){},j.timeout=5E3;else if(c.exists(f.XMLHttpRequest)){var g=j=new f.XMLHttpRequest,t=a;j.onreadystatechange=function(){if(4===g.readyState)switch(g.status){case 200:l(g,t,b,d,k)();break;case 404:d("File not found")}}}else return d&&d(),j;j.overrideMimeType&&j.overrideMimeType("text/xml");j.onerror=function(){d("Error loading file")};setTimeout(function(){try{j.open("GET",a,!0),j.send()}catch(b){d&& d(a)}},0);return j};c.parseXML=function(a){var b;try{if(f.DOMParser){if(b=(new f.DOMParser).parseFromString(a,"text/xml"),b.childNodes&&b.childNodes.length&&"parsererror"==b.childNodes[0].firstChild.nodeName)return}else b=new f.ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a)}catch(c){return}return b};c.filterPlaylist=function(a,b){var d=[],k,j,f,g;for(k=0;k<a.length;k++)if(j=c.extend({},a[k]),j.sources=c.filterSources(j.sources),0<j.sources.length){for(f=0;f<j.sources.length;f++)g= j.sources[f],g.label||(g.label=f.toString());d.push(j)}if(b&&0===d.length)for(k=0;k<a.length;k++)if(j=c.extend({},a[k]),j.sources=c.filterSources(j.sources,!0),0<j.sources.length){for(f=0;f<j.sources.length;f++)g=j.sources[f],g.label||(g.label=f.toString());d.push(j)}return d};c.filterSources=function(a,b){var d,k,j=c.extensionmap;if(a){k=[];for(var f=0;f<a.length;f++){var g=a[f].type,m=a[f].file;m&&(m=c.trim(m));g||(g=j.extType(c.extension(m)),a[f].type=g);b?e.embed.flashCanPlay(m,g)&&(d||(d=g), g==d&&k.push(c.extend({},a[f]))):c.canPlayHTML5(g)&&(d||(d=g),g==d&&k.push(c.extend({},a[f])))}}return k};c.canPlayHTML5=function(a){if(c.isAndroid()&&("hls"==a||"m3u"==a||"m3u8"==a))return!1;a=c.extensionmap.types[a];return!!a&&!!e.vid.canPlayType&&e.vid.canPlayType(a)};c.seconds=function(a){a=a.replace(",",".");var b=a.split(":"),c=0;"s"==a.slice(-1)?c=parseFloat(a):"m"==a.slice(-1)?c=60*parseFloat(a):"h"==a.slice(-1)?c=3600*parseFloat(a):1<b.length?(c=parseFloat(b[b.length-1]),c+=60*parseFloat(b[b.length- 2]),3==b.length&&(c+=3600*parseFloat(b[b.length-3]))):c=parseFloat(a);return c};c.serialize=function(a){return null==a?null:"true"==a.toString().toLowerCase()?!0:"false"==a.toString().toLowerCase()?!1:isNaN(Number(a))||5<a.length||0===a.length?a:Number(a)}}(jwplayer),function(e){var a="video/",l=e.foreach,g={mp4:a+"mp4",vorbis:"audio/ogg",ogg:a+"ogg",webm:a+"webm",aac:"audio/mp4",mp3:"audio/mpeg",hls:"application/vnd.apple.mpegurl"},f={mp4:g.mp4,f4v:g.mp4,m4v:g.mp4,mov:g.mp4,m4a:g.aac,f4a:g.aac,aac:g.aac, mp3:g.mp3,ogv:g.ogg,ogg:g.vorbis,oga:g.vorbis,webm:g.webm,m3u8:g.hls,hls:g.hls},a="video",a={flv:a,f4v:a,mov:a,m4a:a,m4v:a,mp4:a,aac:a,f4a:a,mp3:"sound",smil:"rtmp",m3u8:"hls",hls:"hls"},d=e.extensionmap={};l(f,function(a,f){d[a]={html5:f}});l(a,function(a,f){d[a]||(d[a]={});d[a].flash=f});d.types=g;d.mimeType=function(a){var d;l(g,function(b,f){!d&&f==a&&(d=b)});return d};d.extType=function(a){return d.mimeType(f[a])}}(jwplayer.utils),function(e){var a=e.loaderstatus={NEW:0,LOADING:1,ERROR:2,COMPLETE:3}, l=document;e.scriptloader=function(g){function f(){c=a.ERROR;b.sendEvent(m.ERROR)}function d(){c=a.COMPLETE;b.sendEvent(m.COMPLETE)}var c=a.NEW,m=jwplayer.events,b=new m.eventdispatcher;e.extend(this,b);this.load=function(){var b=e.scriptloader.loaders[g];if(b&&(b.getStatus()==a.NEW||b.getStatus()==a.LOADING))b.addEventListener(m.ERROR,f),b.addEventListener(m.COMPLETE,d);else if(e.scriptloader.loaders[g]=this,c==a.NEW){c=a.LOADING;var h=l.createElement("script");h.addEventListener?(h.onload=d,h.onerror= f):h.readyState&&(h.onreadystatechange=function(){("loaded"==h.readyState||"complete"==h.readyState)&&d()});l.getElementsByTagName("head")[0].appendChild(h);h.src=g}};this.getStatus=function(){return c}};e.scriptloader.loaders={}}(jwplayer.utils),function(e){e.trim=function(a){return a.replace(/^\s*/,"").replace(/\s*$/,"")};e.pad=function(a,e,g){for(g||(g="0");a.length<e;)a=g+a;return a};e.xmlAttribute=function(a,e){for(var g=0;g<a.attributes.length;g++)if(a.attributes[g].name&&a.attributes[g].name.toLowerCase()== e.toLowerCase())return a.attributes[g].value.toString();return""};e.extension=function(a){if(!a||"rtmp"==a.substr(0,4))return"";a=a.substring(a.lastIndexOf("/")+1,a.length).split("?")[0].split("#")[0];if(-1<a.lastIndexOf("."))return a.substr(a.lastIndexOf(".")+1,a.length).toLowerCase()};e.stringToColor=function(a){a=a.replace(/(#|0x)?([0-9A-F]{3,6})$/gi,"$2");3==a.length&&(a=a.charAt(0)+a.charAt(0)+a.charAt(1)+a.charAt(1)+a.charAt(2)+a.charAt(2));return parseInt(a,16)}}(jwplayer.utils),function(e){var a= "touchmove",l="touchstart";e.touch=function(g){function f(k){k.type==l?(b=!0,h=c(n.DRAG_START,k)):k.type==a?b&&(q||(d(n.DRAG_START,k,h),q=!0),d(n.DRAG,k)):(b&&(q?d(n.DRAG_END,k):(k.cancelBubble=!0,d(n.TAP,k))),b=q=!1,h=null)}function d(a,b,d){if(p[a]&&(b.preventManipulation&&b.preventManipulation(),b.preventDefault&&b.preventDefault(),b=d?d:c(a,b)))p[a](b)}function c(a,b){var d=null;b.touches&&b.touches.length?d=b.touches[0]:b.changedTouches&&b.changedTouches.length&&(d=b.changedTouches[0]);if(!d)return null; var c=m.getBoundingClientRect(),d={type:a,target:m,x:d.pageX-window.pageXOffset-c.left,y:d.pageY,deltaX:0,deltaY:0};a!=n.TAP&&h&&(d.deltaX=d.x-h.x,d.deltaY=d.y-h.y);return d}var m=g,b=!1,p={},h=null,q=!1,n=e.touchEvents;document.addEventListener(a,f);document.addEventListener("touchend",function(a){b&&q&&d(n.DRAG_END,a);b=q=!1;h=null});document.addEventListener("touchcancel",f);g.addEventListener(l,f);g.addEventListener("touchend",f);this.addEventListener=function(a,b){p[a]=b};this.removeEventListener= function(a){delete p[a]};return this}}(jwplayer.utils),function(e){e.touchEvents={DRAG:"jwplayerDrag",DRAG_START:"jwplayerDragStart",DRAG_END:"jwplayerDragEnd",TAP:"jwplayerTap"}}(jwplayer.utils),function(e){e.key=function(a){var l,g,f;this.edition=function(){return f&&f.getTime()<(new Date).getTime()?"invalid":l};this.token=function(){return g};e.exists(a)||(a="");try{a=e.tea.decrypt(a,"36QXq4W@GSBV^teR");var d=a.split("/");(l=d[0])?/^(free|pro|premium|ads)$/i.test(l)?(g=d[1],d[2]&&0<parseInt(d[2])&& (f=new Date,f.setTime(String(d[2])))):l="invalid":l="free"}catch(c){l="invalid"}}}(jwplayer.utils),function(e){var a=e.tea={};a.encrypt=function(f,d){if(0==f.length)return"";var c=a.strToLongs(g.encode(f));1>=c.length&&(c[1]=0);for(var m=a.strToLongs(g.encode(d).slice(0,16)),b=c.length,e=c[b-1],h=c[0],q,n=Math.floor(6+52/b),k=0;0<n--;){k+=2654435769;q=k>>>2&3;for(var j=0;j<b;j++)h=c[(j+1)%b],e=(e>>>5^h<<2)+(h>>>3^e<<4)^(k^h)+(m[j&3^q]^e),e=c[j]+=e}c=a.longsToStr(c);return l.encode(c)};a.decrypt=function(f, d){if(0==f.length)return"";for(var c=a.strToLongs(l.decode(f)),m=a.strToLongs(g.encode(d).slice(0,16)),b=c.length,e=c[b-1],h=c[0],q,n=2654435769*Math.floor(6+52/b);0!=n;){q=n>>>2&3;for(var k=b-1;0<=k;k--)e=c[0<k?k-1:b-1],e=(e>>>5^h<<2)+(h>>>3^e<<4)^(n^h)+(m[k&3^q]^e),h=c[k]-=e;n-=2654435769}c=a.longsToStr(c);c=c.replace(/\0+$/,"");return g.decode(c)};a.strToLongs=function(a){for(var d=Array(Math.ceil(a.length/4)),c=0;c<d.length;c++)d[c]=a.charCodeAt(4*c)+(a.charCodeAt(4*c+1)<<8)+(a.charCodeAt(4*c+ 2)<<16)+(a.charCodeAt(4*c+3)<<24);return d};a.longsToStr=function(a){for(var d=Array(a.length),c=0;c<a.length;c++)d[c]=String.fromCharCode(a[c]&255,a[c]>>>8&255,a[c]>>>16&255,a[c]>>>24&255);return d.join("")};var l={code:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\x3d",encode:function(a,d){var c,e,b,p,h=[],q="",n,k,j=l.code;k=("undefined"==typeof d?0:d)?g.encode(a):a;n=k.length%3;if(0<n)for(;3>n++;)q+="\x3d",k+="\x00";for(n=0;n<k.length;n+=3)c=k.charCodeAt(n),e=k.charCodeAt(n+ 1),b=k.charCodeAt(n+2),p=c<<16|e<<8|b,c=p>>18&63,e=p>>12&63,b=p>>6&63,p&=63,h[n/3]=j.charAt(c)+j.charAt(e)+j.charAt(b)+j.charAt(p);h=h.join("");return h=h.slice(0,h.length-q.length)+q},decode:function(a,d){d="undefined"==typeof d?!1:d;var c,e,b,p,h,q=[],n,k=l.code;n=d?g.decode(a):a;for(var j=0;j<n.length;j+=4)c=k.indexOf(n.charAt(j)),e=k.indexOf(n.charAt(j+1)),p=k.indexOf(n.charAt(j+2)),h=k.indexOf(n.charAt(j+3)),b=c<<18|e<<12|p<<6|h,c=b>>>16&255,e=b>>>8&255,b&=255,q[j/4]=String.fromCharCode(c,e, b),64==h&&(q[j/4]=String.fromCharCode(c,e)),64==p&&(q[j/4]=String.fromCharCode(c));p=q.join("");return d?g.decode(p):p}},g={encode:function(a){a=a.replace(/[\u0080-\u07ff]/g,function(a){a=a.charCodeAt(0);return String.fromCharCode(192|a>>6,128|a&63)});return a=a.replace(/[\u0800-\uffff]/g,function(a){a=a.charCodeAt(0);return String.fromCharCode(224|a>>12,128|a>>6&63,128|a&63)})},decode:function(a){a=a.replace(/[\u00e0-\u00ef][\u0080-\u00bf][\u0080-\u00bf]/g,function(a){a=(a.charCodeAt(0)&15)<<12| (a.charCodeAt(1)&63)<<6|a.charCodeAt(2)&63;return String.fromCharCode(a)});return a=a.replace(/[\u00c0-\u00df][\u0080-\u00bf]/g,function(a){a=(a.charCodeAt(0)&31)<<6|a.charCodeAt(1)&63;return String.fromCharCode(a)})}}}(jwplayer.utils),function(e){e.events={COMPLETE:"COMPLETE",ERROR:"ERROR",API_READY:"jwplayerAPIReady",JWPLAYER_READY:"jwplayerReady",JWPLAYER_FULLSCREEN:"jwplayerFullscreen",JWPLAYER_RESIZE:"jwplayerResize",JWPLAYER_ERROR:"jwplayerError",JWPLAYER_SETUP_ERROR:"jwplayerSetupError",JWPLAYER_MEDIA_BEFOREPLAY:"jwplayerMediaBeforePlay", JWPLAYER_MEDIA_BEFORECOMPLETE:"jwplayerMediaBeforeComplete",JWPLAYER_COMPONENT_SHOW:"jwplayerComponentShow",JWPLAYER_COMPONENT_HIDE:"jwplayerComponentHide",JWPLAYER_MEDIA_BUFFER:"jwplayerMediaBuffer",JWPLAYER_MEDIA_BUFFER_FULL:"jwplayerMediaBufferFull",JWPLAYER_MEDIA_ERROR:"jwplayerMediaError",JWPLAYER_MEDIA_LOADED:"jwplayerMediaLoaded",JWPLAYER_MEDIA_COMPLETE:"jwplayerMediaComplete",JWPLAYER_MEDIA_SEEK:"jwplayerMediaSeek",JWPLAYER_MEDIA_TIME:"jwplayerMediaTime",JWPLAYER_MEDIA_VOLUME:"jwplayerMediaVolume", JWPLAYER_MEDIA_META:"jwplayerMediaMeta",JWPLAYER_MEDIA_MUTE:"jwplayerMediaMute",JWPLAYER_MEDIA_LEVELS:"jwplayerMediaLevels",JWPLAYER_MEDIA_LEVEL_CHANGED:"jwplayerMediaLevelChanged",JWPLAYER_CAPTIONS_CHANGED:"jwplayerCaptionsChanged",JWPLAYER_CAPTIONS_LIST:"jwplayerCaptionsList",JWPLAYER_CAPTIONS_LOADED:"jwplayerCaptionsLoaded",JWPLAYER_PLAYER_STATE:"jwplayerPlayerState",state:{BUFFERING:"BUFFERING",IDLE:"IDLE",PAUSED:"PAUSED",PLAYING:"PLAYING"},JWPLAYER_PLAYLIST_LOADED:"jwplayerPlaylistLoaded",JWPLAYER_PLAYLIST_ITEM:"jwplayerPlaylistItem", JWPLAYER_PLAYLIST_COMPLETE:"jwplayerPlaylistComplete",JWPLAYER_DISPLAY_CLICK:"jwplayerViewClick",JWPLAYER_CONTROLS:"jwplayerViewControls",JWPLAYER_USER_ACTION:"jwplayerUserAction",JWPLAYER_INSTREAM_CLICK:"jwplayerInstreamClicked",JWPLAYER_INSTREAM_DESTROYED:"jwplayerInstreamDestroyed",JWPLAYER_AD_TIME:"jwplayerAdTime",JWPLAYER_AD_ERROR:"jwplayerAdError",JWPLAYER_AD_CLICK:"jwplayerAdClicked",JWPLAYER_AD_COMPLETE:"jwplayerAdComplete",JWPLAYER_AD_IMPRESSION:"jwplayerAdImpression",JWPLAYER_AD_COMPANIONS:"jwplayerAdCompanions", JWPLAYER_AD_SKIPPED:"jwplayerAdSkipped"}}(jwplayer),function(e){var a=e.utils;e.events.eventdispatcher=function(l,g){function f(c,b,d){if(c)for(var h=0;h<c.length;h++){var g=c[h];if(g){null!==g.count&&0===--g.count&&delete c[h];try{g.listener(b)}catch(f){a.log('Error handling "'+d+'" event listener ['+h+"]: "+f.toString(),g.listener,b)}}}}var d,c;this.resetEventListeners=function(){d={};c=[]};this.resetEventListeners();this.addEventListener=function(c,b,g){try{a.exists(d[c])||(d[c]=[]),"string"== a.typeOf(b)&&(b=(new Function("return "+b))()),d[c].push({listener:b,count:g||null})}catch(h){a.log("error",h)}return!1};this.removeEventListener=function(c,b){if(d[c]){try{for(var g=0;g<d[c].length;g++)if(d[c][g].listener.toString()==b.toString()){d[c].splice(g,1);break}}catch(h){a.log("error",h)}return!1}};this.addGlobalListener=function(d,b){try{"string"==a.typeOf(d)&&(d=(new Function("return "+d))()),c.push({listener:d,count:b||null})}catch(g){a.log("error",g)}return!1};this.removeGlobalListener= function(d){if(d){try{for(var b=c.length;b--;)c[b].listener.toString()==d.toString()&&c.splice(b,1)}catch(g){a.log("error",g)}return!1}};this.sendEvent=function(m,b){a.exists(b)||(b={});a.extend(b,{id:l,version:e.version,type:m});g&&a.log(m,b);f(d[m],b,m);f(c,b,m)}}}(window.jwplayer),function(e){var a={},l={};e.plugins=function(){};e.plugins.loadPlugins=function(g,f){l[g]=new e.plugins.pluginloader(new e.plugins.model(a),f);return l[g]};e.plugins.registerPlugin=function(g,f,d,c){var m=e.utils.getPluginName(g); a[m]||(a[m]=new e.plugins.plugin(g));a[m].registerPlugin(g,f,d,c)}}(jwplayer),function(e){e.plugins.model=function(a){this.addPlugin=function(l){var g=e.utils.getPluginName(l);a[g]||(a[g]=new e.plugins.plugin(l));return a[g]};this.getPlugins=function(){return a}}}(jwplayer),function(e){var a=jwplayer.utils,l=jwplayer.events;e.pluginmodes={FLASH:0,JAVASCRIPT:1,HYBRID:2};e.plugin=function(g){function f(){switch(a.getPluginPathType(g)){case a.pluginPathType.ABSOLUTE:return g;case a.pluginPathType.RELATIVE:return a.getAbsolutePath(g, window.location.href)}}function d(){q=setTimeout(function(){m=a.loaderstatus.COMPLETE;n.sendEvent(l.COMPLETE)},1E3)}function c(){m=a.loaderstatus.ERROR;n.sendEvent(l.ERROR)}var m=a.loaderstatus.NEW,b,p,h,q,n=new l.eventdispatcher;a.extend(this,n);this.load=function(){if(m==a.loaderstatus.NEW)if(0<g.lastIndexOf(".swf"))b=g,m=a.loaderstatus.COMPLETE,n.sendEvent(l.COMPLETE);else if(a.getPluginPathType(g)==a.pluginPathType.CDN)m=a.loaderstatus.COMPLETE,n.sendEvent(l.COMPLETE);else{m=a.loaderstatus.LOADING; var k=new a.scriptloader(f());k.addEventListener(l.COMPLETE,d);k.addEventListener(l.ERROR,c);k.load()}};this.registerPlugin=function(c,d,g,f){q&&(clearTimeout(q),q=void 0);h=d;g&&f?(b=f,p=g):"string"==typeof g?b=g:"function"==typeof g?p=g:!g&&!f&&(b=c);m=a.loaderstatus.COMPLETE;n.sendEvent(l.COMPLETE)};this.getStatus=function(){return m};this.getPluginName=function(){return a.getPluginName(g)};this.getFlashPath=function(){if(b)switch(a.getPluginPathType(b)){case a.pluginPathType.ABSOLUTE:return b; case a.pluginPathType.RELATIVE:return 0<g.lastIndexOf(".swf")?a.getAbsolutePath(b,window.location.href):a.getAbsolutePath(b,f())}return null};this.getJS=function(){return p};this.getTarget=function(){return h};this.getPluginmode=function(){if("undefined"!=typeof b&&"undefined"!=typeof p)return e.pluginmodes.HYBRID;if("undefined"!=typeof b)return e.pluginmodes.FLASH;if("undefined"!=typeof p)return e.pluginmodes.JAVASCRIPT};this.getNewInstance=function(a,b,c){return new p(a,b,c)};this.getURL=function(){return g}}}(jwplayer.plugins), function(e){var a=e.utils,l=e.events,g=a.foreach;e.plugins.pluginloader=function(f,d){function c(){h?k.sendEvent(l.ERROR,{message:q}):p||(p=!0,b=a.loaderstatus.COMPLETE,k.sendEvent(l.COMPLETE))}function m(){n||c();if(!p&&!h){var b=0,d=f.getPlugins();a.foreach(n,function(g){g=a.getPluginName(g);var k=d[g];g=k.getJS();var f=k.getTarget(),k=k.getStatus();if(k==a.loaderstatus.LOADING||k==a.loaderstatus.NEW)b++;else if(g&&(!f||parseFloat(f)>parseFloat(e.version)))h=!0,q="Incompatible player version",c()}); 0==b&&c()}}var b=a.loaderstatus.NEW,p=!1,h=!1,q,n=d,k=new l.eventdispatcher;a.extend(this,k);this.setupPlugins=function(b,c,d){var k={length:0,plugins:{}},h=0,j={},e=f.getPlugins();g(c.plugins,function(g,f){var m=a.getPluginName(g),p=e[m],l=p.getFlashPath(),n=p.getJS(),q=p.getURL();l&&(k.plugins[l]=a.extend({},f),k.plugins[l].pluginmode=p.getPluginmode(),k.length++);try{if(n&&c.plugins&&c.plugins[q]){var C=document.createElement("div");C.id=b.id+"_"+m;C.style.position="absolute";C.style.top=0;C.style.zIndex= h+10;j[m]=p.getNewInstance(b,a.extend({},c.plugins[q]),C);h++;b.onReady(d(j[m],C,!0));b.onResize(d(j[m],C))}}catch(F){a.log("ERROR: Failed to load "+m+".")}});b.plugins=j;return k};this.load=function(){if(!(a.exists(d)&&"object"!=a.typeOf(d))){b=a.loaderstatus.LOADING;g(d,function(b){a.exists(b)&&(b=f.addPlugin(b),b.addEventListener(l.COMPLETE,m),b.addEventListener(l.ERROR,j))});var c=f.getPlugins();g(c,function(a,b){b.load()})}m()};var j=this.pluginFailed=function(){h||(h=!0,q="File not found",c())}; this.getStatus=function(){return b}}}(jwplayer),function(){jwplayer.parsers={localName:function(e){return e?e.localName?e.localName:e.baseName?e.baseName:"":""},textContent:function(e){return e?e.textContent?jwplayer.utils.trim(e.textContent):e.text?jwplayer.utils.trim(e.text):"":""},getChildNode:function(e,a){return e.childNodes[a]},numChildren:function(e){return e.childNodes?e.childNodes.length:0}}}(jwplayer),function(e){var a=e.parsers;(a.jwparser=function(){}).parseEntry=function(l,g){for(var f= [],d=[],c=e.utils.xmlAttribute,m=0;m<l.childNodes.length;m++){var b=l.childNodes[m];if("jwplayer"==b.prefix){var p=a.localName(b);"source"==p?(delete g.sources,f.push({file:c(b,"file"),"default":c(b,"default"),label:c(b,"label"),type:c(b,"type")})):"track"==p?(delete g.tracks,d.push({file:c(b,"file"),"default":c(b,"default"),kind:c(b,"kind"),label:c(b,"label")})):(g[p]=e.utils.serialize(a.textContent(b)),"file"==p&&g.sources&&delete g.sources)}g.file||(g.file=g.link)}if(f.length){g.sources=[];for(m= 0;m<f.length;m++)0<f[m].file.length&&(f[m]["default"]="true"==f[m]["default"]?!0:!1,f[m].label.length||delete f[m].label,g.sources.push(f[m]))}if(d.length){g.tracks=[];for(m=0;m<d.length;m++)0<d[m].file.length&&(d[m]["default"]="true"==d[m]["default"]?!0:!1,d[m].kind=!d[m].kind.length?"captions":d[m].kind,d[m].label.length||delete d[m].label,g.tracks.push(d[m]))}return g}}(jwplayer),function(e){var a=jwplayer.utils,l=a.xmlAttribute,g=e.localName,f=e.textContent,d=e.numChildren,c=e.mediaparser=function(){}; c.parseGroup=function(e,b){var p,h,q=[];for(h=0;h<d(e);h++)if(p=e.childNodes[h],"media"==p.prefix&&g(p))switch(g(p).toLowerCase()){case "content":l(p,"duration")&&(b.duration=a.seconds(l(p,"duration")));0<d(p)&&(b=c.parseGroup(p,b));l(p,"url")&&(b.sources||(b.sources=[]),b.sources.push({file:l(p,"url"),type:l(p,"type"),width:l(p,"width"),label:l(p,"label")}));break;case "title":b.title=f(p);break;case "description":b.description=f(p);break;case "guid":b.mediaid=f(p);break;case "thumbnail":b.image|| (b.image=l(p,"url"));break;case "group":c.parseGroup(p,b);break;case "subtitle":var n={};n.file=l(p,"url");n.kind="captions";if(0<l(p,"lang").length){var k=n;p=l(p,"lang");var j={zh:"Chinese",nl:"Dutch",en:"English",fr:"French",de:"German",it:"Italian",ja:"Japanese",pt:"Portuguese",ru:"Russian",es:"Spanish"};p=j[p]?j[p]:p;k.label=p}q.push(n)}b.hasOwnProperty("tracks")||(b.tracks=[]);for(h=0;h<q.length;h++)b.tracks.push(q[h]);return b}}(jwplayer.parsers),function(e){function a(a){for(var b={},d=0;d< a.childNodes.length;d++){var h=a.childNodes[d],f=c(h);if(f)switch(f.toLowerCase()){case "enclosure":b.file=l.xmlAttribute(h,"url");break;case "title":b.title=g(h);break;case "guid":b.mediaid=g(h);break;case "pubdate":b.date=g(h);break;case "description":b.description=g(h);break;case "link":b.link=g(h);break;case "category":b.tags=b.tags?b.tags+g(h):g(h)}}b=e.mediaparser.parseGroup(a,b);b=e.jwparser.parseEntry(a,b);return new jwplayer.playlist.item(b)}var l=jwplayer.utils,g=e.textContent,f=e.getChildNode, d=e.numChildren,c=e.localName;e.rssparser={};e.rssparser.parse=function(g){for(var b=[],e=0;e<d(g);e++){var h=f(g,e);if("channel"==c(h).toLowerCase())for(var l=0;l<d(h);l++){var n=f(h,l);"item"==c(n).toLowerCase()&&b.push(a(n))}}return b}}(jwplayer.parsers),function(e){e.playlist=function(a){var l=[];if("array"==e.utils.typeOf(a))for(var g=0;g<a.length;g++)l.push(new e.playlist.item(a[g]));else l.push(new e.playlist.item(a));return l}}(jwplayer),function(e){var a=e.item=function(l){var g=jwplayer.utils, f=g.extend({},a.defaults,l);f.tracks=l&&g.exists(l.tracks)?l.tracks:[];0==f.sources.length&&(f.sources=[new e.source(f)]);for(var d=0;d<f.sources.length;d++){var c=f.sources[d]["default"];f.sources[d]["default"]=c?"true"==c.toString():!1;f.sources[d]=new e.source(f.sources[d])}if(f.captions&&!g.exists(l.tracks)){for(l=0;l<f.captions.length;l++)f.tracks.push(f.captions[l]);delete f.captions}for(d=0;d<f.tracks.length;d++)f.tracks[d]=new e.track(f.tracks[d]);return f};a.defaults={description:"",image:"", mediaid:"",title:"",sources:[],tracks:[]}}(jwplayer.playlist),function(e){var a=jwplayer,l=a.utils,g=a.events,f=a.parsers;e.loader=function(){function a(c){try{var d=c.responseXML.childNodes;c="";for(var l=0;l<d.length&&!(c=d[l],8!=c.nodeType);l++);"xml"==f.localName(c)&&(c=c.nextSibling);if("rss"!=f.localName(c))m("Not a valid RSS feed");else{var n=new e(f.rssparser.parse(c));b.sendEvent(g.JWPLAYER_PLAYLIST_LOADED,{playlist:n})}}catch(k){m()}}function c(a){m(a.match(/invalid/i)?"Not a valid RSS feed": "")}function m(a){b.sendEvent(g.JWPLAYER_ERROR,{message:a?a:"Error loading file"})}var b=new g.eventdispatcher;l.extend(this,b);this.load=function(b){l.ajax(b,a,c)}}}(jwplayer.playlist),function(e){var a=jwplayer.utils,l={file:void 0,label:void 0,type:void 0,"default":void 0};e.source=function(g){var f=a.extend({},l);a.foreach(l,function(d){a.exists(g[d])&&(f[d]=g[d],delete g[d])});f.type&&0<f.type.indexOf("/")&&(f.type=a.extensionmap.mimeType(f.type));"m3u8"==f.type&&(f.type="hls");"smil"==f.type&& (f.type="rtmp");return f}}(jwplayer.playlist),function(e){var a=jwplayer.utils,l={file:void 0,label:void 0,kind:"captions","default":!1};e.track=function(g){var f=a.extend({},l);g||(g={});a.foreach(l,function(d){a.exists(g[d])&&(f[d]=g[d],delete g[d])});return f}}(jwplayer.playlist),function(e){function a(a,c,d){var g=a.style;g.backgroundColor="#000";g.color="#FFF";g.width=l.styleDimension(d.width);g.height=l.styleDimension(d.height);g.display="table";g.opacity=1;d=document.createElement("p");g=d.style; g.verticalAlign="middle";g.textAlign="center";g.display="table-cell";g.font="15px/20px Arial, Helvetica, sans-serif";d.innerHTML=c.replace(":",":\x3cbr\x3e");a.innerHTML="";a.appendChild(d)}var l=e.utils,g=e.events,f=!0,d=!1,c=document,m=e.embed=function(b){function p(a,b){l.foreach(b,function(b,c){"function"==typeof a[b]&&a[b].call(a,c)})}function h(){if(!E)if("array"==l.typeOf(t.playlist)&&2>t.playlist.length&&(0==t.playlist.length||!t.playlist[0].sources||0==t.playlist[0].sources.length))k();else if(!B)if("string"== l.typeOf(t.playlist)){var a=new e.playlist.loader;a.addEventListener(g.JWPLAYER_PLAYLIST_LOADED,function(a){t.playlist=a.playlist;B=d;h()});a.addEventListener(g.JWPLAYER_ERROR,function(a){B=d;k(a)});B=f;a.load(t.playlist)}else if(y.getStatus()==l.loaderstatus.COMPLETE){for(a=0;a<t.modes.length;a++)if(t.modes[a].type&&m[t.modes[a].type]){var c=l.extend({},t),n=new m[t.modes[a].type](r,t.modes[a],c,y,b);if(n.supportsConfig())return n.addEventListener(g.ERROR,q),n.embed(),p(b,c.events),b}var u;t.fallback? (u="No suitable players found and fallback enabled",D=setTimeout(function(){j(u,f)},10),l.log(u),new m.download(r,t,k)):(u="No suitable players found and fallback disabled",j(u,d),l.log(u),r.parentNode.replaceChild(w,r))}}function q(a){u(A+a.message)}function n(a){u("Could not load plugins: "+a.message)}function k(a){a&&a.message?u("Error loading playlist: "+a.message):u(A+"No playable sources found")}function j(a,c){D&&(clearTimeout(D),D=null);D=setTimeout(function(){D=null;b.dispatchEvent(g.JWPLAYER_SETUP_ERROR, {message:a,fallback:c})},0)}function u(b){E||(t.fallback?(E=f,a(r,b,t),j(b,f)):j(b,d))}var t=new m.config(b.config),r,v,w,x=t.width,z=t.height,A="Error loading player: ",y=e.plugins.loadPlugins(b.id,t.plugins),B=d,E=d,D=null;t.fallbackDiv&&(w=t.fallbackDiv,delete t.fallbackDiv);t.id=b.id;v=c.getElementById(b.id);t.aspectratio?b.config.aspectratio=t.aspectratio:delete b.config.aspectratio;r=c.createElement("div");r.id=v.id;r.style.width=0<x.toString().indexOf("%")?x:x+"px";r.style.height=0<z.toString().indexOf("%")? z:z+"px";v.parentNode.replaceChild(r,v);this.embed=function(){E||(y.addEventListener(g.COMPLETE,h),y.addEventListener(g.ERROR,n),y.load())};this.errorScreen=u;return this};e.embed.errorScreen=a}(jwplayer),function(e){function a(a){if(a.playlist)for(var c=0;c<a.playlist.length;c++)a.playlist[c]=new f(a.playlist[c]);else{var e={};g.foreach(f.defaults,function(b){l(a,e,b)});e.sources||(a.levels?(e.sources=a.levels,delete a.levels):(c={},l(a,c,"file"),l(a,c,"type"),e.sources=c.file?[c]:[]));a.playlist= [new f(e)]}}function l(a,c,f){g.exists(a[f])&&(c[f]=a[f],delete a[f])}var g=e.utils,f=e.playlist.item;(e.embed.config=function(d){var c={fallback:!0,height:270,primary:"html5",width:480,base:d.base?d.base:g.getScriptPath("jwplayer.js"),aspectratio:""};d=g.extend(c,e.defaults,d);var c={type:"html5",src:d.base+"jwplayer.html5.js"},f={type:"flash",src:d.base+"jwplayer.flash.swf"};d.modes="flash"==d.primary?[f,c]:[c,f];d.listbar&&(d.playlistsize=d.listbar.size,d.playlistposition=d.listbar.position,d.playlistlayout= d.listbar.layout);d.flashplayer&&(f.src=d.flashplayer);d.html5player&&(c.src=d.html5player);a(d);f=d.aspectratio;if("string"!=typeof f||!g.exists(f))c=0;else{var b=f.indexOf(":");-1==b?c=0:(c=parseFloat(f.substr(0,b)),f=parseFloat(f.substr(b+1)),c=0>=c||0>=f?0:100*(f/c)+"%")}-1==d.width.toString().indexOf("%")?delete d.aspectratio:c?d.aspectratio=c:delete d.aspectratio;return d}).addConfig=function(d,c){a(c);return g.extend(d,c)}}(jwplayer),function(e){var a=e.utils,l=document;e.embed.download=function(g, f,d){function c(b,c){for(var d=l.querySelectorAll(b),g=0;g<d.length;g++)a.foreach(c,function(a,b){d[g].style[a]=b})}function e(a,b,c){a=l.createElement(a);b&&(a.className="jwdownload"+b);c&&c.appendChild(a);return a}var b=a.extend({},f),p=b.width?b.width:480,h=b.height?b.height:320,q;f=f.logo?f.logo:{prefix:a.repo(),file:"logo.png",margin:10};var n,k,j,b=b.playlist,u,t=["mp4","aac","mp3"];if(b&&b.length){u=b[0];q=u.sources;for(b=0;b<q.length;b++){var r=q[b],v=r.type?r.type:a.extensionmap.extType(a.extension(r.file)); r.file&&a.foreach(t,function(b){v==t[b]?(n=r.file,k=u.image):a.isYouTube(r.file)&&(j=r.file)})}n?(q=n,d=k,g&&(b=e("a","display",g),e("div","icon",b),e("div","logo",b),q&&b.setAttribute("href",a.getAbsolutePath(q))),b="#"+g.id+" .jwdownload",g.style.width="",g.style.height="",c(b+"display",{width:a.styleDimension(Math.max(320,p)),height:a.styleDimension(Math.max(180,h)),background:"black center no-repeat "+(d?"url("+d+")":""),backgroundSize:"contain",position:"relative",border:"none",display:"block"}), c(b+"display div",{position:"absolute",width:"100%",height:"100%"}),c(b+"logo",{top:f.margin+"px",right:f.margin+"px",background:"top right no-repeat url("+f.prefix+f.file+")"}),c(b+"icon",{background:"center no-repeat url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAA8CAYAAAA6/NlyAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAgNJREFUeNrs28lqwkAYB/CZqNVDDj2r6FN41QeIy8Fe+gj6BL275Q08u9FbT8ZdwVfotSBYEPUkxFOoks4EKiJdaDuTjMn3wWBO0V/+sySR8SNSqVRKIR8qaXHkzlqS9jCfzzWcTCYp9hF5o+59sVjsiRzcegSckFzcjT+ruN80TeSlAjCAAXzdJSGPFXRpAAMYwACGZQkSdhG4WCzehMNhqV6vG6vVSrirKVEw66YoSqDb7cqlUilE8JjHd/y1MQefVzqdDmiaJpfLZWHgXMHn8F6vJ1cqlVAkEsGuAn83J4gAd2RZymQygX6/L1erVQt+9ZPWb+CDwcCC2zXGJaewl/DhcHhK3DVj+KfKZrMWvFarcYNLomAv4aPRSFZVlTlcSPA5fDweW/BoNIqFnKV53JvncjkLns/n/cLdS+92O7RYLLgsKfv9/t8XlDn4eDyiw+HA9Jyz2eyt0+kY2+3WFC5hluej0Ha7zQQq9PPwdDq1Et1sNsx/nFBgCqWJ8oAK1aUptNVqcYWewE4nahfU0YQnk4ntUEfGMIU2m01HoLaCKbTRaDgKtaVLk9tBYaBcE/6Artdr4RZ5TB6/dC+9iIe/WgAMYADDpAUJAxjAAAYwgGFZgoS/AtNNTF7Z2bL0BYPBV3Jw5xFwwWcYxgtBP5OkE8i9G7aWGOOCruvauwADALMLMEbKf4SdAAAAAElFTkSuQmCC)"})): j?(f=j,g=e("iframe","",g),g.src="http://www.youtube.com/embed/"+a.youTubeID(f),g.width=p,g.height=h,g.style.border="none"):d()}}}(jwplayer),function(e){var a=e.utils,l=e.events,g={};(e.embed.flash=function(d,c,m,b,p){function h(a,b,c){var d=document.createElement("param");d.setAttribute("name",b);d.setAttribute("value",c);a.appendChild(d)}function q(a,b,c){return function(){try{c&&document.getElementById(p.id+"_wrapper").appendChild(b);var d=document.getElementById(p.id).getPluginConfig("display"); "function"==typeof a.resize&&a.resize(d.width,d.height);b.style.left=d.x;b.style.top=d.h}catch(g){}}}function n(b){if(!b)return{};var c={},d=[];a.foreach(b,function(b,g){var k=a.getPluginName(b);d.push(b);a.foreach(g,function(a,b){c[k+"."+a]=b})});c.plugins=d.join(",");return c}var k=new e.events.eventdispatcher,j=a.flashVersion();a.extend(this,k);this.embed=function(){m.id=p.id;if(10>j)return k.sendEvent(l.ERROR,{message:"Flash version must be 10.0 or greater"}),!1;var f,e,r=p.config.listbar,v=a.extend({}, m);if(d.id+"_wrapper"==d.parentNode.id)f=document.getElementById(d.id+"_wrapper");else{f=document.createElement("div");e=document.createElement("div");e.style.display="none";e.id=d.id+"_aspect";f.id=d.id+"_wrapper";f.style.position="relative";f.style.display="block";f.style.width=a.styleDimension(v.width);f.style.height=a.styleDimension(v.height);if(p.config.aspectratio){var w=parseFloat(p.config.aspectratio);e.style.display="block";e.style.marginTop=p.config.aspectratio;f.style.height="auto";f.style.display= "inline-block";r&&("bottom"==r.position?e.style.paddingBottom=r.size+"px":"right"==r.position&&(e.style.marginBottom=-1*r.size*(w/100)+"px"))}d.parentNode.replaceChild(f,d);f.appendChild(d);f.appendChild(e)}f=b.setupPlugins(p,v,q);0<f.length?a.extend(v,n(f.plugins)):delete v.plugins;"undefined"!=typeof v["dock.position"]&&"false"==v["dock.position"].toString().toLowerCase()&&(v.dock=v["dock.position"],delete v["dock.position"]);f=v.wmode?v.wmode:v.height&&40>=v.height?"transparent":"opaque";e="height width modes events primary base fallback volume".split(" "); for(r=0;r<e.length;r++)delete v[e[r]];e=a.getCookies();a.foreach(e,function(a,b){"undefined"==typeof v[a]&&(v[a]=b)});e=window.location.href.split("/");e.splice(e.length-1,1);e=e.join("/");v.base=e+"/";g[d.id]=v;a.isIE()?(e='\x3cobject classid\x3d"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" " width\x3d"100%" height\x3d"100%"id\x3d"'+d.id+'" name\x3d"'+d.id+'" tabindex\x3d0""\x3e',e+='\x3cparam name\x3d"movie" value\x3d"'+c.src+'"\x3e',e+='\x3cparam name\x3d"allowfullscreen" value\x3d"true"\x3e\x3cparam name\x3d"allowscriptaccess" value\x3d"always"\x3e', e+='\x3cparam name\x3d"seamlesstabbing" value\x3d"true"\x3e',e+='\x3cparam name\x3d"wmode" value\x3d"'+f+'"\x3e',e+='\x3cparam name\x3d"bgcolor" value\x3d"#000000"\x3e',e+="\x3c/object\x3e",d.outerHTML=e,f=document.getElementById(d.id)):(e=document.createElement("object"),e.setAttribute("type","application/x-shockwave-flash"),e.setAttribute("data",c.src),e.setAttribute("width","100%"),e.setAttribute("height","100%"),e.setAttribute("bgcolor","#000000"),e.setAttribute("id",d.id),e.setAttribute("name", d.id),e.setAttribute("tabindex",0),h(e,"allowfullscreen","true"),h(e,"allowscriptaccess","always"),h(e,"seamlesstabbing","true"),h(e,"wmode",f),d.parentNode.replaceChild(e,d),f=e);p.config.aspectratio&&(f.style.position="absolute");p.container=f;p.setPlayer(f,"flash")};this.supportsConfig=function(){if(j)if(m){if("string"==a.typeOf(m.playlist))return!0;try{var b=m.playlist[0].sources;if("undefined"==typeof b)return!0;for(var c=0;c<b.length;c++)if(b[c].file&&f(b[c].file,b[c].type))return!0}catch(d){}}else return!0; return!1}}).getVars=function(a){return g[a]};var f=e.embed.flashCanPlay=function(d,c){if(a.isYouTube(d)||a.isRtmp(d,c)||"hls"==c)return!0;var f=a.extensionmap[c?c:a.extension(d)];return!f?!1:!!f.flash}}(jwplayer),function(e){var a=e.utils,l=a.extensionmap,g=e.events;e.embed.html5=function(f,d,c,m,b){function p(a,b,c){return function(){try{var d=document.querySelector("#"+f.id+" .jwmain");c&&d.appendChild(b);"function"==typeof a.resize&&(a.resize(d.clientWidth,d.clientHeight),setTimeout(function(){a.resize(d.clientWidth, d.clientHeight)},400));b.left=d.style.left;b.top=d.style.top}catch(g){}}}function h(a){q.sendEvent(a.type,{message:"HTML5 player not found"})}var q=this,n=new g.eventdispatcher;a.extend(q,n);q.embed=function(){if(e.html5){m.setupPlugins(b,c,p);f.innerHTML="";var k=e.utils.extend({},c);delete k.volume;k=new e.html5.player(k);b.container=document.getElementById(b.id);b.setPlayer(k,"html5")}else k=new a.scriptloader(d.src),k.addEventListener(g.ERROR,h),k.addEventListener(g.COMPLETE,q.embed),k.load()}; q.supportsConfig=function(){if(e.vid.canPlayType)try{if("string"==a.typeOf(c.playlist))return!0;for(var b=c.playlist[0].sources,d=0;d<b.length;d++){var f;var g=b[d].file,h=b[d].type;if(null!==navigator.userAgent.match(/BlackBerry/i)||a.isAndroid()&&("m3u"==a.extension(g)||"m3u8"==a.extension(g))||a.isRtmp(g,h))f=!1;else{var p=l[h?h:a.extension(g)],m;if(!p||p.flash&&!p.html5)m=!1;else{var n=p.html5,q=e.vid;if(n)try{m=q.canPlayType(n)?!0:!1}catch(A){m=!1}else m=!0}f=m}if(f)return!0}}catch(y){}return!1}}}(jwplayer), function(e){var a=e.embed,l=e.utils,g=/\.(js|swf)$/;e.embed=l.extend(function(f){function d(){r="Adobe SiteCatalyst Error: Could not find Media Module"}var c=l.repo(),m=l.extend({},e.defaults),b=l.extend({},m,f.config),p=f.config,h=b.plugins,q=b.analytics,n=c+"jwpsrv.js",k=c+"sharing.js",j=c+"related.js",u=c+"gapro.js",m=e.key?e.key:m.key,t=(new e.utils.key(m)).edition(),r,h=h?h:{};"ads"==t&&b.advertising&&(g.test(b.advertising.client)?h[b.advertising.client]=b.advertising:h[c+b.advertising.client+ ".js"]=b.advertising);delete p.advertising;p.key=m;b.analytics&&g.test(b.analytics.client)&&(n=b.analytics.client);delete p.analytics;q&&"ads"!==t&&delete q.enabled;if("free"==t||!q||!1!==q.enabled)h[n]=q?q:{};delete h.sharing;delete h.related;switch(t){case "ads":if(p.sitecatalyst)try{window.s&&window.s.hasOwnProperty("Media")?new e.embed.sitecatalyst(f):d()}catch(v){d()}case "premium":b.related&&(g.test(b.related.client)&&(j=b.related.client),h[j]=b.related),b.ga&&(g.test(b.ga.client)&&(u=b.ga.client), h[u]=b.ga);case "pro":b.sharing&&(g.test(b.sharing.client)&&(k=b.sharing.client),h[k]=b.sharing),b.skin&&(p.skin=b.skin.replace(/^(beelden|bekle|five|glow|modieus|roundster|stormtrooper|vapor)$/i,l.repo()+"skins/$1.xml"))}p.plugins=h;f.config=p;f=new a(f);r&&f.errorScreen(r);return f},e.embed)}(jwplayer),function(e){var a=jwplayer.utils;e.sitecatalyst=function(e){function g(c){b.debug&&a.log(c)}function f(a){a=a.split("/");a=a[a.length-1];a=a.split("?");return a[0]}function d(){if(!k){k=!0;var a= m.getPosition();g("stop: "+h+" : "+a);s.Media.stop(h,a)}}function c(){j||(d(),j=!0,g("close: "+h),s.Media.close(h),u=!0,n=0)}var m=e,b=a.extend({},m.config.sitecatalyst),p={onPlay:function(){if(!u){var a=m.getPosition();k=!1;g("play: "+h+" : "+a);s.Media.play(h,a)}},onPause:d,onBuffer:d,onIdle:c,onPlaylistItem:function(d){try{u=!0;c();n=0;var g;if(b.mediaName)g=b.mediaName;else{var e=m.getPlaylistItem(d.index);g=e.title?e.title:e.file?f(e.file):e.sources&&e.sources.length?f(e.sources[0].file):""}h= g;q=b.playerName?b.playerName:m.id}catch(k){a.log(k)}},onTime:function(){if(u){var a=m.getDuration();if(-1==a)return;j=k=u=!1;g("open: "+h+" : "+a+" : "+q);s.Media.open(h,a,q);g("play: "+h+" : 0");s.Media.play(h,0)}a=m.getPosition();if(3<=Math.abs(a-n)){var b=n;g("seek: "+b+" to "+a);g("stop: "+h+" : "+b);s.Media.stop(h,b);g("play: "+h+" : "+a);s.Media.play(h,a)}n=a},onComplete:c},h,q,n,k=!0,j=!0,u;a.foreach(p,function(a){m[a](p[a])})}}(jwplayer.embed),function(e,a){var l=[],g=e.utils,f=e.events, d=f.state,c=document,m=e.api=function(b){function l(a,b){return function(c){return b(a,c)}}function h(a,b){t[a]||(t[a]=[],n(f.JWPLAYER_PLAYER_STATE,function(b){var c=b.newstate;b=b.oldstate;if(c==a){var d=t[c];if(d)for(var g=0;g<d.length;g++){var f=d[g];"function"==typeof f&&f.call(this,{oldstate:b,newstate:c})}}}));t[a].push(b);return j}function q(a,b){try{a.jwAddEventListener(b,'function(dat) { jwplayer("'+j.id+'").dispatchEvent("'+b+'", dat); }')}catch(c){g.log("Could not add internal listener")}} function n(a,b){u[a]||(u[a]=[],r&&v&&q(r,a));u[a].push(b);return j}function k(){if(v){if(r){var a=Array.prototype.slice.call(arguments,0),b=a.shift();if("function"===typeof r[b]){switch(a.length){case 6:return r[b](a[0],a[1],a[2],a[3],a[4],a[5]);case 5:return r[b](a[0],a[1],a[2],a[3],a[4]);case 4:return r[b](a[0],a[1],a[2],a[3]);case 3:return r[b](a[0],a[1],a[2]);case 2:return r[b](a[0],a[1]);case 1:return r[b](a[0])}return r[b]()}}return null}w.push(arguments)}var j=this,u={},t={},r,v=!1,w=[],x, z={},A={};j.container=b;j.id=b.id;j.getBuffer=function(){return k("jwGetBuffer")};j.getContainer=function(){return j.container};j.addButton=function(a,b,c,d){try{A[d]=c,k("jwDockAddButton",a,b,"jwplayer('"+j.id+"').callback('"+d+"')",d)}catch(f){g.log("Could not add dock button"+f.message)}};j.removeButton=function(a){k("jwDockRemoveButton",a)};j.callback=function(a){if(A[a])A[a]()};j.forceState=function(a){k("jwForceState",a);return j};j.releaseState=function(){return k("jwReleaseState")};j.getDuration= function(){return k("jwGetDuration")};j.getFullscreen=function(){return k("jwGetFullscreen")};j.getHeight=function(){return k("jwGetHeight")};j.getLockState=function(){return k("jwGetLockState")};j.getMeta=function(){return j.getItemMeta()};j.getMute=function(){return k("jwGetMute")};j.getPlaylist=function(){var a=k("jwGetPlaylist");"flash"==j.renderingMode&&g.deepReplaceKeyName(a,["__dot__","__spc__","__dsh__","__default__"],["."," ","-","default"]);return a};j.getPlaylistItem=function(a){g.exists(a)|| (a=j.getPlaylistIndex());return j.getPlaylist()[a]};j.getPlaylistIndex=function(){return k("jwGetPlaylistIndex")};j.getPosition=function(){return k("jwGetPosition")};j.getRenderingMode=function(){return j.renderingMode};j.getState=function(){return k("jwGetState")};j.getVolume=function(){return k("jwGetVolume")};j.getWidth=function(){return k("jwGetWidth")};j.setFullscreen=function(a){g.exists(a)?k("jwSetFullscreen",a):k("jwSetFullscreen",!k("jwGetFullscreen"));return j};j.setMute=function(a){g.exists(a)? k("jwSetMute",a):k("jwSetMute",!k("jwGetMute"));return j};j.lock=function(){return j};j.unlock=function(){return j};j.load=function(a){k("jwLoad",a);return j};j.playlistItem=function(a){k("jwPlaylistItem",parseInt(a,10));return j};j.playlistPrev=function(){k("jwPlaylistPrev");return j};j.playlistNext=function(){k("jwPlaylistNext");return j};j.resize=function(a,b){if("flash"!==j.renderingMode)k("jwResize",a,b);else{var d=c.getElementById(j.id+"_wrapper"),f=c.getElementById(j.id+"_aspect");f&&(f.style.display= "none");d&&(d.style.display="block",d.style.width=g.styleDimension(a),d.style.height=g.styleDimension(b))}return j};j.play=function(b){b===a?(b=j.getState(),b==d.PLAYING||b==d.BUFFERING?k("jwPause"):k("jwPlay")):k("jwPlay",b);return j};j.pause=function(b){b===a?(b=j.getState(),b==d.PLAYING||b==d.BUFFERING?k("jwPause"):k("jwPlay")):k("jwPause",b);return j};j.stop=function(){k("jwStop");return j};j.seek=function(a){k("jwSeek",a);return j};j.setVolume=function(a){k("jwSetVolume",a);return j};j.createInstream= function(){return new m.instream(this,r)};j.setInstream=function(a){return x=a};j.loadInstream=function(a,b){x=j.setInstream(j.createInstream()).init(b);x.loadItem(a);return x};j.getQualityLevels=function(){return k("jwGetQualityLevels")};j.getCurrentQuality=function(){return k("jwGetCurrentQuality")};j.setCurrentQuality=function(a){k("jwSetCurrentQuality",a)};j.getCaptionsList=function(){return k("jwGetCaptionsList")};j.getCurrentCaptions=function(){return k("jwGetCurrentCaptions")};j.setCurrentCaptions= function(a){k("jwSetCurrentCaptions",a)};j.getControls=function(){return k("jwGetControls")};j.getSafeRegion=function(){return k("jwGetSafeRegion")};j.setControls=function(a){k("jwSetControls",a)};j.destroyPlayer=function(){k("jwPlayerDestroy")};j.playAd=function(a){var b=e(j.id).plugins;b.vast&&b.vast.jwPlayAd(a)};j.pauseAd=function(){var a=e(j.id).plugins;a.vast?a.vast.jwPauseAd():k("jwPauseAd")};var y={onBufferChange:f.JWPLAYER_MEDIA_BUFFER,onBufferFull:f.JWPLAYER_MEDIA_BUFFER_FULL,onError:f.JWPLAYER_ERROR, onSetupError:f.JWPLAYER_SETUP_ERROR,onFullscreen:f.JWPLAYER_FULLSCREEN,onMeta:f.JWPLAYER_MEDIA_META,onMute:f.JWPLAYER_MEDIA_MUTE,onPlaylist:f.JWPLAYER_PLAYLIST_LOADED,onPlaylistItem:f.JWPLAYER_PLAYLIST_ITEM,onPlaylistComplete:f.JWPLAYER_PLAYLIST_COMPLETE,onReady:f.API_READY,onResize:f.JWPLAYER_RESIZE,onComplete:f.JWPLAYER_MEDIA_COMPLETE,onSeek:f.JWPLAYER_MEDIA_SEEK,onTime:f.JWPLAYER_MEDIA_TIME,onVolume:f.JWPLAYER_MEDIA_VOLUME,onBeforePlay:f.JWPLAYER_MEDIA_BEFOREPLAY,onBeforeComplete:f.JWPLAYER_MEDIA_BEFORECOMPLETE, onDisplayClick:f.JWPLAYER_DISPLAY_CLICK,onControls:f.JWPLAYER_CONTROLS,onQualityLevels:f.JWPLAYER_MEDIA_LEVELS,onQualityChange:f.JWPLAYER_MEDIA_LEVEL_CHANGED,onCaptionsList:f.JWPLAYER_CAPTIONS_LIST,onCaptionsChange:f.JWPLAYER_CAPTIONS_CHANGED,onAdError:f.JWPLAYER_AD_ERROR,onAdClick:f.JWPLAYER_AD_CLICK,onAdImpression:f.JWPLAYER_AD_IMPRESSION,onAdTime:f.JWPLAYER_AD_TIME,onAdComplete:f.JWPLAYER_AD_COMPLETE,onAdCompanions:f.JWPLAYER_AD_COMPANIONS,onAdSkipped:f.JWPLAYER_AD_SKIPPED};g.foreach(y,function(a){j[a]= l(y[a],n)});var B={onBuffer:d.BUFFERING,onPause:d.PAUSED,onPlay:d.PLAYING,onIdle:d.IDLE};g.foreach(B,function(a){j[a]=l(B[a],h)});j.remove=function(){if(!v)throw"Cannot call remove() before player is ready";w=[];m.destroyPlayer(this.id)};j.setup=function(a){if(e.embed){var b=c.getElementById(j.id);b&&(a.fallbackDiv=b);b=j;w=[];m.destroyPlayer(b.id);b=e(j.id);b.config=a;(new e.embed(b)).embed();return b}return j};j.registerPlugin=function(a,b,c,d){e.plugins.registerPlugin(a,b,c,d)};j.setPlayer=function(a, b){r=a;j.renderingMode=b};j.detachMedia=function(){if("html5"==j.renderingMode)return k("jwDetachMedia")};j.attachMedia=function(a){if("html5"==j.renderingMode)return k("jwAttachMedia",a)};j.removeEventListener=function(a,b){var c=u[a];if(c)for(var d=c.length;d--;)c[d]===b&&c.splice(d,1)};j.dispatchEvent=function(a,b){var c=u[a];if(c)for(var c=c.slice(0),d=g.translateEventResponse(a,b),e=0;e<c.length;e++){var k=c[e];if("function"===typeof k)try{a===f.JWPLAYER_PLAYLIST_LOADED&&g.deepReplaceKeyName(d.playlist, ["__dot__","__spc__","__dsh__","__default__"],["."," ","-","default"]),k.call(this,d)}catch(h){g.log("There was an error calling back an event handler")}}};j.dispatchInstreamEvent=function(a){x&&x.dispatchEvent(a,arguments)};j.callInternal=k;j.playerReady=function(a){v=!0;r||j.setPlayer(c.getElementById(a.id));j.container=c.getElementById(j.id);g.foreach(u,function(a){q(r,a)});n(f.JWPLAYER_PLAYLIST_ITEM,function(){z={}});n(f.JWPLAYER_MEDIA_META,function(a){g.extend(z,a.metadata)});for(j.dispatchEvent(f.API_READY);0< w.length;)k.apply(this,w.shift())};j.getItemMeta=function(){return z};j.isBeforePlay=function(){return k("jwIsBeforePlay")};j.isBeforeComplete=function(){return k("jwIsBeforeComplete")};return j};m.selectPlayer=function(a){var d;g.exists(a)||(a=0);a.nodeType?d=a:"string"==typeof a&&(d=c.getElementById(a));return d?(a=m.playerById(d.id))?a:m.addPlayer(new m(d)):"number"==typeof a?l[a]:null};m.playerById=function(a){for(var c=0;c<l.length;c++)if(l[c].id==a)return l[c];return null};m.addPlayer=function(a){for(var c= 0;c<l.length;c++)if(l[c]==a)return a;l.push(a);return a};m.destroyPlayer=function(a){for(var d=-1,f,e=0;e<l.length;e++)l[e].id==a&&(d=e,f=l[e]);0<=d&&(a=f.id,e=c.getElementById(a+("flash"==f.renderingMode?"_wrapper":"")),g.clearCss&&g.clearCss("#"+a),e&&("html5"==f.renderingMode&&f.destroyPlayer(),f=c.createElement("div"),f.id=a,e.parentNode.replaceChild(f,e)),l.splice(d,1));return null};e.playerReady=function(a){var c=e.api.playerById(a.id);c?c.playerReady(a):e.api.selectPlayer(a.id).playerReady(a)}}(window.jwplayer), function(e){var a=e.events,l=e.utils,g=a.state;e.api.instream=function(f,d){function c(a,b){h[a]||(h[a]=[],d.jwInstreamAddEventListener(a,'function(dat) { jwplayer("'+f.id+'").dispatchInstreamEvent("'+a+'", dat); }'));h[a].push(b);return this}function e(b,d){q[b]||(q[b]=[],c(a.JWPLAYER_PLAYER_STATE,function(a){var c=a.newstate,d=a.oldstate;if(c==b){var e=q[c];if(e)for(var f=0;f<e.length;f++){var g=e[f];"function"==typeof g&&g.call(this,{oldstate:d,newstate:c,type:a.type})}}}));q[b].push(d);return this} var b,p,h={},q={},n=this;n.type="instream";n.init=function(){f.callInternal("jwInitInstream");return n};n.loadItem=function(a,c){b=a;p=c||{};"array"==l.typeOf(a)?f.callInternal("jwLoadArrayInstream",b,p):f.callInternal("jwLoadItemInstream",b,p)};n.removeEvents=function(){h=q={}};n.removeEventListener=function(a,b){var c=h[a];if(c)for(var d=c.length;d--;)c[d]===b&&c.splice(d,1)};n.dispatchEvent=function(a,b){var c=h[a];if(c)for(var c=c.slice(0),d=l.translateEventResponse(a,b[1]),e=0;e<c.length;e++){var f= c[e];"function"==typeof f&&f.call(this,d)}};n.onError=function(b){return c(a.JWPLAYER_ERROR,b)};n.onMediaError=function(b){return c(a.JWPLAYER_MEDIA_ERROR,b)};n.onFullscreen=function(b){return c(a.JWPLAYER_FULLSCREEN,b)};n.onMeta=function(b){return c(a.JWPLAYER_MEDIA_META,b)};n.onMute=function(b){return c(a.JWPLAYER_MEDIA_MUTE,b)};n.onComplete=function(b){return c(a.JWPLAYER_MEDIA_COMPLETE,b)};n.onPlaylistComplete=function(b){return c(a.JWPLAYER_PLAYLIST_COMPLETE,b)};n.onPlaylistItem=function(b){return c(a.JWPLAYER_PLAYLIST_ITEM, b)};n.onTime=function(b){return c(a.JWPLAYER_MEDIA_TIME,b)};n.onBuffer=function(a){return e(g.BUFFERING,a)};n.onPause=function(a){return e(g.PAUSED,a)};n.onPlay=function(a){return e(g.PLAYING,a)};n.onIdle=function(a){return e(g.IDLE,a)};n.onClick=function(b){return c(a.JWPLAYER_INSTREAM_CLICK,b)};n.onInstreamDestroyed=function(b){return c(a.JWPLAYER_INSTREAM_DESTROYED,b)};n.onAdSkipped=function(b){return c(a.JWPLAYER_AD_SKIPPED,b)};n.play=function(a){d.jwInstreamPlay(a)};n.pause=function(a){d.jwInstreamPause(a)}; n.hide=function(){f.callInternal("jwInstreamHide")};n.destroy=function(){n.removeEvents();f.callInternal("jwInstreamDestroy")};n.setText=function(a){d.jwInstreamSetText(a?a:"")};n.getState=function(){return d.jwInstreamState()};n.setClick=function(a){d.jwInstreamClick&&d.jwInstreamClick(a)}}}(window.jwplayer),function(e){var a=e.api,l=a.selectPlayer;a.selectPlayer=function(a){return(a=l(a))?a:{registerPlugin:function(a,d,c){e.plugins.registerPlugin(a,d,c)}}}}(jwplayer)); /*! * ZeroClipboard * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface. * Copyright (c) 2014 Jon Rohan, James M. Greene * Licensed MIT * http://zeroclipboard.org/ * v2.1.6 */ (function(window, undefined) { "use strict"; /** * Store references to critically important global functions that may be * overridden on certain web pages. */ var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _round = _window.Math.round, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice, _unwrap = function() { var unwrapper = function(el) { return el; }; if (typeof _window.wrap === "function" && typeof _window.unwrap === "function") { try { var div = _document.createElement("div"); var unwrappedDiv = _window.unwrap(div); if (div.nodeType === 1 && unwrappedDiv && unwrappedDiv.nodeType === 1) { unwrapper = _window.unwrap; } } catch (e) {} } return unwrapper; }(); /** * Convert an `arguments` object into an Array. * * @returns The arguments as an Array * @private */ var _args = function(argumentsObj) { return _slice.call(argumentsObj, 0); }; /** * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`. * * @returns The target object, augmented * @private */ var _extend = function() { var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {}; for (i = 1, len = args.length; i < len; i++) { if ((arg = args[i]) != null) { for (prop in arg) { if (_hasOwn.call(arg, prop)) { src = target[prop]; copy = arg[prop]; if (target !== copy && copy !== undefined) { target[prop] = copy; } } } } } return target; }; /** * Return a deep copy of the source object or array. * * @returns Object or Array * @private */ var _deepCopy = function(source) { var copy, i, len, prop; if (typeof source !== "object" || source == null) { copy = source; } else if (typeof source.length === "number") { copy = []; for (i = 0, len = source.length; i < len; i++) { if (_hasOwn.call(source, i)) { copy[i] = _deepCopy(source[i]); } } } else { copy = {}; for (prop in source) { if (_hasOwn.call(source, prop)) { copy[prop] = _deepCopy(source[prop]); } } } return copy; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to * be kept. * * @returns A new filtered object. * @private */ var _pick = function(obj, keys) { var newObj = {}; for (var i = 0, len = keys.length; i < len; i++) { if (keys[i] in obj) { newObj[keys[i]] = obj[keys[i]]; } } return newObj; }; /** * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit. * The inverse of `_pick`. * * @returns A new filtered object. * @private */ var _omit = function(obj, keys) { var newObj = {}; for (var prop in obj) { if (keys.indexOf(prop) === -1) { newObj[prop] = obj[prop]; } } return newObj; }; /** * Remove all owned, enumerable properties from an object. * * @returns The original object without its owned, enumerable properties. * @private */ var _deleteOwnProperties = function(obj) { if (obj) { for (var prop in obj) { if (_hasOwn.call(obj, prop)) { delete obj[prop]; } } } return obj; }; /** * Determine if an element is contained within another element. * * @returns Boolean * @private */ var _containedBy = function(el, ancestorEl) { if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) { do { if (el === ancestorEl) { return true; } el = el.parentNode; } while (el); } return false; }; /** * Get the URL path's parent directory. * * @returns String or `undefined` * @private */ var _getDirPathOfUrl = function(url) { var dir; if (typeof url === "string" && url) { dir = url.split("#")[0].split("?")[0]; dir = url.slice(0, url.lastIndexOf("/") + 1); } return dir; }; /** * Get the current script's URL by throwing an `Error` and analyzing it. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrlFromErrorStack = function(stack) { var url, matches; if (typeof stack === "string" && stack) { matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (matches && matches[1]) { url = matches[1]; } else { matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/); if (matches && matches[1]) { url = matches[1]; } } } return url; }; /** * Get the current script's URL by throwing an `Error` and analyzing it. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrlFromError = function() { var url, err; try { throw new _Error(); } catch (e) { err = e; } if (err) { url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack); } return url; }; /** * Get the current script's URL. * * @returns String or `undefined` * @private */ var _getCurrentScriptUrl = function() { var jsPath, scripts, i; if (_document.currentScript && (jsPath = _document.currentScript.src)) { return jsPath; } scripts = _document.getElementsByTagName("script"); if (scripts.length === 1) { return scripts[0].src || undefined; } if ("readyState" in scripts[0]) { for (i = scripts.length; i--; ) { if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) { return jsPath; } } } if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) { return jsPath; } if (jsPath = _getCurrentScriptUrlFromError()) { return jsPath; } return undefined; }; /** * Get the unanimous parent directory of ALL script tags. * If any script tags are either (a) inline or (b) from differing parent * directories, this method must return `undefined`. * * @returns String or `undefined` * @private */ var _getUnanimousScriptParentDir = function() { var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script"); for (i = scripts.length; i--; ) { if (!(jsPath = scripts[i].src)) { jsDir = null; break; } jsPath = _getDirPathOfUrl(jsPath); if (jsDir == null) { jsDir = jsPath; } else if (jsDir !== jsPath) { jsDir = null; break; } } return jsDir || undefined; }; /** * Get the presumed location of the "ZeroClipboard.swf" file, based on the location * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.). * * @returns String * @private */ var _getDefaultSwfPath = function() { var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || ""; return jsDir + "ZeroClipboard.swf"; }; /** * Keep track of the state of the Flash object. * @private */ var _flashState = { bridge: null, version: "0.0.0", pluginType: "unknown", disabled: null, outdated: null, unavailable: null, deactivated: null, overdue: null, ready: null }; /** * The minimum Flash Player version required to use ZeroClipboard completely. * @readonly * @private */ var _minimumFlashVersion = "11.0.0"; /** * Keep track of all event listener registrations. * @private */ var _handlers = {}; /** * Keep track of the currently activated element. * @private */ var _currentElement; /** * Keep track of the element that was activated when a `copy` process started. * @private */ var _copyTarget; /** * Keep track of data for the pending clipboard transaction. * @private */ var _clipData = {}; /** * Keep track of data formats for the pending clipboard transaction. * @private */ var _clipDataFormatMap = null; /** * The `message` store for events * @private */ var _eventMessages = { ready: "Flash communication is established", error: { "flash-disabled": "Flash is disabled or not installed", "flash-outdated": "Flash is too outdated to support ZeroClipboard", "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript", "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate", "flash-overdue": "Flash communication was established but NOT within the acceptable time limit" } }; /** * ZeroClipboard configuration defaults for the Core module. * @private */ var _globalConfig = { swfPath: _getDefaultSwfPath(), trustedDomains: window.location.host ? [ window.location.host ] : [], cacheBust: true, forceEnhancedClipboard: false, flashLoadTimeout: 3e4, autoActivate: true, bubbleEvents: true, containerId: "global-zeroclipboard-html-bridge", containerClass: "global-zeroclipboard-container", swfObjectId: "global-zeroclipboard-flash-bridge", hoverClass: "zeroclipboard-is-hover", activeClass: "zeroclipboard-is-active", forceHandCursor: false, title: null, zIndex: 999999999 }; /** * The underlying implementation of `ZeroClipboard.config`. * @private */ var _config = function(options) { if (typeof options === "object" && options !== null) { for (var prop in options) { if (_hasOwn.call(options, prop)) { if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) { _globalConfig[prop] = options[prop]; } else if (_flashState.bridge == null) { if (prop === "containerId" || prop === "swfObjectId") { if (_isValidHtml4Id(options[prop])) { _globalConfig[prop] = options[prop]; } else { throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID"); } } else { _globalConfig[prop] = options[prop]; } } } } } if (typeof options === "string" && options) { if (_hasOwn.call(_globalConfig, options)) { return _globalConfig[options]; } return; } return _deepCopy(_globalConfig); }; /** * The underlying implementation of `ZeroClipboard.state`. * @private */ var _state = function() { return { browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]), flash: _omit(_flashState, [ "bridge" ]), zeroclipboard: { version: ZeroClipboard.version, config: ZeroClipboard.config() } }; }; /** * The underlying implementation of `ZeroClipboard.isFlashUnusable`. * @private */ var _isFlashUnusable = function() { return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated); }; /** * The underlying implementation of `ZeroClipboard.on`. * @private */ var _on = function(eventType, listener) { var i, len, events, added = {}; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!_handlers[eventType]) { _handlers[eventType] = []; } _handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { ZeroClipboard.emit({ type: "ready" }); } if (added.error) { var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]] === true) { ZeroClipboard.emit({ type: "error", name: "flash-" + errorTypes[i] }); break; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.off`. * @private */ var _off = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers; if (arguments.length === 0) { events = _keys(_handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { ZeroClipboard.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = _handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = perEventHandlers.indexOf(listener); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = perEventHandlers.indexOf(listener, foundIndex); } } else { perEventHandlers.length = 0; } } } } return ZeroClipboard; }; /** * The underlying implementation of `ZeroClipboard.handlers`. * @private */ var _listeners = function(eventType) { var copy; if (typeof eventType === "string" && eventType) { copy = _deepCopy(_handlers[eventType]) || null; } else { copy = _deepCopy(_handlers); } return copy; }; /** * The underlying implementation of `ZeroClipboard.emit`. * @private */ var _emit = function(event) { var eventCopy, returnVal, tmp; event = _createEvent(event); if (!event) { return; } if (_preprocessEvent(event)) { return; } if (event.type === "ready" && _flashState.overdue === true) { return ZeroClipboard.emit({ type: "error", name: "flash-overdue" }); } eventCopy = _extend({}, event); _dispatchCallbacks.call(this, eventCopy); if (event.type === "copy") { tmp = _mapClipDataToFlash(_clipData); returnVal = tmp.data; _clipDataFormatMap = tmp.formatMap; } return returnVal; }; /** * The underlying implementation of `ZeroClipboard.create`. * @private */ var _create = function() { if (typeof _flashState.ready !== "boolean") { _flashState.ready = false; } if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) { var maxWait = _globalConfig.flashLoadTimeout; if (typeof maxWait === "number" && maxWait >= 0) { _setTimeout(function() { if (typeof _flashState.deactivated !== "boolean") { _flashState.deactivated = true; } if (_flashState.deactivated === true) { ZeroClipboard.emit({ type: "error", name: "flash-deactivated" }); } }, maxWait); } _flashState.overdue = false; _embedSwf(); } }; /** * The underlying implementation of `ZeroClipboard.destroy`. * @private */ var _destroy = function() { ZeroClipboard.clearData(); ZeroClipboard.blur(); ZeroClipboard.emit("destroy"); _unembedSwf(); ZeroClipboard.off(); }; /** * The underlying implementation of `ZeroClipboard.setData`. * @private */ var _setData = function(format, data) { var dataObj; if (typeof format === "object" && format && typeof data === "undefined") { dataObj = format; ZeroClipboard.clearData(); } else if (typeof format === "string" && format) { dataObj = {}; dataObj[format] = data; } else { return; } for (var dataFormat in dataObj) { if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) { _clipData[dataFormat] = dataObj[dataFormat]; } } }; /** * The underlying implementation of `ZeroClipboard.clearData`. * @private */ var _clearData = function(format) { if (typeof format === "undefined") { _deleteOwnProperties(_clipData); _clipDataFormatMap = null; } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { delete _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.getData`. * @private */ var _getData = function(format) { if (typeof format === "undefined") { return _deepCopy(_clipData); } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) { return _clipData[format]; } }; /** * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`. * @private */ var _focus = function(element) { if (!(element && element.nodeType === 1)) { return; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.activeClass); if (_currentElement !== element) { _removeClass(_currentElement, _globalConfig.hoverClass); } } _currentElement = element; _addClass(element, _globalConfig.hoverClass); var newTitle = element.getAttribute("title") || _globalConfig.title; if (typeof newTitle === "string" && newTitle) { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.setAttribute("title", newTitle); } } var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; _setHandCursor(useHandCursor); _reposition(); }; /** * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`. * @private */ var _blur = function() { var htmlBridge = _getHtmlBridge(_flashState.bridge); if (htmlBridge) { htmlBridge.removeAttribute("title"); htmlBridge.style.left = "0px"; htmlBridge.style.top = "-9999px"; htmlBridge.style.width = "1px"; htmlBridge.style.top = "1px"; } if (_currentElement) { _removeClass(_currentElement, _globalConfig.hoverClass); _removeClass(_currentElement, _globalConfig.activeClass); _currentElement = null; } }; /** * The underlying implementation of `ZeroClipboard.activeElement`. * @private */ var _activeElement = function() { return _currentElement || null; }; /** * Check if a value is a valid HTML4 `ID` or `Name` token. * @private */ var _isValidHtml4Id = function(id) { return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id); }; /** * Create or update an `event` object, based on the `eventType`. * @private */ var _createEvent = function(event) { var eventType; if (typeof event === "string" && event) { eventType = event; event = {}; } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) { eventType = event.type; } if (!eventType) { return; } if (!event.target && /^(copy|aftercopy|_click)$/.test(eventType.toLowerCase())) { event.target = _copyTarget; } _extend(event, { type: eventType.toLowerCase(), target: event.target || _currentElement || null, relatedTarget: event.relatedTarget || null, currentTarget: _flashState && _flashState.bridge || null, timeStamp: event.timeStamp || _now() || null }); var msg = _eventMessages[event.type]; if (event.type === "error" && event.name && msg) { msg = msg[event.name]; } if (msg) { event.message = msg; } if (event.type === "ready") { _extend(event, { target: null, version: _flashState.version }); } if (event.type === "error") { if (/^flash-(disabled|outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { target: null, minimumVersion: _minimumFlashVersion }); } if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) { _extend(event, { version: _flashState.version }); } } if (event.type === "copy") { event.clipboardData = { setData: ZeroClipboard.setData, clearData: ZeroClipboard.clearData }; } if (event.type === "aftercopy") { event = _mapClipResultsFromFlash(event, _clipDataFormatMap); } if (event.target && !event.relatedTarget) { event.relatedTarget = _getRelatedTarget(event.target); } event = _addMouseData(event); return event; }; /** * Get a relatedTarget from the target's `data-clipboard-target` attribute * @private */ var _getRelatedTarget = function(targetEl) { var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target"); return relatedTargetId ? _document.getElementById(relatedTargetId) : null; }; /** * Add element and position data to `MouseEvent` instances * @private */ var _addMouseData = function(event) { if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { var srcElement = event.target; var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined; var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined; var pos = _getDOMObjectPosition(srcElement); var screenLeft = _window.screenLeft || _window.screenX || 0; var screenTop = _window.screenTop || _window.screenY || 0; var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft; var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop; var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0); var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0); var clientX = pageX - scrollLeft; var clientY = pageY - scrollTop; var screenX = screenLeft + clientX; var screenY = screenTop + clientY; var moveX = typeof event.movementX === "number" ? event.movementX : 0; var moveY = typeof event.movementY === "number" ? event.movementY : 0; delete event._stageX; delete event._stageY; _extend(event, { srcElement: srcElement, fromElement: fromElement, toElement: toElement, screenX: screenX, screenY: screenY, pageX: pageX, pageY: pageY, clientX: clientX, clientY: clientY, x: clientX, y: clientY, movementX: moveX, movementY: moveY, offsetX: 0, offsetY: 0, layerX: 0, layerY: 0 }); } return event; }; /** * Determine if an event's registered handlers should be execute synchronously or asynchronously. * * @returns {boolean} * @private */ var _shouldPerformAsync = function(event) { var eventType = event && typeof event.type === "string" && event.type || ""; return !/^(?:(?:before)?copy|destroy)$/.test(eventType); }; /** * Control if a callback should be executed asynchronously or not. * * @returns `undefined` * @private */ var _dispatchCallback = function(func, context, args, async) { if (async) { _setTimeout(function() { func.apply(context, args); }, 0); } else { func.apply(context, args); } }; /** * Handle the actual dispatching of events to client instances. * * @returns `undefined` * @private */ var _dispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _handlers["*"] || []; var specificTypeHandlers = _handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Preprocess any special behaviors, reactions, or state changes after receiving this event. * Executes only once per event emitted, NOT once per client. * @private */ var _preprocessEvent = function(event) { var element = event.target || _currentElement || null; var sourceIsSwf = event._source === "swf"; delete event._source; var flashErrorNames = [ "flash-disabled", "flash-outdated", "flash-unavailable", "flash-deactivated", "flash-overdue" ]; switch (event.type) { case "error": if (flashErrorNames.indexOf(event.name) !== -1) { _extend(_flashState, { disabled: event.name === "flash-disabled", outdated: event.name === "flash-outdated", unavailable: event.name === "flash-unavailable", deactivated: event.name === "flash-deactivated", overdue: event.name === "flash-overdue", ready: false }); } break; case "ready": var wasDeactivated = _flashState.deactivated === true; _extend(_flashState, { disabled: false, outdated: false, unavailable: false, deactivated: false, overdue: wasDeactivated, ready: !wasDeactivated }); break; case "beforecopy": _copyTarget = element; break; case "copy": var textContent, htmlContent, targetEl = event.relatedTarget; if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); if (htmlContent !== textContent) { event.clipboardData.setData("text/html", htmlContent); } } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) { event.clipboardData.clearData(); event.clipboardData.setData("text/plain", textContent); } break; case "aftercopy": ZeroClipboard.clearData(); if (element && element !== _safeActiveElement() && element.focus) { element.focus(); } break; case "_mouseover": ZeroClipboard.focus(element); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) { _fireMouseEvent(_extend({}, event, { type: "mouseenter", bubbles: false, cancelable: false })); } _fireMouseEvent(_extend({}, event, { type: "mouseover" })); } break; case "_mouseout": ZeroClipboard.blur(); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) { _fireMouseEvent(_extend({}, event, { type: "mouseleave", bubbles: false, cancelable: false })); } _fireMouseEvent(_extend({}, event, { type: "mouseout" })); } break; case "_mousedown": _addClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mouseup": _removeClass(element, _globalConfig.activeClass); if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_click": _copyTarget = null; if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; case "_mousemove": if (_globalConfig.bubbleEvents === true && sourceIsSwf) { _fireMouseEvent(_extend({}, event, { type: event.type.slice(1) })); } break; } if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) { return true; } }; /** * Dispatch a synthetic MouseEvent. * * @returns `undefined` * @private */ var _fireMouseEvent = function(event) { if (!(event && typeof event.type === "string" && event)) { return; } var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = { view: doc.defaultView || _window, canBubble: true, cancelable: true, detail: event.type === "click" ? 1 : 0, button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1 }, args = _extend(defaults, event); if (!target) { return; } if (doc.createEvent && target.dispatchEvent) { args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ]; e = doc.createEvent("MouseEvents"); if (e.initMouseEvent) { e.initMouseEvent.apply(e, args); e._source = "js"; target.dispatchEvent(e); } } }; /** * Create the HTML bridge element to embed the Flash object into. * @private */ var _createHtmlBridge = function() { var container = _document.createElement("div"); container.id = _globalConfig.containerId; container.className = _globalConfig.containerClass; container.style.position = "absolute"; container.style.left = "0px"; container.style.top = "-9999px"; container.style.width = "1px"; container.style.height = "1px"; container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex); return container; }; /** * Get the HTML element container that wraps the Flash bridge object/element. * @private */ var _getHtmlBridge = function(flashBridge) { var htmlBridge = flashBridge && flashBridge.parentNode; while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) { htmlBridge = htmlBridge.parentNode; } return htmlBridge || null; }; /** * Create the SWF object. * * @returns The SWF object reference. * @private */ var _embedSwf = function() { var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge); if (!flashBridge) { var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig); var allowNetworking = allowScriptAccess === "never" ? "none" : "all"; var flashvars = _vars(_globalConfig); var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig); container = _createHtmlBridge(); var divToBeReplaced = _document.createElement("div"); container.appendChild(divToBeReplaced); _document.body.appendChild(container); var tmpDiv = _document.createElement("div"); var oldIE = _flashState.pluginType === "activex"; tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>"; flashBridge = tmpDiv.firstChild; tmpDiv = null; _unwrap(flashBridge).ZeroClipboard = ZeroClipboard; container.replaceChild(flashBridge, divToBeReplaced); } if (!flashBridge) { flashBridge = _document[_globalConfig.swfObjectId]; if (flashBridge && (len = flashBridge.length)) { flashBridge = flashBridge[len - 1]; } if (!flashBridge && container) { flashBridge = container.firstChild; } } _flashState.bridge = flashBridge || null; return flashBridge; }; /** * Destroy the SWF object. * @private */ var _unembedSwf = function() { var flashBridge = _flashState.bridge; if (flashBridge) { var htmlBridge = _getHtmlBridge(flashBridge); if (htmlBridge) { if (_flashState.pluginType === "activex" && "readyState" in flashBridge) { flashBridge.style.display = "none"; (function removeSwfFromIE() { if (flashBridge.readyState === 4) { for (var prop in flashBridge) { if (typeof flashBridge[prop] === "function") { flashBridge[prop] = null; } } if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } else { _setTimeout(removeSwfFromIE, 10); } })(); } else { if (flashBridge.parentNode) { flashBridge.parentNode.removeChild(flashBridge); } if (htmlBridge.parentNode) { htmlBridge.parentNode.removeChild(htmlBridge); } } } _flashState.ready = null; _flashState.bridge = null; _flashState.deactivated = null; } }; /** * Map the data format names of the "clipData" to Flash-friendly names. * * @returns A new transformed object. * @private */ var _mapClipDataToFlash = function(clipData) { var newClipData = {}, formatMap = {}; if (!(typeof clipData === "object" && clipData)) { return; } for (var dataFormat in clipData) { if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) { switch (dataFormat.toLowerCase()) { case "text/plain": case "text": case "air:text": case "flash:text": newClipData.text = clipData[dataFormat]; formatMap.text = dataFormat; break; case "text/html": case "html": case "air:html": case "flash:html": newClipData.html = clipData[dataFormat]; formatMap.html = dataFormat; break; case "application/rtf": case "text/rtf": case "rtf": case "richtext": case "air:rtf": case "flash:rtf": newClipData.rtf = clipData[dataFormat]; formatMap.rtf = dataFormat; break; default: break; } } } return { data: newClipData, formatMap: formatMap }; }; /** * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping). * * @returns A new transformed object. * @private */ var _mapClipResultsFromFlash = function(clipResults, formatMap) { if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) { return clipResults; } var newResults = {}; for (var prop in clipResults) { if (_hasOwn.call(clipResults, prop)) { if (prop !== "success" && prop !== "data") { newResults[prop] = clipResults[prop]; continue; } newResults[prop] = {}; var tmpHash = clipResults[prop]; for (var dataFormat in tmpHash) { if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) { newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat]; } } } } return newResults; }; /** * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}" * query param string to return. Does NOT append that string to the original path. * This is useful because ExternalInterface often breaks when a Flash SWF is cached. * * @returns The `noCache` query param with necessary "?"/"&" prefix. * @private */ var _cacheBust = function(path, options) { var cacheBust = options == null || options && options.cacheBust === true; if (cacheBust) { return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now(); } else { return ""; } }; /** * Creates a query string for the FlashVars param. * Does NOT include the cache-busting query param. * * @returns FlashVars query string * @private */ var _vars = function(options) { var i, len, domain, domains, str = "", trustedOriginsExpanded = []; if (options.trustedDomains) { if (typeof options.trustedDomains === "string") { domains = [ options.trustedDomains ]; } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) { domains = options.trustedDomains; } } if (domains && domains.length) { for (i = 0, len = domains.length; i < len; i++) { if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") { domain = _extractDomain(domains[i]); if (!domain) { continue; } if (domain === "*") { trustedOriginsExpanded.length = 0; trustedOriginsExpanded.push(domain); break; } trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]); } } } if (trustedOriginsExpanded.length) { str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(",")); } if (options.forceEnhancedClipboard === true) { str += (str ? "&" : "") + "forceEnhancedClipboard=true"; } if (typeof options.swfObjectId === "string" && options.swfObjectId) { str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId); } return str; }; /** * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/"). * * @returns the domain * @private */ var _extractDomain = function(originOrUrl) { if (originOrUrl == null || originOrUrl === "") { return null; } originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, ""); if (originOrUrl === "") { return null; } var protocolIndex = originOrUrl.indexOf("//"); originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2); var pathIndex = originOrUrl.indexOf("/"); originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex); if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") { return null; } return originOrUrl || null; }; /** * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`. * * @returns The appropriate script access level. * @private */ var _determineScriptAccess = function() { var _extractAllDomains = function(origins) { var i, len, tmp, resultsArray = []; if (typeof origins === "string") { origins = [ origins ]; } if (!(typeof origins === "object" && origins && typeof origins.length === "number")) { return resultsArray; } for (i = 0, len = origins.length; i < len; i++) { if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) { if (tmp === "*") { resultsArray.length = 0; resultsArray.push("*"); break; } if (resultsArray.indexOf(tmp) === -1) { resultsArray.push(tmp); } } } return resultsArray; }; return function(currentDomain, configOptions) { var swfDomain = _extractDomain(configOptions.swfPath); if (swfDomain === null) { swfDomain = currentDomain; } var trustedDomains = _extractAllDomains(configOptions.trustedDomains); var len = trustedDomains.length; if (len > 0) { if (len === 1 && trustedDomains[0] === "*") { return "always"; } if (trustedDomains.indexOf(currentDomain) !== -1) { if (len === 1 && currentDomain === swfDomain) { return "sameDomain"; } return "always"; } } return "never"; }; }(); /** * Get the currently active/focused DOM element. * * @returns the currently active/focused element, or `null` * @private */ var _safeActiveElement = function() { try { return _document.activeElement; } catch (err) { return null; } }; /** * Add a class to an element, if it doesn't already have it. * * @returns The element, with its new class added. * @private */ var _addClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (!element.classList.contains(value)) { element.classList.add(value); } return element; } if (value && typeof value === "string") { var classNames = (value || "").split(/\s+/); if (element.nodeType === 1) { if (!element.className) { element.className = value; } else { var className = " " + element.className + " ", setClass = element.className; for (var c = 0, cl = classNames.length; c < cl; c++) { if (className.indexOf(" " + classNames[c] + " ") < 0) { setClass += " " + classNames[c]; } } element.className = setClass.replace(/^\s+|\s+$/g, ""); } } } return element; }; /** * Remove a class from an element, if it has it. * * @returns The element, with its class removed. * @private */ var _removeClass = function(element, value) { if (!element || element.nodeType !== 1) { return element; } if (element.classList) { if (element.classList.contains(value)) { element.classList.remove(value); } return element; } if (typeof value === "string" && value) { var classNames = value.split(/\s+/); if (element.nodeType === 1 && element.className) { var className = (" " + element.className + " ").replace(/[\n\t]/g, " "); for (var c = 0, cl = classNames.length; c < cl; c++) { className = className.replace(" " + classNames[c] + " ", " "); } element.className = className.replace(/^\s+|\s+$/g, ""); } } return element; }; /** * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`, * then we assume that it should be a hand ("pointer") cursor if the element * is an anchor element ("a" tag). * * @returns The computed style property. * @private */ var _getStyle = function(el, prop) { var value = _window.getComputedStyle(el, null).getPropertyValue(prop); if (prop === "cursor") { if (!value || value === "auto") { if (el.nodeName === "A") { return "pointer"; } } } return value; }; /** * Get the zoom factor of the browser. Always returns `1.0`, except at * non-default zoom levels in IE<8 and some older versions of WebKit. * * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`). * @private */ var _getZoomFactor = function() { var rect, physicalWidth, logicalWidth, zoomFactor = 1; if (typeof _document.body.getBoundingClientRect === "function") { rect = _document.body.getBoundingClientRect(); physicalWidth = rect.right - rect.left; logicalWidth = _document.body.offsetWidth; zoomFactor = _round(physicalWidth / logicalWidth * 100) / 100; } return zoomFactor; }; /** * Get the DOM positioning info of an element. * * @returns Object containing the element's position, width, and height. * @private */ var _getDOMObjectPosition = function(obj) { var info = { left: 0, top: 0, width: 0, height: 0 }; if (obj.getBoundingClientRect) { var rect = obj.getBoundingClientRect(); var pageXOffset, pageYOffset, zoomFactor; if ("pageXOffset" in _window && "pageYOffset" in _window) { pageXOffset = _window.pageXOffset; pageYOffset = _window.pageYOffset; } else { zoomFactor = _getZoomFactor(); pageXOffset = _round(_document.documentElement.scrollLeft / zoomFactor); pageYOffset = _round(_document.documentElement.scrollTop / zoomFactor); } var leftBorderWidth = _document.documentElement.clientLeft || 0; var topBorderWidth = _document.documentElement.clientTop || 0; info.left = rect.left + pageXOffset - leftBorderWidth; info.top = rect.top + pageYOffset - topBorderWidth; info.width = "width" in rect ? rect.width : rect.right - rect.left; info.height = "height" in rect ? rect.height : rect.bottom - rect.top; } return info; }; /** * Reposition the Flash object to cover the currently activated element. * * @returns `undefined` * @private */ var _reposition = function() { var htmlBridge; if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) { var pos = _getDOMObjectPosition(_currentElement); _extend(htmlBridge.style, { width: pos.width + "px", height: pos.height + "px", top: pos.top + "px", left: pos.left + "px", zIndex: "" + _getSafeZIndex(_globalConfig.zIndex) }); } }; /** * Sends a signal to the Flash object to display the hand cursor if `true`. * * @returns `undefined` * @private */ var _setHandCursor = function(enabled) { if (_flashState.ready === true) { if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") { _flashState.bridge.setHandCursor(enabled); } else { _flashState.ready = false; } } }; /** * Get a safe value for `zIndex` * * @returns an integer, or "auto" * @private */ var _getSafeZIndex = function(val) { if (/^(?:auto|inherit)$/.test(val)) { return val; } var zIndex; if (typeof val === "number" && !_isNaN(val)) { zIndex = val; } else if (typeof val === "string") { zIndex = _getSafeZIndex(_parseInt(val, 10)); } return typeof zIndex === "number" ? zIndex : "auto"; }; /** * Detect the Flash Player status, version, and plugin type. * * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code} * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript} * * @returns `undefined` * @private */ var _detectFlashSupport = function(ActiveXObject) { var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = ""; /** * Derived from Apple's suggested sniffer. * @param {String} desc e.g. "Shockwave Flash 7.0 r61" * @returns {String} "7.0.61" * @private */ function parseFlashVersion(desc) { var matches = desc.match(/[\d]+/g); matches.length = 3; return matches.join("."); } function isPepperFlash(flashPlayerFileName) { return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin"); } function inspectPlugin(plugin) { if (plugin) { hasFlash = true; if (plugin.version) { flashVersion = parseFlashVersion(plugin.version); } if (!flashVersion && plugin.description) { flashVersion = parseFlashVersion(plugin.description); } if (plugin.filename) { isPPAPI = isPepperFlash(plugin.filename); } } } if (_navigator.plugins && _navigator.plugins.length) { plugin = _navigator.plugins["Shockwave Flash"]; inspectPlugin(plugin); if (_navigator.plugins["Shockwave Flash 2.0"]) { hasFlash = true; flashVersion = "2.0.0.11"; } } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) { mimeType = _navigator.mimeTypes["application/x-shockwave-flash"]; plugin = mimeType && mimeType.enabledPlugin; inspectPlugin(plugin); } else if (typeof ActiveXObject !== "undefined") { isActiveX = true; try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e1) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); hasFlash = true; flashVersion = "6.0.21"; } catch (e2) { try { ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); hasFlash = true; flashVersion = parseFlashVersion(ax.GetVariable("$version")); } catch (e3) { isActiveX = false; } } } } _flashState.disabled = hasFlash !== true; _flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion); _flashState.version = flashVersion || "0.0.0"; _flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown"; }; /** * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later. */ _detectFlashSupport(_ActiveXObject); /** * A shell constructor for `ZeroClipboard` client instances. * * @constructor */ var ZeroClipboard = function() { if (!(this instanceof ZeroClipboard)) { return new ZeroClipboard(); } if (typeof ZeroClipboard._createClient === "function") { ZeroClipboard._createClient.apply(this, _args(arguments)); } }; /** * The ZeroClipboard library's version number. * * @static * @readonly * @property {string} */ _defineProperty(ZeroClipboard, "version", { value: "2.1.6", writable: false, configurable: true, enumerable: true }); /** * Update or get a copy of the ZeroClipboard global configuration. * Returns a copy of the current/updated configuration. * * @returns Object * @static */ ZeroClipboard.config = function() { return _config.apply(this, _args(arguments)); }; /** * Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard. * * @returns Object * @static */ ZeroClipboard.state = function() { return _state.apply(this, _args(arguments)); }; /** * Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc. * * @returns Boolean * @static */ ZeroClipboard.isFlashUnusable = function() { return _isFlashUnusable.apply(this, _args(arguments)); }; /** * Register an event listener. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.on = function() { return _on.apply(this, _args(arguments)); }; /** * Unregister an event listener. * If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`. * If no `eventType` is provided, it will unregister all listeners for every event type. * * @returns `ZeroClipboard` * @static */ ZeroClipboard.off = function() { return _off.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType`. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.handlers = function() { return _listeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. * @static */ ZeroClipboard.emit = function() { return _emit.apply(this, _args(arguments)); }; /** * Create and embed the Flash object. * * @returns The Flash object * @static */ ZeroClipboard.create = function() { return _create.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything, including the embedded Flash object. * * @returns `undefined` * @static */ ZeroClipboard.destroy = function() { return _destroy.apply(this, _args(arguments)); }; /** * Set the pending data for clipboard injection. * * @returns `undefined` * @static */ ZeroClipboard.setData = function() { return _setData.apply(this, _args(arguments)); }; /** * Clear the pending data for clipboard injection. * If no `format` is provided, all pending data formats will be cleared. * * @returns `undefined` * @static */ ZeroClipboard.clearData = function() { return _clearData.apply(this, _args(arguments)); }; /** * Get a copy of the pending data for clipboard injection. * If no `format` is provided, a copy of ALL pending data formats will be returned. * * @returns `String` or `Object` * @static */ ZeroClipboard.getData = function() { return _getData.apply(this, _args(arguments)); }; /** * Sets the current HTML object that the Flash object should overlay. This will put the global * Flash object on top of the current element; depending on the setup, this may also set the * pending clipboard text data as well as the Flash object's wrapping element's title attribute * based on the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.focus = ZeroClipboard.activate = function() { return _focus.apply(this, _args(arguments)); }; /** * Un-overlays the Flash object. This will put the global Flash object off-screen; depending on * the setup, this may also unset the Flash object's wrapping element's title attribute based on * the underlying HTML element and ZeroClipboard configuration. * * @returns `undefined` * @static */ ZeroClipboard.blur = ZeroClipboard.deactivate = function() { return _blur.apply(this, _args(arguments)); }; /** * Returns the currently focused/"activated" HTML element that the Flash object is wrapping. * * @returns `HTMLElement` or `null` * @static */ ZeroClipboard.activeElement = function() { return _activeElement.apply(this, _args(arguments)); }; /** * Keep track of the ZeroClipboard client instance counter. */ var _clientIdCounter = 0; /** * Keep track of the state of the client instances. * * Entry structure: * _clientMeta[client.id] = { * instance: client, * elements: [], * handlers: {} * }; */ var _clientMeta = {}; /** * Keep track of the ZeroClipboard clipped elements counter. */ var _elementIdCounter = 0; /** * Keep track of the state of the clipped element relationships to clients. * * Entry structure: * _elementMeta[element.zcClippingId] = [client1.id, client2.id]; */ var _elementMeta = {}; /** * Keep track of the state of the mouse event handlers for clipped elements. * * Entry structure: * _mouseHandlers[element.zcClippingId] = { * mouseover: function(event) {}, * mouseout: function(event) {}, * mouseenter: function(event) {}, * mouseleave: function(event) {}, * mousemove: function(event) {} * }; */ var _mouseHandlers = {}; /** * Extending the ZeroClipboard configuration defaults for the Client module. */ _extend(_globalConfig, { autoActivate: true }); /** * The real constructor for `ZeroClipboard` client instances. * @private */ var _clientConstructor = function(elements) { var client = this; client.id = "" + _clientIdCounter++; _clientMeta[client.id] = { instance: client, elements: [], handlers: {} }; if (elements) { client.clip(elements); } ZeroClipboard.on("*", function(event) { return client.emit(event); }); ZeroClipboard.on("destroy", function() { client.destroy(); }); ZeroClipboard.create(); }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.on`. * @private */ var _clientOn = function(eventType, listener) { var i, len, events, added = {}, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (typeof eventType === "string" && eventType) { events = eventType.toLowerCase().split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { this.on(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].replace(/^on/, ""); added[eventType] = true; if (!handlers[eventType]) { handlers[eventType] = []; } handlers[eventType].push(listener); } if (added.ready && _flashState.ready) { this.emit({ type: "ready", client: this }); } if (added.error) { var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ]; for (i = 0, len = errorTypes.length; i < len; i++) { if (_flashState[errorTypes[i]]) { this.emit({ type: "error", name: "flash-" + errorTypes[i], client: this }); break; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.off`. * @private */ var _clientOff = function(eventType, listener) { var i, len, foundIndex, events, perEventHandlers, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (arguments.length === 0) { events = _keys(handlers); } else if (typeof eventType === "string" && eventType) { events = eventType.split(/\s+/); } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") { for (i in eventType) { if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") { this.off(i, eventType[i]); } } } if (events && events.length) { for (i = 0, len = events.length; i < len; i++) { eventType = events[i].toLowerCase().replace(/^on/, ""); perEventHandlers = handlers[eventType]; if (perEventHandlers && perEventHandlers.length) { if (listener) { foundIndex = perEventHandlers.indexOf(listener); while (foundIndex !== -1) { perEventHandlers.splice(foundIndex, 1); foundIndex = perEventHandlers.indexOf(listener, foundIndex); } } else { perEventHandlers.length = 0; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.handlers`. * @private */ var _clientListeners = function(eventType) { var copy = null, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers; if (handlers) { if (typeof eventType === "string" && eventType) { copy = handlers[eventType] ? handlers[eventType].slice(0) : []; } else { copy = _deepCopy(handlers); } } return copy; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.emit`. * @private */ var _clientEmit = function(event) { if (_clientShouldEmit.call(this, event)) { if (typeof event === "object" && event && typeof event.type === "string" && event.type) { event = _extend({}, event); } var eventCopy = _extend({}, _createEvent(event), { client: this }); _clientDispatchCallbacks.call(this, eventCopy); } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.clip`. * @private */ var _clientClip = function(elements) { elements = _prepClip(elements); for (var i = 0; i < elements.length; i++) { if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) { if (!elements[i].zcClippingId) { elements[i].zcClippingId = "zcClippingId_" + _elementIdCounter++; _elementMeta[elements[i].zcClippingId] = [ this.id ]; if (_globalConfig.autoActivate === true) { _addMouseHandlers(elements[i]); } } else if (_elementMeta[elements[i].zcClippingId].indexOf(this.id) === -1) { _elementMeta[elements[i].zcClippingId].push(this.id); } var clippedElements = _clientMeta[this.id] && _clientMeta[this.id].elements; if (clippedElements.indexOf(elements[i]) === -1) { clippedElements.push(elements[i]); } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.unclip`. * @private */ var _clientUnclip = function(elements) { var meta = _clientMeta[this.id]; if (!meta) { return this; } var clippedElements = meta.elements; var arrayIndex; if (typeof elements === "undefined") { elements = clippedElements.slice(0); } else { elements = _prepClip(elements); } for (var i = elements.length; i--; ) { if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) { arrayIndex = 0; while ((arrayIndex = clippedElements.indexOf(elements[i], arrayIndex)) !== -1) { clippedElements.splice(arrayIndex, 1); } var clientIds = _elementMeta[elements[i].zcClippingId]; if (clientIds) { arrayIndex = 0; while ((arrayIndex = clientIds.indexOf(this.id, arrayIndex)) !== -1) { clientIds.splice(arrayIndex, 1); } if (clientIds.length === 0) { if (_globalConfig.autoActivate === true) { _removeMouseHandlers(elements[i]); } delete elements[i].zcClippingId; } } } } return this; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.elements`. * @private */ var _clientElements = function() { var meta = _clientMeta[this.id]; return meta && meta.elements ? meta.elements.slice(0) : []; }; /** * The underlying implementation of `ZeroClipboard.Client.prototype.destroy`. * @private */ var _clientDestroy = function() { this.unclip(); this.off(); delete _clientMeta[this.id]; }; /** * Inspect an Event to see if the Client (`this`) should honor it for emission. * @private */ var _clientShouldEmit = function(event) { if (!(event && event.type)) { return false; } if (event.client && event.client !== this) { return false; } var clippedEls = _clientMeta[this.id] && _clientMeta[this.id].elements; var hasClippedEls = !!clippedEls && clippedEls.length > 0; var goodTarget = !event.target || hasClippedEls && clippedEls.indexOf(event.target) !== -1; var goodRelTarget = event.relatedTarget && hasClippedEls && clippedEls.indexOf(event.relatedTarget) !== -1; var goodClient = event.client && event.client === this; if (!(goodTarget || goodRelTarget || goodClient)) { return false; } return true; }; /** * Handle the actual dispatching of events to a client instance. * * @returns `this` * @private */ var _clientDispatchCallbacks = function(event) { if (!(typeof event === "object" && event && event.type)) { return; } var async = _shouldPerformAsync(event); var wildcardTypeHandlers = _clientMeta[this.id] && _clientMeta[this.id].handlers["*"] || []; var specificTypeHandlers = _clientMeta[this.id] && _clientMeta[this.id].handlers[event.type] || []; var handlers = wildcardTypeHandlers.concat(specificTypeHandlers); if (handlers && handlers.length) { var i, len, func, context, eventCopy, originalContext = this; for (i = 0, len = handlers.length; i < len; i++) { func = handlers[i]; context = originalContext; if (typeof func === "string" && typeof _window[func] === "function") { func = _window[func]; } if (typeof func === "object" && func && typeof func.handleEvent === "function") { context = func; func = func.handleEvent; } if (typeof func === "function") { eventCopy = _extend({}, event); _dispatchCallback(func, context, [ eventCopy ], async); } } } return this; }; /** * Prepares the elements for clipping/unclipping. * * @returns An Array of elements. * @private */ var _prepClip = function(elements) { if (typeof elements === "string") { elements = []; } return typeof elements.length !== "number" ? [ elements ] : elements; }; /** * Add a `mouseover` handler function for a clipped element. * * @returns `undefined` * @private */ var _addMouseHandlers = function(element) { if (!(element && element.nodeType === 1)) { return; } var _suppressMouseEvents = function(event) { if (!(event || (event = _window.event))) { return; } if (event._source !== "js") { event.stopImmediatePropagation(); event.preventDefault(); } delete event._source; }; var _elementMouseOver = function(event) { if (!(event || (event = _window.event))) { return; } _suppressMouseEvents(event); ZeroClipboard.focus(element); }; element.addEventListener("mouseover", _elementMouseOver, false); element.addEventListener("mouseout", _suppressMouseEvents, false); element.addEventListener("mouseenter", _suppressMouseEvents, false); element.addEventListener("mouseleave", _suppressMouseEvents, false); element.addEventListener("mousemove", _suppressMouseEvents, false); _mouseHandlers[element.zcClippingId] = { mouseover: _elementMouseOver, mouseout: _suppressMouseEvents, mouseenter: _suppressMouseEvents, mouseleave: _suppressMouseEvents, mousemove: _suppressMouseEvents }; }; /** * Remove a `mouseover` handler function for a clipped element. * * @returns `undefined` * @private */ var _removeMouseHandlers = function(element) { if (!(element && element.nodeType === 1)) { return; } var mouseHandlers = _mouseHandlers[element.zcClippingId]; if (!(typeof mouseHandlers === "object" && mouseHandlers)) { return; } var key, val, mouseEvents = [ "move", "leave", "enter", "out", "over" ]; for (var i = 0, len = mouseEvents.length; i < len; i++) { key = "mouse" + mouseEvents[i]; val = mouseHandlers[key]; if (typeof val === "function") { element.removeEventListener(key, val, false); } } delete _mouseHandlers[element.zcClippingId]; }; /** * Creates a new ZeroClipboard client instance. * Optionally, auto-`clip` an element or collection of elements. * * @constructor */ ZeroClipboard._createClient = function() { _clientConstructor.apply(this, _args(arguments)); }; /** * Register an event listener to the client. * * @returns `this` */ ZeroClipboard.prototype.on = function() { return _clientOn.apply(this, _args(arguments)); }; /** * Unregister an event handler from the client. * If no `listener` function/object is provided, it will unregister all handlers for the provided `eventType`. * If no `eventType` is provided, it will unregister all handlers for every event type. * * @returns `this` */ ZeroClipboard.prototype.off = function() { return _clientOff.apply(this, _args(arguments)); }; /** * Retrieve event listeners for an `eventType` from the client. * If no `eventType` is provided, it will retrieve all listeners for every event type. * * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null` */ ZeroClipboard.prototype.handlers = function() { return _clientListeners.apply(this, _args(arguments)); }; /** * Event emission receiver from the Flash object for this client's registered JavaScript event listeners. * * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`. */ ZeroClipboard.prototype.emit = function() { return _clientEmit.apply(this, _args(arguments)); }; /** * Register clipboard actions for new element(s) to the client. * * @returns `this` */ ZeroClipboard.prototype.clip = function() { return _clientClip.apply(this, _args(arguments)); }; /** * Unregister the clipboard actions of previously registered element(s) on the page. * If no elements are provided, ALL registered elements will be unregistered. * * @returns `this` */ ZeroClipboard.prototype.unclip = function() { return _clientUnclip.apply(this, _args(arguments)); }; /** * Get all of the elements to which this client is clipped. * * @returns array of clipped elements */ ZeroClipboard.prototype.elements = function() { return _clientElements.apply(this, _args(arguments)); }; /** * Self-destruct and clean up everything for a single client. * This will NOT destroy the embedded Flash object. * * @returns `undefined` */ ZeroClipboard.prototype.destroy = function() { return _clientDestroy.apply(this, _args(arguments)); }; /** * Stores the pending plain text to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setText = function(text) { ZeroClipboard.setData("text/plain", text); return this; }; /** * Stores the pending HTML text to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setHtml = function(html) { ZeroClipboard.setData("text/html", html); return this; }; /** * Stores the pending rich text (RTF) to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setRichText = function(richText) { ZeroClipboard.setData("application/rtf", richText); return this; }; /** * Stores the pending data to inject into the clipboard. * * @returns `this` */ ZeroClipboard.prototype.setData = function() { ZeroClipboard.setData.apply(this, _args(arguments)); return this; }; /** * Clears the pending data to inject into the clipboard. * If no `format` is provided, all pending data formats will be cleared. * * @returns `this` */ ZeroClipboard.prototype.clearData = function() { ZeroClipboard.clearData.apply(this, _args(arguments)); return this; }; /** * Gets a copy of the pending data to inject into the clipboard. * If no `format` is provided, a copy of ALL pending data formats will be returned. * * @returns `String` or `Object` */ ZeroClipboard.prototype.getData = function() { return ZeroClipboard.getData.apply(this, _args(arguments)); }; if (typeof define === "function" && define.amd) { define(function() { return ZeroClipboard; }); } else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) { module.exports = ZeroClipboard; } else { window.ZeroClipboard = ZeroClipboard; } })(function() { return this || window; }()); // Copyright 2006 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Known Issues: // // * Patterns only support repeat. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; var IE_VERSION = +navigator.userAgent.match(/MSIE ([\d.]+)?/)[1]; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } function encodeHtmlAttribute(s) { return String(s).replace(/&/g, '&').replace(/"/g, '"'); } function addNamespace(doc, prefix, urn) { if (!doc.namespaces[prefix]) { doc.namespaces.add(prefix, urn, '#default#VML'); } } function addNamespacesAndStylesheet(doc) { addNamespace(doc, 'g_vml_', 'urn:schemas-microsoft-com:vml'); addNamespace(doc, 'g_o_', 'urn:schemas-microsoft-com:office:office'); // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}'; } } // Add namespaces and stylesheet at startup. addNamespacesAndStylesheet(document); var G_vmlCanvasManager_ = { init: function(opt_doc) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); }, init_: function(doc) { // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Add namespaces and stylesheet to document of the element. addNamespacesAndStylesheet(el.ownerDocument); // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.getContext().clearRect(); el.style.width = el.attributes.width.nodeValue + 'px'; // In IE8 this does not trigger onresize. el.firstChild.style.width = el.clientWidth + 'px'; break; case 'height': el.getContext().clearRect(); el.style.height = el.attributes.height.nodeValue + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var decToHex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { decToHex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.font = o1.font; o2.textAlign = o1.textAlign; o2.textBaseline = o1.textBaseline; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } var colorData = { aliceblue: '#F0F8FF', antiquewhite: '#FAEBD7', aquamarine: '#7FFFD4', azure: '#F0FFFF', beige: '#F5F5DC', bisque: '#FFE4C4', black: '#000000', blanchedalmond: '#FFEBCD', blueviolet: '#8A2BE2', brown: '#A52A2A', burlywood: '#DEB887', cadetblue: '#5F9EA0', chartreuse: '#7FFF00', chocolate: '#D2691E', coral: '#FF7F50', cornflowerblue: '#6495ED', cornsilk: '#FFF8DC', crimson: '#DC143C', cyan: '#00FFFF', darkblue: '#00008B', darkcyan: '#008B8B', darkgoldenrod: '#B8860B', darkgray: '#A9A9A9', darkgreen: '#006400', darkgrey: '#A9A9A9', darkkhaki: '#BDB76B', darkmagenta: '#8B008B', darkolivegreen: '#556B2F', darkorange: '#FF8C00', darkorchid: '#9932CC', darkred: '#8B0000', darksalmon: '#E9967A', darkseagreen: '#8FBC8F', darkslateblue: '#483D8B', darkslategray: '#2F4F4F', darkslategrey: '#2F4F4F', darkturquoise: '#00CED1', darkviolet: '#9400D3', deeppink: '#FF1493', deepskyblue: '#00BFFF', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1E90FF', firebrick: '#B22222', floralwhite: '#FFFAF0', forestgreen: '#228B22', gainsboro: '#DCDCDC', ghostwhite: '#F8F8FF', gold: '#FFD700', goldenrod: '#DAA520', grey: '#808080', greenyellow: '#ADFF2F', honeydew: '#F0FFF0', hotpink: '#FF69B4', indianred: '#CD5C5C', indigo: '#4B0082', ivory: '#FFFFF0', khaki: '#F0E68C', lavender: '#E6E6FA', lavenderblush: '#FFF0F5', lawngreen: '#7CFC00', lemonchiffon: '#FFFACD', lightblue: '#ADD8E6', lightcoral: '#F08080', lightcyan: '#E0FFFF', lightgoldenrodyellow: '#FAFAD2', lightgreen: '#90EE90', lightgrey: '#D3D3D3', lightpink: '#FFB6C1', lightsalmon: '#FFA07A', lightseagreen: '#20B2AA', lightskyblue: '#87CEFA', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#B0C4DE', lightyellow: '#FFFFE0', limegreen: '#32CD32', linen: '#FAF0E6', magenta: '#FF00FF', mediumaquamarine: '#66CDAA', mediumblue: '#0000CD', mediumorchid: '#BA55D3', mediumpurple: '#9370DB', mediumseagreen: '#3CB371', mediumslateblue: '#7B68EE', mediumspringgreen: '#00FA9A', mediumturquoise: '#48D1CC', mediumvioletred: '#C71585', midnightblue: '#191970', mintcream: '#F5FFFA', mistyrose: '#FFE4E1', moccasin: '#FFE4B5', navajowhite: '#FFDEAD', oldlace: '#FDF5E6', olivedrab: '#6B8E23', orange: '#FFA500', orangered: '#FF4500', orchid: '#DA70D6', palegoldenrod: '#EEE8AA', palegreen: '#98FB98', paleturquoise: '#AFEEEE', palevioletred: '#DB7093', papayawhip: '#FFEFD5', peachpuff: '#FFDAB9', peru: '#CD853F', pink: '#FFC0CB', plum: '#DDA0DD', powderblue: '#B0E0E6', rosybrown: '#BC8F8F', royalblue: '#4169E1', saddlebrown: '#8B4513', salmon: '#FA8072', sandybrown: '#F4A460', seagreen: '#2E8B57', seashell: '#FFF5EE', sienna: '#A0522D', skyblue: '#87CEEB', slateblue: '#6A5ACD', slategray: '#708090', slategrey: '#708090', snow: '#FFFAFA', springgreen: '#00FF7F', steelblue: '#4682B4', tan: '#D2B48C', thistle: '#D8BFD8', tomato: '#FF6347', turquoise: '#40E0D0', violet: '#EE82EE', wheat: '#F5DEB3', whitesmoke: '#F5F5F5', yellowgreen: '#9ACD32' }; function getRgbHslContent(styleString) { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var parts = styleString.substring(start + 1, end).split(','); // add alpha if needed if (parts.length != 4 || styleString.charAt(3) != 'a') { parts[3] = 1; } return parts; } function percent(s) { return parseFloat(s) / 100; } function clamp(v, min, max) { return Math.min(max, Math.max(min, v)); } function hslToRgb(parts){ var r, g, b, h, s, l; h = parseFloat(parts[0]) / 360 % 360; if (h < 0) h++; s = clamp(percent(parts[1]), 0, 1); l = clamp(percent(parts[2]), 0, 1); if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hueToRgb(p, q, h + 1 / 3); g = hueToRgb(p, q, h); b = hueToRgb(p, q, h - 1 / 3); } return '#' + decToHex[Math.floor(r * 255)] + decToHex[Math.floor(g * 255)] + decToHex[Math.floor(b * 255)]; } function hueToRgb(m1, m2, h) { if (h < 0) h++; if (h > 1) h--; if (6 * h < 1) return m1 + (m2 - m1) * 6 * h; else if (2 * h < 1) return m2; else if (3 * h < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6; else return m1; } var processStyleCache = {}; function processStyle(styleString) { if (styleString in processStyleCache) { return processStyleCache[styleString]; } var str, alpha = 1; styleString = String(styleString); if (styleString.charAt(0) == '#') { str = styleString; } else if (/^rgb/.test(styleString)) { var parts = getRgbHslContent(styleString); var str = '#', n; for (var i = 0; i < 3; i++) { if (parts[i].indexOf('%') != -1) { n = Math.floor(percent(parts[i]) * 255); } else { n = +parts[i]; } str += decToHex[clamp(n, 0, 255)]; } alpha = +parts[3]; } else if (/^hsl/.test(styleString)) { var parts = getRgbHslContent(styleString); str = hslToRgb(parts); alpha = parts[3]; } else { str = colorData[styleString] || styleString; } return processStyleCache[styleString] = {color: str, alpha: alpha}; } var DEFAULT_STYLE = { style: 'normal', variant: 'normal', weight: 'normal', size: 10, family: 'sans-serif' }; // Internal text style cache var fontStyleCache = {}; function processFontStyle(styleString) { if (fontStyleCache[styleString]) { return fontStyleCache[styleString]; } var el = document.createElement('div'); var style = el.style; try { style.font = styleString; } catch (ex) { // Ignore failures to set to invalid font. } return fontStyleCache[styleString] = { style: style.fontStyle || DEFAULT_STYLE.style, variant: style.fontVariant || DEFAULT_STYLE.variant, weight: style.fontWeight || DEFAULT_STYLE.weight, size: style.fontSize || DEFAULT_STYLE.size, family: style.fontFamily || DEFAULT_STYLE.family }; } function getComputedStyle(style, element) { var computedStyle = {}; for (var p in style) { computedStyle[p] = style[p]; } // Compute the size var canvasFontSize = parseFloat(element.currentStyle.fontSize), fontSize = parseFloat(style.size); if (typeof style.size == 'number') { computedStyle.size = style.size; } else if (style.size.indexOf('px') != -1) { computedStyle.size = fontSize; } else if (style.size.indexOf('em') != -1) { computedStyle.size = canvasFontSize * fontSize; } else if(style.size.indexOf('%') != -1) { computedStyle.size = (canvasFontSize / 100) * fontSize; } else if (style.size.indexOf('pt') != -1) { computedStyle.size = fontSize / .75; } else { computedStyle.size = canvasFontSize; } // Different scaling between normal text and VML text. This was found using // trial and error to get the same size as non VML text. computedStyle.size *= 0.981; return computedStyle; } function buildStyle(style) { return style.style + ' ' + style.variant + ' ' + style.weight + ' ' + style.size + 'px ' + style.family; } var lineCapMap = { 'butt': 'flat', 'round': 'round' }; function processLineCap(lineCap) { return lineCapMap[lineCap] || 'square'; } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} canvasElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(canvasElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.font = '10px sans-serif'; this.textAlign = 'left'; this.textBaseline = 'alphabetic'; this.canvas = canvasElement; var cssText = 'width:' + canvasElement.clientWidth + 'px;height:' + canvasElement.clientHeight + 'px;overflow:hidden;position:absolute'; var el = canvasElement.ownerDocument.createElement('div'); el.style.cssText = cssText; canvasElement.appendChild(el); var overlayEl = el.cloneNode(false); // Use a non transparent background. overlayEl.style.backgroundColor = 'red'; overlayEl.style.filter = 'alpha(opacity=0)'; canvasElement.appendChild(overlayEl); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { if (this.textMeasureEl_) { this.textMeasureEl_.removeNode(true); this.textMeasureEl_ = null; } this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = getCoords(this, aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = getCoords(this, aX, aY); var cp1 = getCoords(this, aCP1x, aCP1y); var cp2 = getCoords(this, aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = getCoords(this, aCPx, aCPy); var p = getCoords(this, aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = getCoords(this, aX, aY); var pStart = getCoords(this, xStart, yStart); var pEnd = getCoords(this, xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { if (image.getContext) { // draw canvas this.element_.innerHTML += image.getContext("2d").element_.innerHTML; } var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = getCoords(this, dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1] || this.m_[1][1] != 1 || this.m_[1][0]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = getCoords(this, dx + dw, dy); var c3 = getCoords(this, dx, dy + dh); var c4 = getCoords(this, dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');"); } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var lineStr = []; var lineOpen = false; var W = 10; var H = 10; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0,0"', ' coordsize="', Z * W, ',', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var i = 0; i < this.currentPath_.length; i++) { var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { appendStroke(this, lineStr); } else { appendFill(this, lineStr, min, max); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; function appendStroke(ctx, lineStr) { var a = processStyle(ctx.strokeStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; var lineWidth = ctx.lineScale_ * ctx.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', ctx.lineJoin, '"', ' miterlimit="', ctx.miterLimit, '"', ' endcap="', processLineCap(ctx.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } function appendFill(ctx, lineStr, min, max) { var fillStyle = ctx.fillStyle; var arcScaleX = ctx.arcScaleX_; var arcScaleY = ctx.arcScaleY_; var width = max.x - min.x; var height = max.y - min.y; if (fillStyle instanceof CanvasGradient_) { // TODO: Gradients transformed with the transformation matrix. var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / arcScaleX; var y0 = fillStyle.y0_ / arcScaleY; var x1 = fillStyle.x1_ / arcScaleX; var y1 = fillStyle.y1_ / arcScaleY; var p0 = getCoords(ctx, x0, y0); var p1 = getCoords(ctx, x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = getCoords(ctx, fillStyle.x0_, fillStyle.y0_); focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= arcScaleX * Z; height /= arcScaleY * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * ctx.globalAlpha; var opacity2 = stops[length - 1].alpha * ctx.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else if (fillStyle instanceof CanvasPattern_) { if (width && height) { var deltaLeft = -min.x; var deltaTop = -min.y; lineStr.push('<g_vml_:fill', ' position="', deltaLeft / width * arcScaleX * arcScaleX, ',', deltaTop / height * arcScaleY * arcScaleY, '"', ' type="tile"', // TODO: Figure out the correct size to fit the scale. //' size="', w, 'px ', h, 'px"', ' src="', fillStyle.src_, '" />'); } } else { var a = processStyle(ctx.fillStyle); var color = a.color; var opacity = a.alpha * ctx.globalAlpha; lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } } contextPrototype.fill = function() { this.stroke(true); }; contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; function getCoords(ctx, aX, aY) { var m = ctx.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 }; }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { if (this.aStack_.length) { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); } }; function matrixIsFinite(m) { return isFinite(m[0][0]) && isFinite(m[0][1]) && isFinite(m[1][0]) && isFinite(m[1][1]) && isFinite(m[2][0]) && isFinite(m[2][1]); } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /** * The text drawing function. * The maxWidth argument isn't taken in account, since no browser supports * it yet. */ contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) { var m = this.m_, delta = 1000, left = 0, right = delta, offset = {x: 0, y: 0}, lineStr = []; var fontStyle = getComputedStyle(processFontStyle(this.font), this.element_); var fontStyleString = buildStyle(fontStyle); var elementStyle = this.element_.currentStyle; var textAlign = this.textAlign.toLowerCase(); switch (textAlign) { case 'left': case 'center': case 'right': break; case 'end': textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left'; break; case 'start': textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left'; break; default: textAlign = 'left'; } // 1.75 is an arbitrary number, as there is no info about the text baseline switch (this.textBaseline) { case 'hanging': case 'top': offset.y = fontStyle.size / 1.75; break; case 'middle': break; default: case null: case 'alphabetic': case 'ideographic': case 'bottom': offset.y = -fontStyle.size / 2.25; break; } switch(textAlign) { case 'right': left = delta; right = 0.05; break; case 'center': left = right = delta / 2; break; } var d = getCoords(this, x + offset.x, y + offset.y); lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ', ' coordsize="100 100" coordorigin="0 0"', ' filled="', !stroke, '" stroked="', !!stroke, '" style="position:absolute;width:1px;height:1px;">'); if (stroke) { appendStroke(this, lineStr); } else { // TODO: Fix the min and max params. appendFill(this, lineStr, {x: -left, y: 0}, {x: right, y: fontStyle.size}); } var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' + m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0'; var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z); lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ', ' offset="', skewOffset, '" origin="', left ,' 0" />', '<g_vml_:path textpathok="true" />', '<g_vml_:textpath on="true" string="', encodeHtmlAttribute(text), '" style="v-text-align:', textAlign, ';font:', encodeHtmlAttribute(fontStyleString), '" /></g_vml_:line>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fillText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, false); }; contextPrototype.strokeText = function(text, x, y, maxWidth) { this.drawText_(text, x, y, maxWidth, true); }; contextPrototype.measureText = function(text) { if (!this.textMeasureEl_) { var s = '<span style="position:absolute;' + 'top:-20000px;left:0;padding:0;margin:0;border:none;' + 'white-space:pre;"></span>'; this.element_.insertAdjacentHTML('beforeEnd', s); this.textMeasureEl_ = this.element_.lastChild; } var doc = this.element_.ownerDocument; this.textMeasureEl_.innerHTML = ''; this.textMeasureEl_.style.font = this.font; // Don't use innerHTML or innerText because they allow markup/whitespace. this.textMeasureEl_.appendChild(doc.createTextNode(text)); return {width: this.textMeasureEl_.offsetWidth}; }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function(image, repetition) { return new CanvasPattern_(image, repetition); }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_(image, repetition) { assertImageIsValid(image); switch (repetition) { case 'repeat': case null: case '': this.repetition_ = 'repeat'; break case 'repeat-x': case 'repeat-y': case 'no-repeat': this.repetition_ = repetition; break; default: throwException('SYNTAX_ERR'); } this.src_ = image.src; this.width_ = image.width; this.height_ = image.height; } function throwException(s) { throw new DOMException_(s); } function assertImageIsValid(img) { if (!img || img.nodeType != 1 || img.tagName != 'IMG') { throwException('TYPE_MISMATCH_ERR'); } if (img.readyState != 'complete') { throwException('INVALID_STATE_ERR'); } } function DOMException_(s) { this.code = this[s]; this.message = s +': DOM Exception ' + this.code; } var p = DOMException_.prototype = new Error; p.INDEX_SIZE_ERR = 1; p.DOMSTRING_SIZE_ERR = 2; p.HIERARCHY_REQUEST_ERR = 3; p.WRONG_DOCUMENT_ERR = 4; p.INVALID_CHARACTER_ERR = 5; p.NO_DATA_ALLOWED_ERR = 6; p.NO_MODIFICATION_ALLOWED_ERR = 7; p.NOT_FOUND_ERR = 8; p.NOT_SUPPORTED_ERR = 9; p.INUSE_ATTRIBUTE_ERR = 10; p.INVALID_STATE_ERR = 11; p.SYNTAX_ERR = 12; p.INVALID_MODIFICATION_ERR = 13; p.NAMESPACE_ERR = 14; p.INVALID_ACCESS_ERR = 15; p.VALIDATION_ERR = 16; p.TYPE_MISMATCH_ERR = 17; // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; DOMException = DOMException_; })(); } // if /*! SWFObject v2.3.20130521 <http://github.com/swfobject/swfobject> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfobject=function(){var D="undefined",r="object",T="Shockwave Flash",Z="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",S="SWFObjectExprInst",x="onreadystatechange",Q=window,h=document,t=navigator,V=false,X=[],o=[],P=[],K=[],I,p,E,B,L=false,a=false,m,G,j=true,l=false,O=function(){var ad=typeof h.getElementById!=D&&typeof h.getElementsByTagName!=D&&typeof h.createElement!=D,ak=t.userAgent.toLowerCase(),ab=t.platform.toLowerCase(),ah=ab?/win/.test(ab):/win/.test(ak),af=ab?/mac/.test(ab):/mac/.test(ak),ai=/webkit/.test(ak)?parseFloat(ak.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,aa=t.appName==="Microsoft Internet Explorer",aj=[0,0,0],ae=null;if(typeof t.plugins!=D&&typeof t.plugins[T]==r){ae=t.plugins[T].description;if(ae&&(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&t.mimeTypes[q].enabledPlugin)){V=true;aa=false;ae=ae.replace(/^.*\s+(\S+\s+\S+$)/,"$1");aj[0]=n(ae.replace(/^(.*)\..*$/,"$1"));aj[1]=n(ae.replace(/^.*\.(.*)\s.*$/,"$1"));aj[2]=/[a-zA-Z]/.test(ae)?n(ae.replace(/^.*[a-zA-Z]+(.*)$/,"$1")):0}}else{if(typeof Q.ActiveXObject!=D){try{var ag=new ActiveXObject(Z);if(ag){ae=ag.GetVariable("$version");if(ae){aa=true;ae=ae.split(" ")[1].split(",");aj=[n(ae[0]),n(ae[1]),n(ae[2])]}}}catch(ac){}}}return{w3:ad,pv:aj,wk:ai,ie:aa,win:ah,mac:af}}(),i=function(){if(!O.w3){return}if((typeof h.readyState!=D&&(h.readyState==="complete"||h.readyState==="interactive"))||(typeof h.readyState==D&&(h.getElementsByTagName("body")[0]||h.body))){f()}if(!L){if(typeof h.addEventListener!=D){h.addEventListener("DOMContentLoaded",f,false)}if(O.ie){h.attachEvent(x,function aa(){if(h.readyState=="complete"){h.detachEvent(x,aa);f()}});if(Q==top){(function ac(){if(L){return}try{h.documentElement.doScroll("left")}catch(ad){setTimeout(ac,0);return}f()}())}}if(O.wk){(function ab(){if(L){return}if(!/loaded|complete/.test(h.readyState)){setTimeout(ab,0);return}f()}())}}}();function f(){if(L||!document.getElementsByTagName("body")[0]){return}try{var ac,ad=C("span");ad.style.display="none";ac=h.getElementsByTagName("body")[0].appendChild(ad);ac.parentNode.removeChild(ac);ac=null;ad=null}catch(ae){return}L=true;var aa=X.length;for(var ab=0;ab<aa;ab++){X[ab]()}}function M(aa){if(L){aa()}else{X[X.length]=aa}}function s(ab){if(typeof Q.addEventListener!=D){Q.addEventListener("load",ab,false)}else{if(typeof h.addEventListener!=D){h.addEventListener("load",ab,false)}else{if(typeof Q.attachEvent!=D){g(Q,"onload",ab)}else{if(typeof Q.onload=="function"){var aa=Q.onload;Q.onload=function(){aa();ab()}}else{Q.onload=ab}}}}}function Y(){var aa=h.getElementsByTagName("body")[0];var ae=C(r);ae.setAttribute("style","visibility: hidden;");ae.setAttribute("type",q);var ad=aa.appendChild(ae);if(ad){var ac=0;(function ab(){if(typeof ad.GetVariable!=D){try{var ag=ad.GetVariable("$version");if(ag){ag=ag.split(" ")[1].split(",");O.pv=[n(ag[0]),n(ag[1]),n(ag[2])]}}catch(af){O.pv=[8,0,0]}}else{if(ac<10){ac++;setTimeout(ab,10);return}}aa.removeChild(ae);ad=null;H()}())}else{H()}}function H(){var aj=o.length;if(aj>0){for(var ai=0;ai<aj;ai++){var ab=o[ai].id;var ae=o[ai].callbackFn;var ad={success:false,id:ab};if(O.pv[0]>0){var ah=c(ab);if(ah){if(F(o[ai].swfVersion)&&!(O.wk&&O.wk<312)){w(ab,true);if(ae){ad.success=true;ad.ref=z(ab);ad.id=ab;ae(ad)}}else{if(o[ai].expressInstall&&A()){var al={};al.data=o[ai].expressInstall;al.width=ah.getAttribute("width")||"0";al.height=ah.getAttribute("height")||"0";if(ah.getAttribute("class")){al.styleclass=ah.getAttribute("class")}if(ah.getAttribute("align")){al.align=ah.getAttribute("align")}var ak={};var aa=ah.getElementsByTagName("param");var af=aa.length;for(var ag=0;ag<af;ag++){if(aa[ag].getAttribute("name").toLowerCase()!="movie"){ak[aa[ag].getAttribute("name")]=aa[ag].getAttribute("value")}}R(al,ak,ab,ae)}else{b(ah);if(ae){ae(ad)}}}}}else{w(ab,true);if(ae){var ac=z(ab);if(ac&&typeof ac.SetVariable!=D){ad.success=true;ad.ref=ac;ad.id=ac.id}ae(ad)}}}}}X[0]=function(){if(V){Y()}else{H()}};function z(ac){var aa=null,ab=c(ac);if(ab&&ab.nodeName.toUpperCase()==="OBJECT"){if(typeof ab.SetVariable!==D){aa=ab}else{aa=ab.getElementsByTagName(r)[0]||ab}}return aa}function A(){return !a&&F("6.0.65")&&(O.win||O.mac)&&!(O.wk&&O.wk<312)}function R(ad,ae,aa,ac){var ah=c(aa);aa=W(aa);a=true;E=ac||null;B={success:false,id:aa};if(ah){if(ah.nodeName.toUpperCase()=="OBJECT"){I=J(ah);p=null}else{I=ah;p=aa}ad.id=S;if(typeof ad.width==D||(!/%$/.test(ad.width)&&n(ad.width)<310)){ad.width="310"}if(typeof ad.height==D||(!/%$/.test(ad.height)&&n(ad.height)<137)){ad.height="137"}var ag=O.ie?"ActiveX":"PlugIn",af="MMredirectURL="+encodeURIComponent(Q.location.toString().replace(/&/g,"%26"))+"&MMplayerType="+ag+"&MMdoctitle="+encodeURIComponent(h.title.slice(0,47)+" - Flash Player Installation");if(typeof ae.flashvars!=D){ae.flashvars+="&"+af}else{ae.flashvars=af}if(O.ie&&ah.readyState!=4){var ab=C("div"); aa+="SWFObjectNew";ab.setAttribute("id",aa);ah.parentNode.insertBefore(ab,ah);ah.style.display="none";y(ah)}u(ad,ae,aa)}}function b(ab){if(O.ie&&ab.readyState!=4){ab.style.display="none";var aa=C("div");ab.parentNode.insertBefore(aa,ab);aa.parentNode.replaceChild(J(ab),aa);y(ab)}else{ab.parentNode.replaceChild(J(ab),ab)}}function J(af){var ae=C("div");if(O.win&&O.ie){ae.innerHTML=af.innerHTML}else{var ab=af.getElementsByTagName(r)[0];if(ab){var ag=ab.childNodes;if(ag){var aa=ag.length;for(var ad=0;ad<aa;ad++){if(!(ag[ad].nodeType==1&&ag[ad].nodeName=="PARAM")&&!(ag[ad].nodeType==8)){ae.appendChild(ag[ad].cloneNode(true))}}}}}return ae}function k(aa,ab){var ac=C("div");ac.innerHTML="<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'><param name='movie' value='"+aa+"'>"+ab+"</object>";return ac.firstChild}function u(ai,ag,ab){var aa,ad=c(ab);ab=W(ab);if(O.wk&&O.wk<312){return aa}if(ad){var ac=(O.ie)?C("div"):C(r),af,ah,ae;if(typeof ai.id==D){ai.id=ab}for(ae in ag){if(ag.hasOwnProperty(ae)&&ae.toLowerCase()!=="movie"){e(ac,ae,ag[ae])}}if(O.ie){ac=k(ai.data,ac.innerHTML)}for(af in ai){if(ai.hasOwnProperty(af)){ah=af.toLowerCase();if(ah==="styleclass"){ac.setAttribute("class",ai[af])}else{if(ah!=="classid"&&ah!=="data"){ac.setAttribute(af,ai[af])}}}}if(O.ie){P[P.length]=ai.id}else{ac.setAttribute("type",q);ac.setAttribute("data",ai.data)}ad.parentNode.replaceChild(ac,ad);aa=ac}return aa}function e(ac,aa,ab){var ad=C("param");ad.setAttribute("name",aa);ad.setAttribute("value",ab);ac.appendChild(ad)}function y(ac){var ab=c(ac);if(ab&&ab.nodeName.toUpperCase()=="OBJECT"){if(O.ie){ab.style.display="none";(function aa(){if(ab.readyState==4){for(var ad in ab){if(typeof ab[ad]=="function"){ab[ad]=null}}ab.parentNode.removeChild(ab)}else{setTimeout(aa,10)}}())}else{ab.parentNode.removeChild(ab)}}}function U(aa){return(aa&&aa.nodeType&&aa.nodeType===1)}function W(aa){return(U(aa))?aa.id:aa}function c(ac){if(U(ac)){return ac}var aa=null;try{aa=h.getElementById(ac)}catch(ab){}return aa}function C(aa){return h.createElement(aa)}function n(aa){return parseInt(aa,10)}function g(ac,aa,ab){ac.attachEvent(aa,ab);K[K.length]=[ac,aa,ab]}function F(ac){ac+="";var ab=O.pv,aa=ac.split(".");aa[0]=n(aa[0]);aa[1]=n(aa[1])||0;aa[2]=n(aa[2])||0;return(ab[0]>aa[0]||(ab[0]==aa[0]&&ab[1]>aa[1])||(ab[0]==aa[0]&&ab[1]==aa[1]&&ab[2]>=aa[2]))?true:false}function v(af,ab,ag,ae){var ad=h.getElementsByTagName("head")[0];if(!ad){return}var aa=(typeof ag=="string")?ag:"screen";if(ae){m=null;G=null}if(!m||G!=aa){var ac=C("style");ac.setAttribute("type","text/css");ac.setAttribute("media",aa);m=ad.appendChild(ac);if(O.ie&&typeof h.styleSheets!=D&&h.styleSheets.length>0){m=h.styleSheets[h.styleSheets.length-1]}G=aa}if(m){if(typeof m.addRule!=D){m.addRule(af,ab)}else{if(typeof h.createTextNode!=D){m.appendChild(h.createTextNode(af+" {"+ab+"}"))}}}}function w(ad,aa){if(!j){return}var ab=aa?"visible":"hidden",ac=c(ad);if(L&&ac){ac.style.visibility=ab}else{if(typeof ad==="string"){v("#"+ad,"visibility:"+ab)}}}function N(ab){var ac=/[\\\"<>\.;]/;var aa=ac.exec(ab)!=null;return aa&&typeof encodeURIComponent!=D?encodeURIComponent(ab):ab}var d=function(){if(O.ie){window.attachEvent("onunload",function(){var af=K.length;for(var ae=0;ae<af;ae++){K[ae][0].detachEvent(K[ae][1],K[ae][2])}var ac=P.length;for(var ad=0;ad<ac;ad++){y(P[ad])}for(var ab in O){O[ab]=null}O=null;for(var aa in swfobject){swfobject[aa]=null}swfobject=null})}}();return{registerObject:function(ae,aa,ad,ac){if(O.w3&&ae&&aa){var ab={};ab.id=ae;ab.swfVersion=aa;ab.expressInstall=ad;ab.callbackFn=ac;o[o.length]=ab;w(ae,false)}else{if(ac){ac({success:false,id:ae})}}},getObjectById:function(aa){if(O.w3){return z(aa)}},embedSWF:function(af,al,ai,ak,ab,ae,ad,ah,aj,ag){var ac=W(al),aa={success:false,id:ac};if(O.w3&&!(O.wk&&O.wk<312)&&af&&al&&ai&&ak&&ab){w(ac,false);M(function(){ai+="";ak+="";var an={};if(aj&&typeof aj===r){for(var aq in aj){an[aq]=aj[aq]}}an.data=af;an.width=ai;an.height=ak;var ar={};if(ah&&typeof ah===r){for(var ao in ah){ar[ao]=ah[ao]}}if(ad&&typeof ad===r){for(var am in ad){if(ad.hasOwnProperty(am)){var ap=(l)?encodeURIComponent(am):am,at=(l)?encodeURIComponent(ad[am]):ad[am];if(typeof ar.flashvars!=D){ar.flashvars+="&"+ap+"="+at}else{ar.flashvars=ap+"="+at}}}}if(F(ab)){var au=u(an,ar,al);if(an.id==ac){w(ac,true)}aa.success=true;aa.ref=au;aa.id=au.id}else{if(ae&&A()){an.data=ae;R(an,ar,al,ag);return}else{w(ac,true)}}if(ag){ag(aa)}})}else{if(ag){ag(aa)}}},switchOffAutoHideShow:function(){j=false},enableUriEncoding:function(aa){l=(typeof aa===D)?true:aa},ua:O,getFlashPlayerVersion:function(){return{major:O.pv[0],minor:O.pv[1],release:O.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(ac,ab,aa){if(O.w3){return u(ac,ab,aa)}else{return undefined}},showExpressInstall:function(ac,ad,aa,ab){if(O.w3&&A()){R(ac,ad,aa,ab)}},removeSWF:function(aa){if(O.w3){y(aa)}},createCSS:function(ad,ac,ab,aa){if(O.w3){v(ad,ac,ab,aa)}},addDomLoadEvent:M,addLoadEvent:s,getQueryParamValue:function(ad){var ac=h.location.search||h.location.hash; if(ac){if(/\?/.test(ac)){ac=ac.split("?")[1]}if(ad==null){return N(ac)}var ab=ac.split("&");for(var aa=0;aa<ab.length;aa++){if(ab[aa].substring(0,ab[aa].indexOf("="))==ad){return N(ab[aa].substring((ab[aa].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var aa=c(S);if(aa&&I){aa.parentNode.replaceChild(I,aa);if(p){w(p,true);if(O.ie){I.style.display="block"}}if(E){E(B)}}a=false}},version:"2.3"}}(); /* Highcharts JS v4.0.3 (2014-07-03) (c) 2009-2014 Torstein Honsi License: www.highcharts.com/license */ (function(){function r(a,b){var c;a||(a={});for(c in b)a[c]=b[c];return a}function w(){var a,b=arguments,c,d={},e=function(a,b){var c,d;typeof a!=="object"&&(a={});for(d in b)b.hasOwnProperty(d)&&(c=b[d],a[d]=c&&typeof c==="object"&&Object.prototype.toString.call(c)!=="[object Array]"&&d!=="renderTo"&&typeof c.nodeType!=="number"?e(a[d]||{},c):b[d]);return a};b[0]===!0&&(d=b[1],b=Array.prototype.slice.call(b,2));c=b.length;for(a=0;a<c;a++)d=e(d,b[a]);return d}function z(a,b){return parseInt(a,b|| 10)}function Fa(a){return typeof a==="string"}function da(a){return a&&typeof a==="object"}function La(a){return Object.prototype.toString.call(a)==="[object Array]"}function ia(a){return typeof a==="number"}function za(a){return V.log(a)/V.LN10}function ja(a){return V.pow(10,a)}function ka(a,b){for(var c=a.length;c--;)if(a[c]===b){a.splice(c,1);break}}function s(a){return a!==t&&a!==null}function F(a,b,c){var d,e;if(Fa(b))s(c)?a.setAttribute(b,c):a&&a.getAttribute&&(e=a.getAttribute(b));else if(s(b)&& da(b))for(d in b)a.setAttribute(d,b[d]);return e}function ra(a){return La(a)?a:[a]}function p(){var a=arguments,b,c,d=a.length;for(b=0;b<d;b++)if(c=a[b],c!==t&&c!==null)return c}function A(a,b){if(Aa&&!ba&&b&&b.opacity!==t)b.filter="alpha(opacity="+b.opacity*100+")";r(a.style,b)}function $(a,b,c,d,e){a=x.createElement(a);b&&r(a,b);e&&A(a,{padding:0,border:P,margin:0});c&&A(a,c);d&&d.appendChild(a);return a}function la(a,b){var c=function(){return t};c.prototype=new a;r(c.prototype,b);return c}function Ga(a, b,c,d){var e=L.lang,a=+a||0,f=b===-1?(a.toString().split(".")[1]||"").length:isNaN(b=Q(b))?2:b,b=c===void 0?e.decimalPoint:c,d=d===void 0?e.thousandsSep:d,e=a<0?"-":"",c=String(z(a=Q(a).toFixed(f))),g=c.length>3?c.length%3:0;return e+(g?c.substr(0,g)+d:"")+c.substr(g).replace(/(\d{3})(?=\d)/g,"$1"+d)+(f?b+Q(a-c).toFixed(f).slice(2):"")}function Ha(a,b){return Array((b||2)+1-String(a).length).join(0)+a}function Ma(a,b,c){var d=a[b];a[b]=function(){var a=Array.prototype.slice.call(arguments);a.unshift(d); return c.apply(this,a)}}function Ia(a,b){for(var c="{",d=!1,e,f,g,h,i,j=[];(c=a.indexOf(c))!==-1;){e=a.slice(0,c);if(d){f=e.split(":");g=f.shift().split(".");i=g.length;e=b;for(h=0;h<i;h++)e=e[g[h]];if(f.length)f=f.join(":"),g=/\.([0-9])/,h=L.lang,i=void 0,/f$/.test(f)?(i=(i=f.match(g))?i[1]:-1,e!==null&&(e=Ga(e,i,h.decimalPoint,f.indexOf(",")>-1?h.thousandsSep:""))):e=bb(f,e)}j.push(e);a=a.slice(c+1);c=(d=!d)?"}":"{"}j.push(a);return j.join("")}function lb(a){return V.pow(10,U(V.log(a)/V.LN10))} function mb(a,b,c,d){var e,c=p(c,1);e=a/c;b||(b=[1,2,2.5,5,10],d&&d.allowDecimals===!1&&(c===1?b=[1,2,5,10]:c<=0.1&&(b=[1/c])));for(d=0;d<b.length;d++)if(a=b[d],e<=(b[d]+(b[d+1]||b[d]))/2)break;a*=c;return a}function nb(a,b){var c=a.length,d,e;for(e=0;e<c;e++)a[e].ss_i=e;a.sort(function(a,c){d=b(a,c);return d===0?a.ss_i-c.ss_i:d});for(e=0;e<c;e++)delete a[e].ss_i}function Na(a){for(var b=a.length,c=a[0];b--;)a[b]<c&&(c=a[b]);return c}function Ba(a){for(var b=a.length,c=a[0];b--;)a[b]>c&&(c=a[b]); return c}function Oa(a,b){for(var c in a)a[c]&&a[c]!==b&&a[c].destroy&&a[c].destroy(),delete a[c]}function Pa(a){cb||(cb=$(Ja));a&&cb.appendChild(a);cb.innerHTML=""}function ea(a){return parseFloat(a.toPrecision(14))}function Qa(a,b){va=p(a,b.animation)}function Ab(){var a=L.global.useUTC,b=a?"getUTC":"get",c=a?"setUTC":"set";Ra=(a&&L.global.timezoneOffset||0)*6E4;db=a?Date.UTC:function(a,b,c,g,h,i){return(new Date(a,b,p(c,1),p(g,0),p(h,0),p(i,0))).getTime()};ob=b+"Minutes";pb=b+"Hours";qb=b+"Day"; Wa=b+"Date";eb=b+"Month";fb=b+"FullYear";Bb=c+"Minutes";Cb=c+"Hours";rb=c+"Date";Db=c+"Month";Eb=c+"FullYear"}function G(){}function Sa(a,b,c,d){this.axis=a;this.pos=b;this.type=c||"";this.isNew=!0;!c&&!d&&this.addLabel()}function ma(){this.init.apply(this,arguments)}function Xa(){this.init.apply(this,arguments)}function Fb(a,b,c,d,e){var f=a.chart.inverted;this.axis=a;this.isNegative=c;this.options=b;this.x=d;this.total=null;this.points={};this.stack=e;this.alignOptions={align:b.align||(f?c?"left": "right":"center"),verticalAlign:b.verticalAlign||(f?"middle":c?"bottom":"top"),y:p(b.y,f?4:c?14:-6),x:p(b.x,f?c?-6:6:0)};this.textAlign=b.textAlign||(f?c?"right":"left":"center")}var t,x=document,H=window,V=Math,v=V.round,U=V.floor,Ka=V.ceil,u=V.max,C=V.min,Q=V.abs,aa=V.cos,fa=V.sin,na=V.PI,Ca=na*2/360,wa=navigator.userAgent,Gb=H.opera,Aa=/msie/i.test(wa)&&!Gb,gb=x.documentMode===8,sb=/AppleWebKit/.test(wa),Ta=/Firefox/.test(wa),Hb=/(Mobile|Android|Windows Phone)/.test(wa),xa="http://www.w3.org/2000/svg", ba=!!x.createElementNS&&!!x.createElementNS(xa,"svg").createSVGRect,Nb=Ta&&parseInt(wa.split("Firefox/")[1],10)<4,ga=!ba&&!Aa&&!!x.createElement("canvas").getContext,Ya,Za,Ib={},tb=0,cb,L,bb,va,ub,B,oa,sa=function(){return t},W=[],$a=0,Ja="div",P="none",Ob=/^[0-9]+$/,Pb="stroke-width",db,Ra,ob,pb,qb,Wa,eb,fb,Bb,Cb,rb,Db,Eb,J={},S;H.Highcharts?oa(16,!0):S=H.Highcharts={};bb=function(a,b,c){if(!s(b)||isNaN(b))return"Invalid date";var a=p(a,"%Y-%m-%d %H:%M:%S"),d=new Date(b-Ra),e,f=d[pb](),g=d[qb](), h=d[Wa](),i=d[eb](),j=d[fb](),k=L.lang,l=k.weekdays,d=r({a:l[g].substr(0,3),A:l[g],d:Ha(h),e:h,b:k.shortMonths[i],B:k.months[i],m:Ha(i+1),y:j.toString().substr(2,2),Y:j,H:Ha(f),I:Ha(f%12||12),l:f%12||12,M:Ha(d[ob]()),p:f<12?"AM":"PM",P:f<12?"am":"pm",S:Ha(d.getSeconds()),L:Ha(v(b%1E3),3)},S.dateFormats);for(e in d)for(;a.indexOf("%"+e)!==-1;)a=a.replace("%"+e,typeof d[e]==="function"?d[e](b):d[e]);return c?a.substr(0,1).toUpperCase()+a.substr(1):a};oa=function(a,b){var c="Highcharts error #"+a+": www.highcharts.com/errors/"+ a;if(b)throw c;H.console&&console.log(c)};B={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:26784E5,year:31556952E3};ub={init:function(a,b,c){var b=b||"",d=a.shift,e=b.indexOf("C")>-1,f=e?7:3,g,b=b.split(" "),c=[].concat(c),h,i,j=function(a){for(g=a.length;g--;)a[g]==="M"&&a.splice(g+1,0,a[g+1],a[g+2],a[g+1],a[g+2])};e&&(j(b),j(c));a.isArea&&(h=b.splice(b.length-6,6),i=c.splice(c.length-6,6));if(d<=c.length/f&&b.length===c.length)for(;d--;)c=[].concat(c).splice(0,f).concat(c); a.shift=0;if(b.length)for(a=c.length;b.length<a;)d=[].concat(b).splice(b.length-f,f),e&&(d[f-6]=d[f-2],d[f-5]=d[f-1]),b=b.concat(d);h&&(b=b.concat(h),c=c.concat(i));return[b,c]},step:function(a,b,c,d){var e=[],f=a.length;if(c===1)e=d;else if(f===b.length&&c<1)for(;f--;)d=parseFloat(a[f]),e[f]=isNaN(d)?a[f]:c*parseFloat(b[f]-d)+d;else e=b;return e}};(function(a){H.HighchartsAdapter=H.HighchartsAdapter||a&&{init:function(b){var c=a.fx,d=c.step,e,f=a.Tween,g=f&&f.propHooks;e=a.cssHooks.opacity;a.extend(a.easing, {easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c}});a.each(["cur","_default","width","height","opacity"],function(a,b){var e=d,k;b==="cur"?e=c.prototype:b==="_default"&&f&&(e=g[b],b="set");(k=e[b])&&(e[b]=function(c){var d,c=a?c:this;if(c.prop!=="align")return d=c.elem,d.attr?d.attr(c.prop,b==="cur"?t:c.now):k.apply(this,arguments)})});Ma(e,"get",function(a,b,c){return b.attr?b.opacity||0:a.call(this,b,c)});e=function(a){var c=a.elem,d;if(!a.started)d=b.init(c,c.d,c.toD),a.start=d[0],a.end= d[1],a.started=!0;c.attr("d",b.step(a.start,a.end,a.pos,c.toD))};f?g.d={set:e}:d.d=e;this.each=Array.prototype.forEach?function(a,b){return Array.prototype.forEach.call(a,b)}:function(a,b){var c,d=a.length;for(c=0;c<d;c++)if(b.call(a[c],a[c],c,a)===!1)return c};a.fn.highcharts=function(){var a="Chart",b=arguments,c,d;if(this[0]){Fa(b[0])&&(a=b[0],b=Array.prototype.slice.call(b,1));c=b[0];if(c!==t)c.chart=c.chart||{},c.chart.renderTo=this[0],new S[a](c,b[1]),d=this;c===t&&(d=W[F(this[0],"data-highcharts-chart")])}return d}}, getScript:a.getScript,inArray:a.inArray,adapterRun:function(b,c){return a(b)[c]()},grep:a.grep,map:function(a,c){for(var d=[],e=0,f=a.length;e<f;e++)d[e]=c.call(a[e],a[e],e,a);return d},offset:function(b){return a(b).offset()},addEvent:function(b,c,d){a(b).bind(c,d)},removeEvent:function(b,c,d){var e=x.removeEventListener?"removeEventListener":"detachEvent";x[e]&&b&&!b[e]&&(b[e]=function(){});a(b).unbind(c,d)},fireEvent:function(b,c,d,e){var f=a.Event(c),g="detached"+c,h;!Aa&&d&&(delete d.layerX, delete d.layerY,delete d.returnValue);r(f,d);b[c]&&(b[g]=b[c],b[c]=null);a.each(["preventDefault","stopPropagation"],function(a,b){var c=f[b];f[b]=function(){try{c.call(f)}catch(a){b==="preventDefault"&&(h=!0)}}});a(b).trigger(f);b[g]&&(b[c]=b[g],b[g]=null);e&&!f.isDefaultPrevented()&&!h&&e(f)},washMouseEvent:function(a){var c=a.originalEvent||a;if(c.pageX===t)c.pageX=a.pageX,c.pageY=a.pageY;return c},animate:function(b,c,d){var e=a(b);if(!b.style)b.style={};if(c.d)b.toD=c.d,c.d=1;e.stop();c.opacity!== t&&b.attr&&(c.opacity+="px");e.animate(c,d)},stop:function(b){a(b).stop()}}})(H.jQuery);var T=H.HighchartsAdapter,M=T||{};T&&T.init.call(T,ub);var hb=M.adapterRun,Qb=M.getScript,Da=M.inArray,q=M.each,vb=M.grep,Rb=M.offset,Ua=M.map,N=M.addEvent,X=M.removeEvent,K=M.fireEvent,Sb=M.washMouseEvent,ib=M.animate,ab=M.stop,M={enabled:!0,x:0,y:15,style:{color:"#606060",cursor:"default",fontSize:"11px"}};L={colors:"#7cb5ec,#434348,#90ed7d,#f7a35c,#8085e9,#f15c80,#e4d354,#8085e8,#8d4653,#91e8e1".split(","), symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January,February,March,April,May,June,July,August,September,October,November,December".split(","),shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec".split(","),weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(","),decimalPoint:".",numericSymbols:"k,M,G,T,P,E".split(","),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:","},global:{useUTC:!0, canvasToolsURL:"http://code.highcharts.com/4.0.3/modules/canvas-tools.js",VMLRadialGradientURL:"http://code.highcharts.com/4.0.3/gfx/vml-radial-gradient.png"},chart:{borderColor:"#4572A7",borderRadius:0,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],backgroundColor:"#FFFFFF",plotBorderColor:"#C0C0C0",resetZoomButton:{theme:{zIndex:20},position:{align:"right",x:-10,y:10}}},title:{text:"Chart title",align:"center",margin:15,style:{color:"#333333",fontSize:"18px"}},subtitle:{text:"", align:"center",style:{color:"#555555"}},plotOptions:{line:{allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},lineWidth:2,marker:{lineWidth:0,radius:4,lineColor:"#FFFFFF",states:{hover:{enabled:!0,lineWidthPlus:1,radiusPlus:2},select:{fillColor:"#FFFFFF",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:w(M,{align:"center",enabled:!1,formatter:function(){return this.y===null?"":Ga(this.y,-1)},verticalAlign:"bottom",y:0}),cropThreshold:300,pointRange:0,states:{hover:{lineWidthPlus:1, marker:{},halo:{size:10,opacity:0.25}},select:{marker:{}}},stickyTracking:!0,turboThreshold:1E3}},labels:{style:{position:"absolute",color:"#3E576F"}},legend:{enabled:!0,align:"center",layout:"horizontal",labelFormatter:function(){return this.name},borderColor:"#909090",borderRadius:0,navigation:{activeColor:"#274b6d",inactiveColor:"#CCC"},shadow:!1,itemStyle:{color:"#333333",fontSize:"12px",fontWeight:"bold"},itemHoverStyle:{color:"#000"},itemHiddenStyle:{color:"#CCC"},itemCheckboxStyle:{position:"absolute", width:"13px",height:"13px"},symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold",position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"white",opacity:0.5,textAlign:"center"}},tooltip:{enabled:!0,animation:ba,backgroundColor:"rgba(249, 249, 249, .85)",borderWidth:1,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M", day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},headerFormat:'<span style="font-size: 10px">{point.key}</span><br/>',pointFormat:'<span style="color:{series.color}">??</span> {series.name}: <b>{point.y}</b><br/>',shadow:!0,snap:Hb?25:10,style:{color:"#333333",cursor:"default",fontSize:"12px",padding:"8px",whiteSpace:"nowrap"}},credits:{enabled:!0,text:"Highcharts.com",href:"http://www.highcharts.com",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer", color:"#909090",fontSize:"9px"}}};var ca=L.plotOptions,T=ca.line;Ab();var Tb=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,Ub=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,Vb=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,ya=function(a){var b=[],c,d;(function(a){a&&a.stops?d=Ua(a.stops,function(a){return ya(a[1])}):(c=Tb.exec(a))?b=[z(c[1]),z(c[2]),z(c[3]),parseFloat(c[4],10)]:(c=Ub.exec(a))?b=[z(c[1],16),z(c[2],16),z(c[3], 16),1]:(c=Vb.exec(a))&&(b=[z(c[1]),z(c[2]),z(c[3]),1])})(a);return{get:function(c){var f;d?(f=w(a),f.stops=[].concat(f.stops),q(d,function(a,b){f.stops[b]=[f.stops[b][0],a.get(c)]})):f=b&&!isNaN(b[0])?c==="rgb"?"rgb("+b[0]+","+b[1]+","+b[2]+")":c==="a"?b[3]:"rgba("+b.join(",")+")":a;return f},brighten:function(a){if(d)q(d,function(b){b.brighten(a)});else if(ia(a)&&a!==0){var c;for(c=0;c<3;c++)b[c]+=z(a*255),b[c]<0&&(b[c]=0),b[c]>255&&(b[c]=255)}return this},rgba:b,setOpacity:function(a){b[3]=a;return this}}}; G.prototype={opacity:1,textProps:"fontSize,fontWeight,fontFamily,color,lineHeight,width,textDecoration,textShadow,HcTextStroke".split(","),init:function(a,b){this.element=b==="span"?$(b):x.createElementNS(xa,b);this.renderer=a},animate:function(a,b,c){b=p(b,va,!0);ab(this);if(b){b=w(b,{});if(c)b.complete=c;ib(this,a,b)}else this.attr(a),c&&c();return this},colorGradient:function(a,b,c){var d=this.renderer,e,f,g,h,i,j,k,l,m,n,o=[];a.linearGradient?f="linearGradient":a.radialGradient&&(f="radialGradient"); if(f){g=a[f];h=d.gradients;j=a.stops;m=c.radialReference;La(g)&&(a[f]=g={x1:g[0],y1:g[1],x2:g[2],y2:g[3],gradientUnits:"userSpaceOnUse"});f==="radialGradient"&&m&&!s(g.gradientUnits)&&(g=w(g,{cx:m[0]-m[2]/2+g.cx*m[2],cy:m[1]-m[2]/2+g.cy*m[2],r:g.r*m[2],gradientUnits:"userSpaceOnUse"}));for(n in g)n!=="id"&&o.push(n,g[n]);for(n in j)o.push(j[n]);o=o.join(",");h[o]?a=h[o].attr("id"):(g.id=a="highcharts-"+tb++,h[o]=i=d.createElement(f).attr(g).add(d.defs),i.stops=[],q(j,function(a){a[1].indexOf("rgba")=== 0?(e=ya(a[1]),k=e.get("rgb"),l=e.get("a")):(k=a[1],l=1);a=d.createElement("stop").attr({offset:a[0],"stop-color":k,"stop-opacity":l}).add(i);i.stops.push(a)}));c.setAttribute(b,"url("+d.url+"#"+a+")")}},attr:function(a,b){var c,d,e=this.element,f,g=this,h;typeof a==="string"&&b!==t&&(c=a,a={},a[c]=b);if(typeof a==="string")g=(this[a+"Getter"]||this._defaultGetter).call(this,a,e);else{for(c in a){d=a[c];h=!1;this.symbolName&&/^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(c)&&(f||(this.symbolAttr(a), f=!0),h=!0);if(this.rotation&&(c==="x"||c==="y"))this.doTransform=!0;h||(this[c+"Setter"]||this._defaultSetter).call(this,d,c,e);this.shadows&&/^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(c)&&this.updateShadows(c,d)}if(this.doTransform)this.updateTransform(),this.doTransform=!1}return g},updateShadows:function(a,b){for(var c=this.shadows,d=c.length;d--;)c[d].setAttribute(a,a==="height"?u(b-(c[d].cutHeight||0),0):a==="d"?this.d:b)},addClass:function(a){var b=this.element,c=F(b,"class")|| "";c.indexOf(a)===-1&&F(b,"class",c+" "+a);return this},symbolAttr:function(a){var b=this;q("x,y,r,start,end,width,height,innerR,anchorX,anchorY".split(","),function(c){b[c]=p(a[c],b[c])});b.attr({d:b.renderer.symbols[b.symbolName](b.x,b.y,b.width,b.height,b)})},clip:function(a){return this.attr("clip-path",a?"url("+this.renderer.url+"#"+a.id+")":P)},crisp:function(a){var b,c={},d,e=a.strokeWidth||this.strokeWidth||0;d=v(e)%2/2;a.x=U(a.x||this.x||0)+d;a.y=U(a.y||this.y||0)+d;a.width=U((a.width||this.width|| 0)-2*d);a.height=U((a.height||this.height||0)-2*d);a.strokeWidth=e;for(b in a)this[b]!==a[b]&&(this[b]=c[b]=a[b]);return c},css:function(a){var b=this.styles,c={},d=this.element,e,f,g="";e=!b;if(a&&a.color)a.fill=a.color;if(b)for(f in a)a[f]!==b[f]&&(c[f]=a[f],e=!0);if(e){e=this.textWidth=a&&a.width&&d.nodeName.toLowerCase()==="text"&&z(a.width);b&&(a=r(b,c));this.styles=a;e&&(ga||!ba&&this.renderer.forExport)&&delete a.width;if(Aa&&!ba)A(this.element,a);else{b=function(a,b){return"-"+b.toLowerCase()}; for(f in a)g+=f.replace(/([A-Z])/g,b)+":"+a[f]+";";F(d,"style",g)}e&&this.added&&this.renderer.buildText(this)}return this},on:function(a,b){var c=this,d=c.element;Za&&a==="click"?(d.ontouchstart=function(a){c.touchEventFired=Date.now();a.preventDefault();b.call(d,a)},d.onclick=function(a){(wa.indexOf("Android")===-1||Date.now()-(c.touchEventFired||0)>1100)&&b.call(d,a)}):d["on"+a]=b;return this},setRadialReference:function(a){this.element.radialReference=a;return this},translate:function(a,b){return this.attr({translateX:a, translateY:b})},invert:function(){this.inverted=!0;this.updateTransform();return this},updateTransform:function(){var a=this.translateX||0,b=this.translateY||0,c=this.scaleX,d=this.scaleY,e=this.inverted,f=this.rotation,g=this.element;e&&(a+=this.attr("width"),b+=this.attr("height"));a=["translate("+a+","+b+")"];e?a.push("rotate(90) scale(-1,1)"):f&&a.push("rotate("+f+" "+(g.getAttribute("x")||0)+" "+(g.getAttribute("y")||0)+")");(s(c)||s(d))&&a.push("scale("+p(c,1)+" "+p(d,1)+")");a.length&&g.setAttribute("transform", a.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,b,c){var d,e,f,g,h={};e=this.renderer;f=e.alignedObjects;if(a){if(this.alignOptions=a,this.alignByTranslate=b,!c||Fa(c))this.alignTo=d=c||"renderer",ka(f,this),f.push(this),c=null}else a=this.alignOptions,b=this.alignByTranslate,d=this.alignTo;c=p(c,e[d],e);d=a.align;e=a.verticalAlign;f=(c.x||0)+(a.x||0);g=(c.y||0)+(a.y||0);if(d==="right"||d==="center")f+=(c.width-(a.width||0))/{right:1,center:2}[d]; h[b?"translateX":"x"]=v(f);if(e==="bottom"||e==="middle")g+=(c.height-(a.height||0))/({bottom:1,middle:2}[e]||1);h[b?"translateY":"y"]=v(g);this[this.placed?"animate":"attr"](h);this.placed=!0;this.alignAttr=h;return this},getBBox:function(){var a=this.bBox,b=this.renderer,c,d,e=this.rotation;c=this.element;var f=this.styles,g=e*Ca;d=this.textStr;var h;if(d===""||Ob.test(d))h="num."+d.toString().length+(f?"|"+f.fontSize+"|"+f.fontFamily:"");h&&(a=b.cache[h]);if(!a){if(c.namespaceURI===xa||b.forExport){try{a= c.getBBox?r({},c.getBBox()):{width:c.offsetWidth,height:c.offsetHeight}}catch(i){}if(!a||a.width<0)a={width:0,height:0}}else a=this.htmlGetBBox();if(b.isSVG){c=a.width;d=a.height;if(Aa&&f&&f.fontSize==="11px"&&d.toPrecision(3)==="16.9")a.height=d=14;if(e)a.width=Q(d*fa(g))+Q(c*aa(g)),a.height=Q(d*aa(g))+Q(c*fa(g))}this.bBox=a;h&&(b.cache[h]=a)}return a},show:function(a){return a&&this.element.namespaceURI===xa?(this.element.removeAttribute("visibility"),this):this.attr({visibility:a?"inherit":"visible"})}, hide:function(){return this.attr({visibility:"hidden"})},fadeOut:function(a){var b=this;b.animate({opacity:0},{duration:a||150,complete:function(){b.hide()}})},add:function(a){var b=this.renderer,c=a||b,d=c.element||b.box,e=this.element,f=this.zIndex,g,h;if(a)this.parentGroup=a;this.parentInverted=a&&a.inverted;this.textStr!==void 0&&b.buildText(this);if(f)c.handleZ=!0,f=z(f);if(c.handleZ){a=d.childNodes;for(g=0;g<a.length;g++)if(b=a[g],c=F(b,"zIndex"),b!==e&&(z(c)>f||!s(f)&&s(c))){d.insertBefore(e, b);h=!0;break}}h||d.appendChild(e);this.added=!0;if(this.onAdd)this.onAdd();return this},safeRemoveChild:function(a){var b=a.parentNode;b&&b.removeChild(a)},destroy:function(){var a=this,b=a.element||{},c=a.shadows,d=a.renderer.isSVG&&b.nodeName==="SPAN"&&a.parentGroup,e,f;b.onclick=b.onmouseout=b.onmouseover=b.onmousemove=b.point=null;ab(a);if(a.clipPath)a.clipPath=a.clipPath.destroy();if(a.stops){for(f=0;f<a.stops.length;f++)a.stops[f]=a.stops[f].destroy();a.stops=null}a.safeRemoveChild(b);for(c&& q(c,function(b){a.safeRemoveChild(b)});d&&d.div&&d.div.childNodes.length===0;)b=d.parentGroup,a.safeRemoveChild(d.div),delete d.div,d=b;a.alignTo&&ka(a.renderer.alignedObjects,a);for(e in a)delete a[e];return null},shadow:function(a,b,c){var d=[],e,f,g=this.element,h,i,j,k;if(a){i=p(a.width,3);j=(a.opacity||0.15)/i;k=this.parentInverted?"(-1,-1)":"("+p(a.offsetX,1)+", "+p(a.offsetY,1)+")";for(e=1;e<=i;e++){f=g.cloneNode(0);h=i*2+1-2*e;F(f,{isShadow:"true",stroke:a.color||"black","stroke-opacity":j* e,"stroke-width":h,transform:"translate"+k,fill:P});if(c)F(f,"height",u(F(f,"height")-h,0)),f.cutHeight=h;b?b.element.appendChild(f):g.parentNode.insertBefore(f,g);d.push(f)}this.shadows=d}return this},xGetter:function(a){this.element.nodeName==="circle"&&(a={x:"cx",y:"cy"}[a]||a);return this._defaultGetter(a)},_defaultGetter:function(a){a=p(this[a],this.element?this.element.getAttribute(a):null,0);/^[\-0-9\.]+$/.test(a)&&(a=parseFloat(a));return a},dSetter:function(a,b,c){a&&a.join&&(a=a.join(" ")); /(NaN| {2}|^$)/.test(a)&&(a="M 0 0");c.setAttribute(b,a);this[b]=a},dashstyleSetter:function(a){var b;if(a=a&&a.toLowerCase()){a=a.replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot","1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").replace("solid",1).split(",");for(b=a.length;b--;)a[b]=z(a[b])*this["stroke-width"];a=a.join(",");this.element.setAttribute("stroke-dasharray",a)}},alignSetter:function(a){this.element.setAttribute("text-anchor", {left:"start",center:"middle",right:"end"}[a])},opacitySetter:function(a,b,c){this[b]=a;c.setAttribute(b,a)},titleSetter:function(a){var b=this.element.getElementsByTagName("title")[0];b||(b=x.createElementNS(xa,"title"),this.element.appendChild(b));b.textContent=a},textSetter:function(a){if(a!==this.textStr)delete this.bBox,this.textStr=a,this.added&&this.renderer.buildText(this)},fillSetter:function(a,b,c){typeof a==="string"?c.setAttribute(b,a):a&&this.colorGradient(a,b,c)},zIndexSetter:function(a, b,c){c.setAttribute(b,a);this[b]=a},_defaultSetter:function(a,b,c){c.setAttribute(b,a)}};G.prototype.yGetter=G.prototype.xGetter;G.prototype.translateXSetter=G.prototype.translateYSetter=G.prototype.rotationSetter=G.prototype.verticalAlignSetter=G.prototype.scaleXSetter=G.prototype.scaleYSetter=function(a,b){this[b]=a;this.doTransform=!0};G.prototype["stroke-widthSetter"]=G.prototype.strokeSetter=function(a,b,c){this[b]=a;if(this.stroke&&this["stroke-width"])this.strokeWidth=this["stroke-width"], G.prototype.fillSetter.call(this,this.stroke,"stroke",c),c.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0;else if(b==="stroke-width"&&a===0&&this.hasStroke)c.removeAttribute("stroke"),this.hasStroke=!1};var ta=function(){this.init.apply(this,arguments)};ta.prototype={Element:G,init:function(a,b,c,d,e){var f=location,g,d=this.createElement("svg").attr({version:"1.1"}).css(this.getStyle(d));g=d.element;a.appendChild(g);a.innerHTML.indexOf("xmlns")===-1&&F(g,"xmlns",xa);this.isSVG= !0;this.box=g;this.boxWrapper=d;this.alignedObjects=[];this.url=(Ta||sb)&&x.getElementsByTagName("base").length?f.href.replace(/#.*?$/,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(x.createTextNode("Created with Highcharts 4.0.3"));this.defs=this.createElement("defs").add();this.forExport=e;this.gradients={};this.cache={};this.setSize(b,c,!1);var h;if(Ta&&a.getBoundingClientRect)this.subPixelFix=b=function(){A(a,{left:0,top:0});h=a.getBoundingClientRect(); A(a,{left:Ka(h.left)-h.left+"px",top:Ka(h.top)-h.top+"px"})},b(),N(H,"resize",b)},getStyle:function(a){return this.style=r({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();Oa(this.gradients||{});this.gradients=null;if(a)this.defs=a.destroy();this.subPixelFix&&X(H,"resize",this.subPixelFix);return this.alignedObjects= null},createElement:function(a){var b=new this.Element;b.init(this,a);return b},draw:function(){},buildText:function(a){for(var b=a.element,c=this,d=c.forExport,e=p(a.textStr,"").toString(),f=e.indexOf("<")!==-1,g=b.childNodes,h,i,j=F(b,"x"),k=a.styles,l=a.textWidth,m=k&&k.lineHeight,n=k&&k.HcTextStroke,o=g.length,Y=function(a){return m?z(m):c.fontMetrics(/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize:k&&k.fontSize||c.style.fontSize||12,a).h};o--;)b.removeChild(g[o]);!f&&!n&&e.indexOf(" ")=== -1?b.appendChild(x.createTextNode(e)):(h=/<.*style="([^"]+)".*>/,i=/<.*href="(http[^"]+)".*>/,l&&!a.added&&this.box.appendChild(b),e=f?e.replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">').replace(/<a/g,"<span").replace(/<\/(b|strong|i|em|a)>/g,"</span>").split(/<br.*?>/g):[e],e[e.length-1]===""&&e.pop(),q(e,function(e,f){var g,m=0,e=e.replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");g=e.split("|||");q(g,function(e){if(e!== ""||g.length===1){var n={},o=x.createElementNS(xa,"tspan"),p;h.test(e)&&(p=e.match(h)[1].replace(/(;| |^)color([ :])/,"$1fill$2"),F(o,"style",p));i.test(e)&&!d&&(F(o,"onclick",'location.href="'+e.match(i)[1]+'"'),A(o,{cursor:"pointer"}));e=(e.replace(/<(.|\n)*?>/g,"")||" ").replace(/</g,"<").replace(/>/g,">");if(e!==" "){o.appendChild(x.createTextNode(e));if(m)n.dx=0;else if(f&&j!==null)n.x=j;F(o,n);b.appendChild(o);!m&&f&&(!ba&&d&&A(o,{display:"block"}),F(o,"dy",Y(o)));if(l)for(var e=e.replace(/([^\^])-/g, "$1- ").split(" "),n=g.length>1||e.length>1&&k.whiteSpace!=="nowrap",q,E,s=k.HcHeight,u=[],t=Y(o),Kb=1;n&&(e.length||u.length);)delete a.bBox,q=a.getBBox(),E=q.width,!ba&&c.forExport&&(E=c.measureSpanWidth(o.firstChild.data,a.styles)),q=E>l,!q||e.length===1?(e=u,u=[],e.length&&(Kb++,s&&Kb*t>s?(e=["..."],a.attr("title",a.textStr)):(o=x.createElementNS(xa,"tspan"),F(o,{dy:t,x:j}),p&&F(o,"style",p),b.appendChild(o))),E>l&&(l=E)):(o.removeChild(o.firstChild),u.unshift(e.pop())),e.length&&o.appendChild(x.createTextNode(e.join(" ").replace(/- /g, "-")));m++}}})}))},button:function(a,b,c,d,e,f,g,h,i){var j=this.label(a,b,c,i,null,null,null,null,"button"),k=0,l,m,n,o,p,q,a={x1:0,y1:0,x2:0,y2:1},e=w({"stroke-width":1,stroke:"#CCCCCC",fill:{linearGradient:a,stops:[[0,"#FEFEFE"],[1,"#F6F6F6"]]},r:2,padding:5,style:{color:"black"}},e);n=e.style;delete e.style;f=w(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#FFF"],[1,"#ACF"]]}},f);o=f.style;delete f.style;g=w(e,{stroke:"#68A",fill:{linearGradient:a,stops:[[0,"#9BD"],[1,"#CDF"]]}},g);p=g.style; delete g.style;h=w(e,{style:{color:"#CCC"}},h);q=h.style;delete h.style;N(j.element,Aa?"mouseover":"mouseenter",function(){k!==3&&j.attr(f).css(o)});N(j.element,Aa?"mouseout":"mouseleave",function(){k!==3&&(l=[e,f,g][k],m=[n,o,p][k],j.attr(l).css(m))});j.setState=function(a){(j.state=k=a)?a===2?j.attr(g).css(p):a===3&&j.attr(h).css(q):j.attr(e).css(n)};return j.on("click",function(){k!==3&&d.call(j)}).attr(e).css(r({cursor:"default"},n))},crispLine:function(a,b){a[1]===a[4]&&(a[1]=a[4]=v(a[1])-b% 2/2);a[2]===a[5]&&(a[2]=a[5]=v(a[2])+b%2/2);return a},path:function(a){var b={fill:P};La(a)?b.d=a:da(a)&&r(b,a);return this.createElement("path").attr(b)},circle:function(a,b,c){a=da(a)?a:{x:a,y:b,r:c};b=this.createElement("circle");b.xSetter=function(a){this.element.setAttribute("cx",a)};b.ySetter=function(a){this.element.setAttribute("cy",a)};return b.attr(a)},arc:function(a,b,c,d,e,f){if(da(a))b=a.y,c=a.r,d=a.innerR,e=a.start,f=a.end,a=a.x;a=this.symbol("arc",a||0,b||0,c||0,c||0,{innerR:d||0,start:e|| 0,end:f||0});a.r=c;return a},rect:function(a,b,c,d,e,f){var e=da(a)?a.r:e,g=this.createElement("rect"),a=da(a)?a:a===t?{}:{x:a,y:b,width:u(c,0),height:u(d,0)};if(f!==t)a.strokeWidth=f,a=g.crisp(a);if(e)a.r=e;g.rSetter=function(a){F(this.element,{rx:a,ry:a})};return g.attr(a)},setSize:function(a,b,c){var d=this.alignedObjects,e=d.length;this.width=a;this.height=b;for(this.boxWrapper[p(c,!0)?"animate":"attr"]({width:a,height:b});e--;)d[e].align()},g:function(a){var b=this.createElement("g");return s(a)? b.attr({"class":"highcharts-"+a}):b},image:function(a,b,c,d,e){var f={preserveAspectRatio:P};arguments.length>1&&r(f,{x:b,y:c,width:d,height:e});f=this.createElement("image").attr(f);f.element.setAttributeNS?f.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a):f.element.setAttribute("hc-svg-href",a);return f},symbol:function(a,b,c,d,e,f){var g,h=this.symbols[a],h=h&&h(v(b),v(c),d,e,f),i=/^url\((.*?)\)$/,j,k;if(h)g=this.path(h),r(g,{symbolName:a,x:b,y:c,width:d,height:e}),f&&r(g,f);else if(i.test(a))k= function(a,b){a.element&&(a.attr({width:b[0],height:b[1]}),a.alignByTranslate||a.translate(v((d-b[0])/2),v((e-b[1])/2)))},j=a.match(i)[1],a=Ib[j],g=this.image(j).attr({x:b,y:c}),g.isImg=!0,a?k(g,a):(g.attr({width:0,height:0}),$("img",{onload:function(){k(g,Ib[j]=[this.width,this.height])},src:j}));return g},symbols:{circle:function(a,b,c,d){var e=0.166*c;return["M",a+c/2,b,"C",a+c+e,b,a+c+e,b+d,a+c/2,b+d,"C",a-e,b+d,a-e,b,a+c/2,b,"Z"]},square:function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c,b+d,a,b+ d,"Z"]},triangle:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d,a,b+d,"Z"]},"triangle-down":function(a,b,c,d){return["M",a,b,"L",a+c,b,a+c/2,b+d,"Z"]},diamond:function(a,b,c,d){return["M",a+c/2,b,"L",a+c,b+d/2,a+c/2,b+d,a,b+d/2,"Z"]},arc:function(a,b,c,d,e){var f=e.start,c=e.r||c||d,g=e.end-0.001,d=e.innerR,h=e.open,i=aa(f),j=fa(f),k=aa(g),g=fa(g),e=e.end-f<na?0:1;return["M",a+c*i,b+c*j,"A",c,c,0,e,1,a+c*k,b+c*g,h?"M":"L",a+d*k,b+d*g,"A",d,d,0,e,0,a+d*i,b+d*j,h?"":"Z"]},callout:function(a,b,c,d, e){var f=C(e&&e.r||0,c,d),g=f+6,h=e&&e.anchorX,i=e&&e.anchorY,e=v(e.strokeWidth||0)%2/2;a+=e;b+=e;e=["M",a+f,b,"L",a+c-f,b,"C",a+c,b,a+c,b,a+c,b+f,"L",a+c,b+d-f,"C",a+c,b+d,a+c,b+d,a+c-f,b+d,"L",a+f,b+d,"C",a,b+d,a,b+d,a,b+d-f,"L",a,b+f,"C",a,b,a,b,a+f,b];h&&h>c&&i>b+g&&i<b+d-g?e.splice(13,3,"L",a+c,i-6,a+c+6,i,a+c,i+6,a+c,b+d-f):h&&h<0&&i>b+g&&i<b+d-g?e.splice(33,3,"L",a,i+6,a-6,i,a,i-6,a,b+f):i&&i>d&&h>a+g&&h<a+c-g?e.splice(23,3,"L",h+6,b+d,h,b+d+6,h-6,b+d,a+f,b+d):i&&i<0&&h>a+g&&h<a+c-g&&e.splice(3, 3,"L",h-6,b,h,b-6,h+6,b,c-f,b);return e}},clipRect:function(a,b,c,d){var e="highcharts-"+tb++,f=this.createElement("clipPath").attr({id:e}).add(this.defs),a=this.rect(a,b,c,d,0).add(f);a.id=e;a.clipPath=f;return a},text:function(a,b,c,d){var e=ga||!ba&&this.forExport,f={};if(d&&!this.forExport)return this.html(a,b,c);f.x=Math.round(b||0);if(c)f.y=Math.round(c);if(a||a===0)f.text=a;a=this.createElement("text").attr(f);e&&a.css({position:"absolute"});if(!d)a.xSetter=function(a,b,c){var d=c.getElementsByTagName("tspan"), e,f=c.getAttribute(b),m;for(m=0;m<d.length;m++)e=d[m],e.getAttribute(b)===f&&e.setAttribute(b,a);c.setAttribute(b,a)};return a},fontMetrics:function(a,b){a=a||this.style.fontSize;if(b&&H.getComputedStyle)b=b.element||b,a=H.getComputedStyle(b,"").fontSize;var a=/px/.test(a)?z(a):/em/.test(a)?parseFloat(a)*12:12,c=a<24?a+4:v(a*1.2),d=v(c*0.8);return{h:c,b:d,f:a}},label:function(a,b,c,d,e,f,g,h,i){function j(){var a,b;a=o.element.style;E=(u===void 0||wb===void 0||n.styles.textAlign)&&o.textStr&&o.getBBox(); n.width=(u||E.width||0)+2*D+jb;n.height=(wb||E.height||0)+2*D;R=D+m.fontMetrics(a&&a.fontSize,o).b;if(z){if(!p)a=v(-I*D),b=h?-R:0,n.box=p=d?m.symbol(d,a,b,n.width,n.height,y):m.rect(a,b,n.width,n.height,0,y[Pb]),p.attr("fill",P).add(n);p.isImg||p.attr(r({width:v(n.width),height:v(n.height)},y));y=null}}function k(){var a=n.styles,a=a&&a.textAlign,b=jb+D*(1-I),c;c=h?0:R;if(s(u)&&E&&(a==="center"||a==="right"))b+={center:0.5,right:1}[a]*(u-E.width);if(b!==o.x||c!==o.y)o.attr("x",b),c!==t&&o.attr("y", c);o.x=b;o.y=c}function l(a,b){p?p.attr(a,b):y[a]=b}var m=this,n=m.g(i),o=m.text("",0,0,g).attr({zIndex:1}),p,E,I=0,D=3,jb=0,u,wb,xb,x,Jb=0,y={},R,z;n.onAdd=function(){o.add(n);n.attr({text:a||"",x:b,y:c});p&&s(e)&&n.attr({anchorX:e,anchorY:f})};n.widthSetter=function(a){u=a};n.heightSetter=function(a){wb=a};n.paddingSetter=function(a){s(a)&&a!==D&&(D=a,k())};n.paddingLeftSetter=function(a){s(a)&&a!==jb&&(jb=a,k())};n.alignSetter=function(a){I={left:0,center:0.5,right:1}[a]};n.textSetter=function(a){a!== t&&o.textSetter(a);j();k()};n["stroke-widthSetter"]=function(a,b){a&&(z=!0);Jb=a%2/2;l(b,a)};n.strokeSetter=n.fillSetter=n.rSetter=function(a,b){b==="fill"&&a&&(z=!0);l(b,a)};n.anchorXSetter=function(a,b){e=a;l(b,a+Jb-xb)};n.anchorYSetter=function(a,b){f=a;l(b,a-x)};n.xSetter=function(a){n.x=a;I&&(a-=I*((u||E.width)+D));xb=v(a);n.attr("translateX",xb)};n.ySetter=function(a){x=n.y=v(a);n.attr("translateY",x)};var C=n.css;return r(n,{css:function(a){if(a){var b={},a=w(a);q(n.textProps,function(c){a[c]!== t&&(b[c]=a[c],delete a[c])});o.css(b)}return C.call(n,a)},getBBox:function(){return{width:E.width+2*D,height:E.height+2*D,x:E.x-D,y:E.y-D}},shadow:function(a){p&&p.shadow(a);return n},destroy:function(){X(n.element,"mouseenter");X(n.element,"mouseleave");o&&(o=o.destroy());p&&(p=p.destroy());G.prototype.destroy.call(n);n=m=j=k=l=null}})}};Ya=ta;r(G.prototype,{htmlCss:function(a){var b=this.element;if(b=a&&b.tagName==="SPAN"&&a.width)delete a.width,this.textWidth=b,this.updateTransform();this.styles= r(this.styles,a);A(this.element,a);return this},htmlGetBBox:function(){var a=this.element,b=this.bBox;if(!b){if(a.nodeName==="text")a.style.position="absolute";b=this.bBox={x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}}return b},htmlUpdateTransform:function(){if(this.added){var a=this.renderer,b=this.element,c=this.translateX||0,d=this.translateY||0,e=this.x||0,f=this.y||0,g=this.textAlign||"left",h={left:0,center:0.5,right:1}[g],i=this.shadows;A(b,{marginLeft:c,marginTop:d}); i&&q(i,function(a){A(a,{marginLeft:c+1,marginTop:d+1})});this.inverted&&q(b.childNodes,function(c){a.invertChild(c,b)});if(b.tagName==="SPAN"){var j=this.rotation,k,l=z(this.textWidth),m=[j,g,b.innerHTML,this.textWidth].join(",");if(m!==this.cTT){k=a.fontMetrics(b.style.fontSize).b;s(j)&&this.setSpanRotation(j,h,k);i=p(this.elemWidth,b.offsetWidth);if(i>l&&/[ \-]/.test(b.textContent||b.innerText))A(b,{width:l+"px",display:"block",whiteSpace:"normal"}),i=l;this.getSpanCorrection(i,k,h,j,g)}A(b,{left:e+ (this.xCorr||0)+"px",top:f+(this.yCorr||0)+"px"});if(sb)k=b.offsetHeight;this.cTT=m}}else this.alignOnAdd=!0},setSpanRotation:function(a,b,c){var d={},e=Aa?"-ms-transform":sb?"-webkit-transform":Ta?"MozTransform":Gb?"-o-transform":"";d[e]=d.transform="rotate("+a+"deg)";d[e+(Ta?"Origin":"-origin")]=d.transformOrigin=b*100+"% "+c+"px";A(this.element,d)},getSpanCorrection:function(a,b,c){this.xCorr=-a*c;this.yCorr=-b}});r(ta.prototype,{html:function(a,b,c){var d=this.createElement("span"),e=d.element, f=d.renderer;d.textSetter=function(a){a!==e.innerHTML&&delete this.bBox;e.innerHTML=this.textStr=a};d.xSetter=d.ySetter=d.alignSetter=d.rotationSetter=function(a,b){b==="align"&&(b="textAlign");d[b]=a;d.htmlUpdateTransform()};d.attr({text:a,x:v(b),y:v(c)}).css({position:"absolute",whiteSpace:"nowrap",fontFamily:this.style.fontFamily,fontSize:this.style.fontSize});d.css=d.htmlCss;if(f.isSVG)d.add=function(a){var b,c=f.box.parentNode,j=[];if(this.parentGroup=a){if(b=a.div,!b){for(;a;)j.push(a),a=a.parentGroup; q(j.reverse(),function(a){var d;b=a.div=a.div||$(Ja,{className:F(a.element,"class")},{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px"},b||c);d=b.style;r(a,{translateXSetter:function(b,c){d.left=b+"px";a[c]=b;a.doTransform=!0},translateYSetter:function(b,c){d.top=b+"px";a[c]=b;a.doTransform=!0},visibilitySetter:function(a,b){d[b]=a}})})}}else b=c;b.appendChild(e);d.added=!0;d.alignOnAdd&&d.htmlUpdateTransform();return d};return d}});var Z;if(!ba&&!ga){Z={init:function(a, b){var c=["<",b,' filled="f" stroked="f"'],d=["position: ","absolute",";"],e=b===Ja;(b==="shape"||e)&&d.push("left:0;top:0;width:1px;height:1px;");d.push("visibility: ",e?"hidden":"visible");c.push(' style="',d.join(""),'"/>');if(b)c=e||b==="span"||b==="img"?c.join(""):a.prepVML(c),this.element=$(c);this.renderer=a},add:function(a){var b=this.renderer,c=this.element,d=b.box,d=a?a.element||a:d;a&&a.inverted&&b.invertChild(c,d);d.appendChild(c);this.added=!0;this.alignOnAdd&&!this.deferUpdateTransform&& this.updateTransform();if(this.onAdd)this.onAdd();return this},updateTransform:G.prototype.htmlUpdateTransform,setSpanRotation:function(){var a=this.rotation,b=aa(a*Ca),c=fa(a*Ca);A(this.element,{filter:a?["progid:DXImageTransform.Microsoft.Matrix(M11=",b,", M12=",-c,", M21=",c,", M22=",b,", sizingMethod='auto expand')"].join(""):P})},getSpanCorrection:function(a,b,c,d,e){var f=d?aa(d*Ca):1,g=d?fa(d*Ca):0,h=p(this.elemHeight,this.element.offsetHeight),i;this.xCorr=f<0&&-a;this.yCorr=g<0&&-h;i=f*g< 0;this.xCorr+=g*b*(i?1-c:c);this.yCorr-=f*b*(d?i?c:1-c:1);e&&e!=="left"&&(this.xCorr-=a*c*(f<0?-1:1),d&&(this.yCorr-=h*c*(g<0?-1:1)),A(this.element,{textAlign:e}))},pathToVML:function(a){for(var b=a.length,c=[];b--;)if(ia(a[b]))c[b]=v(a[b]*10)-5;else if(a[b]==="Z")c[b]="x";else if(c[b]=a[b],a.isArc&&(a[b]==="wa"||a[b]==="at"))c[b+5]===c[b+7]&&(c[b+7]+=a[b+7]>a[b+5]?1:-1),c[b+6]===c[b+8]&&(c[b+8]+=a[b+8]>a[b+6]?1:-1);return c.join(" ")||"x"},clip:function(a){var b=this,c;a?(c=a.members,ka(c,b),c.push(b), b.destroyClip=function(){ka(c,b)},a=a.getCSS(b)):(b.destroyClip&&b.destroyClip(),a={clip:gb?"inherit":"rect(auto)"});return b.css(a)},css:G.prototype.htmlCss,safeRemoveChild:function(a){a.parentNode&&Pa(a)},destroy:function(){this.destroyClip&&this.destroyClip();return G.prototype.destroy.apply(this)},on:function(a,b){this.element["on"+a]=function(){var a=H.event;a.target=a.srcElement;b(a)};return this},cutOffPath:function(a,b){var c,a=a.split(/[ ,]/);c=a.length;if(c===9||c===11)a[c-4]=a[c-2]=z(a[c- 2])-10*b;return a.join(" ")},shadow:function(a,b,c){var d=[],e,f=this.element,g=this.renderer,h,i=f.style,j,k=f.path,l,m,n,o;k&&typeof k.value!=="string"&&(k="x");m=k;if(a){n=p(a.width,3);o=(a.opacity||0.15)/n;for(e=1;e<=3;e++){l=n*2+1-2*e;c&&(m=this.cutOffPath(k.value,l+0.5));j=['<shape isShadow="true" strokeweight="',l,'" filled="false" path="',m,'" coordsize="10 10" style="',f.style.cssText,'" />'];h=$(g.prepVML(j),null,{left:z(i.left)+p(a.offsetX,1),top:z(i.top)+p(a.offsetY,1)});if(c)h.cutOff= l+1;j=['<stroke color="',a.color||"black",'" opacity="',o*e,'"/>'];$(g.prepVML(j),null,null,h);b?b.element.appendChild(h):f.parentNode.insertBefore(h,f);d.push(h)}this.shadows=d}return this},updateShadows:sa,setAttr:function(a,b){gb?this.element[a]=b:this.element.setAttribute(a,b)},classSetter:function(a){this.element.className=a},dashstyleSetter:function(a,b,c){(c.getElementsByTagName("stroke")[0]||$(this.renderer.prepVML(["<stroke/>"]),null,null,c))[b]=a||"solid";this[b]=a},dSetter:function(a,b, c){var d=this.shadows,a=a||[];this.d=a.join&&a.join(" ");c.path=a=this.pathToVML(a);if(d)for(c=d.length;c--;)d[c].path=d[c].cutOff?this.cutOffPath(a,d[c].cutOff):a;this.setAttr(b,a)},fillSetter:function(a,b,c){var d=c.nodeName;if(d==="SPAN")c.style.color=a;else if(d!=="IMG")c.filled=a!==P,this.setAttr("fillcolor",this.renderer.color(a,c,b,this))},opacitySetter:sa,rotationSetter:function(a,b,c){c=c.style;this[b]=c[b]=a;c.left=-v(fa(a*Ca)+1)+"px";c.top=v(aa(a*Ca))+"px"},strokeSetter:function(a,b,c){this.setAttr("strokecolor", this.renderer.color(a,c,b))},"stroke-widthSetter":function(a,b,c){c.stroked=!!a;this[b]=a;ia(a)&&(a+="px");this.setAttr("strokeweight",a)},titleSetter:function(a,b){this.setAttr(b,a)},visibilitySetter:function(a,b,c){a==="inherit"&&(a="visible");this.shadows&&q(this.shadows,function(c){c.style[b]=a});c.nodeName==="DIV"&&(a=a==="hidden"?"-999em":0,gb||(c.style[b]=a?"visible":"hidden"),b="top");c.style[b]=a},xSetter:function(a,b,c){this[b]=a;b==="x"?b="left":b==="y"&&(b="top");this.updateClipping?(this[b]= a,this.updateClipping()):c.style[b]=a},zIndexSetter:function(a,b,c){c.style[b]=a}};S.VMLElement=Z=la(G,Z);Z.prototype.ySetter=Z.prototype.widthSetter=Z.prototype.heightSetter=Z.prototype.xSetter;var ha={Element:Z,isIE8:wa.indexOf("MSIE 8.0")>-1,init:function(a,b,c,d){var e;this.alignedObjects=[];d=this.createElement(Ja).css(r(this.getStyle(d),{position:"relative"}));e=d.element;a.appendChild(d.element);this.isVML=!0;this.box=e;this.boxWrapper=d;this.cache={};this.setSize(b,c,!1);if(!x.namespaces.hcv){x.namespaces.add("hcv", "urn:schemas-microsoft-com:vml");try{x.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}catch(f){x.styleSheets[0].cssText+="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}}},isHidden:function(){return!this.box.offsetWidth},clipRect:function(a,b,c,d){var e=this.createElement(),f=da(a);return r(e,{members:[],left:(f?a.x:a)+1,top:(f?a.y:b)+1,width:(f?a.width: c)-1,height:(f?a.height:d)-1,getCSS:function(a){var b=a.element,c=b.nodeName,a=a.inverted,d=this.top-(c==="shape"?b.offsetTop:0),e=this.left,b=e+this.width,f=d+this.height,d={clip:"rect("+v(a?e:d)+"px,"+v(a?f:b)+"px,"+v(a?b:f)+"px,"+v(a?d:e)+"px)"};!a&&gb&&c==="DIV"&&r(d,{width:b+"px",height:f+"px"});return d},updateClipping:function(){q(e.members,function(a){a.element&&a.css(e.getCSS(a))})}})},color:function(a,b,c,d){var e=this,f,g=/^rgba/,h,i,j=P;a&&a.linearGradient?i="gradient":a&&a.radialGradient&& (i="pattern");if(i){var k,l,m=a.linearGradient||a.radialGradient,n,o,p,E,I,D="",a=a.stops,u,s=[],t=function(){h=['<fill colors="'+s.join(",")+'" opacity="',p,'" o:opacity2="',o,'" type="',i,'" ',D,'focus="100%" method="any" />'];$(e.prepVML(h),null,null,b)};n=a[0];u=a[a.length-1];n[0]>0&&a.unshift([0,n[1]]);u[0]<1&&a.push([1,u[1]]);q(a,function(a,b){g.test(a[1])?(f=ya(a[1]),k=f.get("rgb"),l=f.get("a")):(k=a[1],l=1);s.push(a[0]*100+"% "+k);b?(p=l,E=k):(o=l,I=k)});if(c==="fill")if(i==="gradient")c= m.x1||m[0]||0,a=m.y1||m[1]||0,n=m.x2||m[2]||0,m=m.y2||m[3]||0,D='angle="'+(90-V.atan((m-a)/(n-c))*180/na)+'"',t();else{var j=m.r,r=j*2,v=j*2,x=m.cx,y=m.cy,R=b.radialReference,w,j=function(){R&&(w=d.getBBox(),x+=(R[0]-w.x)/w.width-0.5,y+=(R[1]-w.y)/w.height-0.5,r*=R[2]/w.width,v*=R[2]/w.height);D='src="'+L.global.VMLRadialGradientURL+'" size="'+r+","+v+'" origin="0.5,0.5" position="'+x+","+y+'" color2="'+I+'" ';t()};d.added?j():d.onAdd=j;j=E}else j=k}else if(g.test(a)&&b.tagName!=="IMG")f=ya(a),h= ["<",c,' opacity="',f.get("a"),'"/>'],$(this.prepVML(h),null,null,b),j=f.get("rgb");else{j=b.getElementsByTagName(c);if(j.length)j[0].opacity=1,j[0].type="solid";j=a}return j},prepVML:function(a){var b=this.isIE8,a=a.join("");b?(a=a.replace("/>",' xmlns="urn:schemas-microsoft-com:vml" />'),a=a.indexOf('style="')===-1?a.replace("/>",' style="display:inline-block;behavior:url(#default#VML);" />'):a.replace('style="','style="display:inline-block;behavior:url(#default#VML);')):a=a.replace("<","<hcv:"); return a},text:ta.prototype.html,path:function(a){var b={coordsize:"10 10"};La(a)?b.d=a:da(a)&&r(b,a);return this.createElement("shape").attr(b)},circle:function(a,b,c){var d=this.symbol("circle");if(da(a))c=a.r,b=a.y,a=a.x;d.isCircle=!0;d.r=c;return d.attr({x:a,y:b})},g:function(a){var b;a&&(b={className:"highcharts-"+a,"class":"highcharts-"+a});return this.createElement(Ja).attr(b)},image:function(a,b,c,d,e){var f=this.createElement("img").attr({src:a});arguments.length>1&&f.attr({x:b,y:c,width:d, height:e});return f},createElement:function(a){return a==="rect"?this.symbol(a):ta.prototype.createElement.call(this,a)},invertChild:function(a,b){var c=this,d=b.style,e=a.tagName==="IMG"&&a.style;A(a,{flip:"x",left:z(d.width)-(e?z(e.top):1),top:z(d.height)-(e?z(e.left):1),rotation:-90});q(a.childNodes,function(b){c.invertChild(b,a)})},symbols:{arc:function(a,b,c,d,e){var f=e.start,g=e.end,h=e.r||c||d,c=e.innerR,d=aa(f),i=fa(f),j=aa(g),k=fa(g);if(g-f===0)return["x"];f=["wa",a-h,b-h,a+h,b+h,a+h*d, b+h*i,a+h*j,b+h*k];e.open&&!c&&f.push("e","M",a,b);f.push("at",a-c,b-c,a+c,b+c,a+c*j,b+c*k,a+c*d,b+c*i,"x","e");f.isArc=!0;return f},circle:function(a,b,c,d,e){e&&(c=d=2*e.r);e&&e.isCircle&&(a-=c/2,b-=d/2);return["wa",a,b,a+c,b+d,a+c,b+d/2,a+c,b+d/2,"e"]},rect:function(a,b,c,d,e){return ta.prototype.symbols[!s(e)||!e.r?"square":"callout"].call(0,a,b,c,d,e)}}};S.VMLRenderer=Z=function(){this.init.apply(this,arguments)};Z.prototype=w(ta.prototype,ha);Ya=Z}ta.prototype.measureSpanWidth=function(a,b){var c= x.createElement("span"),d;d=x.createTextNode(a);c.appendChild(d);A(c,b);this.box.appendChild(c);d=c.offsetWidth;Pa(c);return d};var Lb;if(ga)S.CanVGRenderer=Z=function(){xa="http://www.w3.org/1999/xhtml"},Z.prototype.symbols={},Lb=function(){function a(){var a=b.length,d;for(d=0;d<a;d++)b[d]();b=[]}var b=[];return{push:function(c,d){b.length===0&&Qb(d,a);b.push(c)}}}(),Ya=Z;Sa.prototype={addLabel:function(){var a=this.axis,b=a.options,c=a.chart,d=a.horiz,e=a.categories,f=a.names,g=this.pos,h=b.labels, i=h.rotation,j=a.tickPositions,d=d&&e&&!h.step&&!h.staggerLines&&!h.rotation&&c.plotWidth/j.length||!d&&(c.margin[3]||c.chartWidth*0.33),k=g===j[0],l=g===j[j.length-1],m,f=e?p(e[g],f[g],g):g,e=this.label,n=j.info;a.isDatetimeAxis&&n&&(m=b.dateTimeLabelFormats[n.higherRanks[g]||n.unitName]);this.isFirst=k;this.isLast=l;b=a.labelFormatter.call({axis:a,chart:c,isFirst:k,isLast:l,dateTimeLabelFormat:m,value:a.isLog?ea(ja(f)):f});g=d&&{width:u(1,v(d-2*(h.padding||10)))+"px"};g=r(g,h.style);if(s(e))e&& e.attr({text:b}).css(g);else{m={align:a.labelAlign};if(ia(i))m.rotation=i;if(d&&h.ellipsis)g.HcHeight=a.len/j.length;this.label=e=s(b)&&h.enabled?c.renderer.text(b,0,0,h.useHTML).attr(m).css(g).add(a.labelGroup):null;a.tickBaseline=c.renderer.fontMetrics(h.style.fontSize,e).b;i&&a.side===2&&(a.tickBaseline*=aa(i*Ca))}this.yOffset=e?p(h.y,a.tickBaseline+(a.side===2?8:-(e.getBBox().height/2))):0},getLabelSize:function(){var a=this.label,b=this.axis;return a?a.getBBox()[b.horiz?"height":"width"]:0}, getLabelSides:function(){var a=this.label.getBBox(),b=this.axis,c=b.horiz,d=b.options.labels,a=c?a.width:a.height,b=c?d.x-a*{left:0,center:0.5,right:1}[b.labelAlign]:0;return[b,c?a+b:a]},handleOverflow:function(a,b){var c=!0,d=this.axis,e=this.isFirst,f=this.isLast,g=d.horiz?b.x:b.y,h=d.reversed,i=d.tickPositions,j=this.getLabelSides(),k=j[0],j=j[1],l,m,n,o=this.label.line||0;l=d.labelEdge;m=d.justifyLabels&&(e||f);l[o]===t||g+k>l[o]?l[o]=g+j:m||(c=!1);if(m){l=(m=d.justifyToPlot)?d.pos:0;m=m?l+d.len: d.chart.chartWidth;do a+=e?1:-1,n=d.ticks[i[a]];while(i[a]&&(!n||!n.label||n.label.line!==o));d=n&&n.label.xy&&n.label.xy.x+n.getLabelSides()[e?0:1];e&&!h||f&&h?g+k<l&&(g=l-k,n&&g+j>d&&(c=!1)):g+j>m&&(g=m-j,n&&g+k<d&&(c=!1));b.x=g}return c},getPosition:function(a,b,c,d){var e=this.axis,f=e.chart,g=d&&f.oldChartHeight||f.chartHeight;return{x:a?e.translate(b+c,null,null,d)+e.transB:e.left+e.offset+(e.opposite?(d&&f.oldChartWidth||f.chartWidth)-e.right-e.left:0),y:a?g-e.bottom+e.offset-(e.opposite?e.height: 0):g-e.translate(b+c,null,null,d)-e.transB}},getLabelPosition:function(a,b,c,d,e,f,g,h){var i=this.axis,j=i.transA,k=i.reversed,l=i.staggerLines,a=a+e.x-(f&&d?f*j*(k?-1:1):0),b=b+this.yOffset-(f&&!d?f*j*(k?1:-1):0);if(l)c.line=g/(h||1)%l,b+=c.line*(i.labelOffset/l);return{x:a,y:b}},getMarkPath:function(a,b,c,d,e,f){return f.crispLine(["M",a,b,"L",a+(e?0:-c),b+(e?c:0)],d)},render:function(a,b,c){var d=this.axis,e=d.options,f=d.chart.renderer,g=d.horiz,h=this.type,i=this.label,j=this.pos,k=e.labels, l=this.gridLine,m=h?h+"Grid":"grid",n=h?h+"Tick":"tick",o=e[m+"LineWidth"],q=e[m+"LineColor"],E=e[m+"LineDashStyle"],I=e[n+"Length"],m=e[n+"Width"]||0,D=e[n+"Color"],u=e[n+"Position"],n=this.mark,s=k.step,r=!0,v=d.tickmarkOffset,w=this.getPosition(g,j,v,b),x=w.x,w=w.y,y=g&&x===d.pos+d.len||!g&&w===d.pos?-1:1,c=p(c,1);this.isActive=!0;if(o){j=d.getPlotLinePath(j+v,o*y,b,!0);if(l===t){l={stroke:q,"stroke-width":o};if(E)l.dashstyle=E;if(!h)l.zIndex=1;if(b)l.opacity=0;this.gridLine=l=o?f.path(j).attr(l).add(d.gridGroup): null}if(!b&&l&&j)l[this.isNew?"attr":"animate"]({d:j,opacity:c})}if(m&&I)u==="inside"&&(I=-I),d.opposite&&(I=-I),h=this.getMarkPath(x,w,I,m*y,g,f),n?n.animate({d:h,opacity:c}):this.mark=f.path(h).attr({stroke:D,"stroke-width":m,opacity:c}).add(d.axisGroup);if(i&&!isNaN(x))i.xy=w=this.getLabelPosition(x,w,i,g,k,v,a,s),this.isFirst&&!this.isLast&&!p(e.showFirstLabel,1)||this.isLast&&!this.isFirst&&!p(e.showLastLabel,1)?r=!1:!d.isRadial&&!k.step&&!k.rotation&&!b&&c!==0&&(r=this.handleOverflow(a,w)), s&&a%s&&(r=!1),r&&!isNaN(w.y)?(w.opacity=c,i[this.isNew?"attr":"animate"](w),this.isNew=!1):i.attr("y",-9999)},destroy:function(){Oa(this,this.axis)}};S.PlotLineOrBand=function(a,b){this.axis=a;if(b)this.options=b,this.id=b.id};S.PlotLineOrBand.prototype={render:function(){var a=this,b=a.axis,c=b.horiz,d=(b.pointRange||0)/2,e=a.options,f=e.label,g=a.label,h=e.width,i=e.to,j=e.from,k=s(j)&&s(i),l=e.value,m=e.dashStyle,n=a.svgElem,o=[],p,q=e.color,I=e.zIndex,D=e.events,r={},t=b.chart.renderer;b.isLog&& (j=za(j),i=za(i),l=za(l));if(h){if(o=b.getPlotLinePath(l,h),r={stroke:q,"stroke-width":h},m)r.dashstyle=m}else if(k){j=u(j,b.min-d);i=C(i,b.max+d);o=b.getPlotBandPath(j,i,e);if(q)r.fill=q;if(e.borderWidth)r.stroke=e.borderColor,r["stroke-width"]=e.borderWidth}else return;if(s(I))r.zIndex=I;if(n)if(o)n.animate({d:o},null,n.onGetPath);else{if(n.hide(),n.onGetPath=function(){n.show()},g)a.label=g=g.destroy()}else if(o&&o.length&&(a.svgElem=n=t.path(o).attr(r).add(),D))for(p in d=function(b){n.on(b,function(c){D[b].apply(a, [c])})},D)d(p);if(f&&s(f.text)&&o&&o.length&&b.width>0&&b.height>0){f=w({align:c&&k&&"center",x:c?!k&&4:10,verticalAlign:!c&&k&&"middle",y:c?k?16:10:k?6:-4,rotation:c&&!k&&90},f);if(!g){r={align:f.textAlign||f.align,rotation:f.rotation};if(s(I))r.zIndex=I;a.label=g=t.text(f.text,0,0,f.useHTML).attr(r).css(f.style).add()}b=[o[1],o[4],k?o[6]:o[1]];k=[o[2],o[5],k?o[7]:o[2]];o=Na(b);c=Na(k);g.align(f,!1,{x:o,y:c,width:Ba(b)-o,height:Ba(k)-c});g.show()}else g&&g.hide();return a},destroy:function(){ka(this.axis.plotLinesAndBands, this);delete this.axis;Oa(this)}};ma.prototype={defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,gridLineColor:"#C0C0C0",labels:M,lineColor:"#C0D0E0",lineWidth:1,minPadding:0.01,maxPadding:0.01,minorGridLineColor:"#E0E0E0",minorGridLineWidth:1,minorTickColor:"#A0A0A0",minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:!1,tickColor:"#C0D0E0",tickLength:10, tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",tickWidth:1,title:{align:"middle",style:{color:"#707070"}},type:"linear"},defaultYAxisOptions:{endOnTick:!0,gridLineWidth:1,tickPixelInterval:72,showLastLabel:!0,labels:{x:-8,y:3},lineWidth:0,maxPadding:0.05,minPadding:0.05,startOnTick:!0,tickWidth:0,title:{rotation:270,text:"Values"},stackLabels:{enabled:!1,formatter:function(){return Ga(this.total,-1)},style:M.style}},defaultLeftAxisOptions:{labels:{x:-15,y:null},title:{rotation:270}}, defaultRightAxisOptions:{labels:{x:15,y:null},title:{rotation:90}},defaultBottomAxisOptions:{labels:{x:0,y:null},title:{rotation:0}},defaultTopAxisOptions:{labels:{x:0,y:-15},title:{rotation:0}},init:function(a,b){var c=b.isX;this.horiz=a.inverted?!c:c;this.coll=(this.isXAxis=c)?"xAxis":"yAxis";this.opposite=b.opposite;this.side=b.side||(this.horiz?this.opposite?0:2:this.opposite?1:3);this.setOptions(b);var d=this.options,e=d.type;this.labelFormatter=d.labels.formatter||this.defaultLabelFormatter; this.userOptions=b;this.minPixelPadding=0;this.chart=a;this.reversed=d.reversed;this.zoomEnabled=d.zoomEnabled!==!1;this.categories=d.categories||e==="category";this.names=[];this.isLog=e==="logarithmic";this.isDatetimeAxis=e==="datetime";this.isLinked=s(d.linkedTo);this.tickmarkOffset=this.categories&&d.tickmarkPlacement==="between"?0.5:0;this.ticks={};this.labelEdge=[];this.minorTicks={};this.plotLinesAndBands=[];this.alternateBands={};this.len=0;this.minRange=this.userMinRange=d.minRange||d.maxZoom; this.range=d.range;this.offset=d.offset||0;this.stacks={};this.oldStacks={};this.min=this.max=null;this.crosshair=p(d.crosshair,ra(a.options.tooltip.crosshairs)[c?0:1],!1);var f,d=this.options.events;Da(this,a.axes)===-1&&(c&&!this.isColorAxis?a.axes.splice(a.xAxis.length,0,this):a.axes.push(this),a[this.coll].push(this));this.series=this.series||[];if(a.inverted&&c&&this.reversed===t)this.reversed=!0;this.removePlotLine=this.removePlotBand=this.removePlotBandOrLine;for(f in d)N(this,f,d[f]);if(this.isLog)this.val2lin= za,this.lin2val=ja},setOptions:function(a){this.options=w(this.defaultOptions,this.isXAxis?{}:this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],w(L[this.coll],a))},defaultLabelFormatter:function(){var a=this.axis,b=this.value,c=a.categories,d=this.dateTimeLabelFormat,e=L.lang.numericSymbols,f=e&&e.length,g,h=a.options.labels.format,a=a.isLog?b:a.tickInterval;if(h)g=Ia(h,this);else if(c)g=b;else if(d)g= bb(d,b);else if(f&&a>=1E3)for(;f--&&g===t;)c=Math.pow(1E3,f+1),a>=c&&e[f]!==null&&(g=Ga(b/c,-1)+e[f]);g===t&&(g=Q(b)>=1E4?Ga(b,0):Ga(b,-1,t,""));return g},getSeriesExtremes:function(){var a=this,b=a.chart;a.hasVisibleSeries=!1;a.dataMin=a.dataMax=null;a.buildStacks&&a.buildStacks();q(a.series,function(c){if(c.visible||!b.options.chart.ignoreHiddenSeries){var d;d=c.options.threshold;var e;a.hasVisibleSeries=!0;a.isLog&&d<=0&&(d=null);if(a.isXAxis){if(d=c.xData,d.length)a.dataMin=C(p(a.dataMin,d[0]), Na(d)),a.dataMax=u(p(a.dataMax,d[0]),Ba(d))}else{c.getExtremes();e=c.dataMax;c=c.dataMin;if(s(c)&&s(e))a.dataMin=C(p(a.dataMin,c),c),a.dataMax=u(p(a.dataMax,e),e);if(s(d))if(a.dataMin>=d)a.dataMin=d,a.ignoreMinPadding=!0;else if(a.dataMax<d)a.dataMax=d,a.ignoreMaxPadding=!0}}})},translate:function(a,b,c,d,e,f){var g=1,h=0,i=d?this.oldTransA:this.transA,d=d?this.oldMin:this.min,j=this.minPixelPadding,e=(this.options.ordinal||this.isLog&&e)&&this.lin2val;if(!i)i=this.transA;if(c)g*=-1,h=this.len;this.reversed&& (g*=-1,h-=g*(this.sector||this.len));b?(a=a*g+h,a-=j,a=a/i+d,e&&(a=this.lin2val(a))):(e&&(a=this.val2lin(a)),f==="between"&&(f=0.5),a=g*(a-d)*i+h+g*j+(ia(f)?i*f*this.pointRange:0));return a},toPixels:function(a,b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a-(b?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a,b,c,d,e){var f=this.chart,g=this.left,h=this.top,i,j,k=c&&f.oldChartHeight||f.chartHeight,l=c&&f.oldChartWidth|| f.chartWidth,m;i=this.transB;e=p(e,this.translate(a,null,null,c));a=c=v(e+i);i=j=v(k-e-i);if(isNaN(e))m=!0;else if(this.horiz){if(i=h,j=k-this.bottom,a<g||a>g+this.width)m=!0}else if(a=g,c=l-this.right,i<h||i>h+this.height)m=!0;return m&&!d?null:f.renderer.crispLine(["M",a,i,"L",c,j],b||1)},getLinearTickPositions:function(a,b,c){var d,e=ea(U(b/a)*a),f=ea(Ka(c/a)*a),g=[];if(b===c&&ia(b))return[b];for(b=e;b<=f;){g.push(b);b=ea(b+a);if(b===d)break;d=b}return g},getMinorTickPositions:function(){var a= this.options,b=this.tickPositions,c=this.minorTickInterval,d=[],e;if(this.isLog){e=b.length;for(a=1;a<e;a++)d=d.concat(this.getLogTickPositions(c,b[a-1],b[a],!0))}else if(this.isDatetimeAxis&&a.minorTickInterval==="auto")d=d.concat(this.getTimeTicks(this.normalizeTimeTickInterval(c),this.min,this.max,a.startOfWeek)),d[0]<this.min&&d.shift();else for(b=this.min+(b[0]-this.min)%c;b<=this.max;b+=c)d.push(b);return d},adjustForMinRange:function(){var a=this.options,b=this.min,c=this.max,d,e=this.dataMax- this.dataMin>=this.minRange,f,g,h,i,j;if(this.isXAxis&&this.minRange===t&&!this.isLog)s(a.min)||s(a.max)?this.minRange=null:(q(this.series,function(a){i=a.xData;for(g=j=a.xIncrement?1:i.length-1;g>0;g--)if(h=i[g]-i[g-1],f===t||h<f)f=h}),this.minRange=C(f*5,this.dataMax-this.dataMin));if(c-b<this.minRange){var k=this.minRange;d=(k-c+b)/2;d=[b-d,p(a.min,b-d)];if(e)d[2]=this.dataMin;b=Ba(d);c=[b+k,p(a.max,b+k)];if(e)c[2]=this.dataMax;c=Na(c);c-b<k&&(d[0]=c-k,d[1]=p(a.min,c-k),b=Ba(d))}this.min=b;this.max= c},setAxisTranslation:function(a){var b=this,c=b.max-b.min,d=b.axisPointRange||0,e,f=0,g=0,h=b.linkedParent,i=!!b.categories,j=b.transA;if(b.isXAxis||i||d)h?(f=h.minPointOffset,g=h.pointRangePadding):q(b.series,function(a){var h=i?1:b.isXAxis?a.pointRange:b.axisPointRange||0,j=a.options.pointPlacement,n=a.closestPointRange;h>c&&(h=0);d=u(d,h);f=u(f,Fa(j)?0:h/2);g=u(g,j==="on"?0:h);!a.noSharedTooltip&&s(n)&&(e=s(e)?C(e,n):n)}),h=b.ordinalSlope&&e?b.ordinalSlope/e:1,b.minPointOffset=f*=h,b.pointRangePadding= g*=h,b.pointRange=C(d,c),b.closestPointRange=e;if(a)b.oldTransA=j;b.translationSlope=b.transA=j=b.len/(c+g||1);b.transB=b.horiz?b.left:b.bottom;b.minPixelPadding=j*f},setTickPositions:function(a){var b=this,c=b.chart,d=b.options,e=d.startOnTick,f=d.endOnTick,g=b.isLog,h=b.isDatetimeAxis,i=b.isXAxis,j=b.isLinked,k=b.options.tickPositioner,l=d.maxPadding,m=d.minPadding,n=d.tickInterval,o=d.minTickInterval,Y=d.tickPixelInterval,E,I=b.categories;j?(b.linkedParent=c[b.coll][d.linkedTo],c=b.linkedParent.getExtremes(), b.min=p(c.min,c.dataMin),b.max=p(c.max,c.dataMax),d.type!==b.linkedParent.options.type&&oa(11,1)):(b.min=p(b.userMin,d.min,b.dataMin),b.max=p(b.userMax,d.max,b.dataMax));if(g)!a&&C(b.min,p(b.dataMin,b.min))<=0&&oa(10,1),b.min=ea(za(b.min)),b.max=ea(za(b.max));if(b.range&&s(b.max))b.userMin=b.min=u(b.min,b.max-b.range),b.userMax=b.max,b.range=null;b.beforePadding&&b.beforePadding();b.adjustForMinRange();if(!I&&!b.axisPointRange&&!b.usePercentage&&!j&&s(b.min)&&s(b.max)&&(c=b.max-b.min)){if(!s(d.min)&& !s(b.userMin)&&m&&(b.dataMin<0||!b.ignoreMinPadding))b.min-=c*m;if(!s(d.max)&&!s(b.userMax)&&l&&(b.dataMax>0||!b.ignoreMaxPadding))b.max+=c*l}if(ia(d.floor))b.min=u(b.min,d.floor);if(ia(d.ceiling))b.max=C(b.max,d.ceiling);b.min===b.max||b.min===void 0||b.max===void 0?b.tickInterval=1:j&&!n&&Y===b.linkedParent.options.tickPixelInterval?b.tickInterval=b.linkedParent.tickInterval:(b.tickInterval=p(n,I?1:(b.max-b.min)*Y/u(b.len,Y)),!s(n)&&b.len<Y&&!this.isRadial&&!this.isLog&&!I&&e&&f&&(E=!0,b.tickInterval/= 4));i&&!a&&q(b.series,function(a){a.processData(b.min!==b.oldMin||b.max!==b.oldMax)});b.setAxisTranslation(!0);b.beforeSetTickPositions&&b.beforeSetTickPositions();if(b.postProcessTickInterval)b.tickInterval=b.postProcessTickInterval(b.tickInterval);if(b.pointRange)b.tickInterval=u(b.pointRange,b.tickInterval);if(!n&&b.tickInterval<o)b.tickInterval=o;if(!h&&!g&&!n)b.tickInterval=mb(b.tickInterval,null,lb(b.tickInterval),d);b.minorTickInterval=d.minorTickInterval==="auto"&&b.tickInterval?b.tickInterval/ 5:d.minorTickInterval;b.tickPositions=a=d.tickPositions?[].concat(d.tickPositions):k&&k.apply(b,[b.min,b.max]);if(!a)!b.ordinalPositions&&(b.max-b.min)/b.tickInterval>u(2*b.len,200)&&oa(19,!0),a=h?b.getTimeTicks(b.normalizeTimeTickInterval(b.tickInterval,d.units),b.min,b.max,d.startOfWeek,b.ordinalPositions,b.closestPointRange,!0):g?b.getLogTickPositions(b.tickInterval,b.min,b.max):b.getLinearTickPositions(b.tickInterval,b.min,b.max),E&&a.splice(1,a.length-2),b.tickPositions=a;if(!j)d=a[0],g=a[a.length- 1],h=b.minPointOffset||0,!e&&!f&&!I&&a.length===2&&a.splice(1,0,(g+d)/2),e?b.min=d:b.min-h>d&&a.shift(),f?b.max=g:b.max+h<g&&a.pop(),a.length===1&&(e=Q(b.max)>1E13?1:0.001,b.min-=e,b.max+=e)},setMaxTicks:function(){var a=this.chart,b=a.maxTicks||{},c=this.tickPositions,d=this._maxTicksKey=[this.coll,this.pos,this.len].join("-");if(!this.isLinked&&!this.isDatetimeAxis&&c&&c.length>(b[d]||0)&&this.options.alignTicks!==!1)b[d]=c.length;a.maxTicks=b},adjustTickAmount:function(){var a=this._maxTicksKey, b=this.tickPositions,c=this.chart.maxTicks;if(c&&c[a]&&!this.isDatetimeAxis&&!this.categories&&!this.isLinked&&this.options.alignTicks!==!1&&this.min!==t){var d=this.tickAmount,e=b.length;this.tickAmount=a=c[a];if(e<a){for(;b.length<a;)b.push(ea(b[b.length-1]+this.tickInterval));this.transA*=(e-1)/(a-1);this.max=b[b.length-1]}if(s(d)&&a!==d)this.isDirty=!0}},setScale:function(){var a=this.stacks,b,c,d,e;this.oldMin=this.min;this.oldMax=this.max;this.oldAxisLength=this.len;this.setAxisSize();e=this.len!== this.oldAxisLength;q(this.series,function(a){if(a.isDirtyData||a.isDirty||a.xAxis.isDirty)d=!0});if(e||d||this.isLinked||this.forceRedraw||this.userMin!==this.oldUserMin||this.userMax!==this.oldUserMax){if(!this.isXAxis)for(b in a)for(c in a[b])a[b][c].total=null,a[b][c].cum=0;this.forceRedraw=!1;this.getSeriesExtremes();this.setTickPositions();this.oldUserMin=this.userMin;this.oldUserMax=this.userMax;if(!this.isDirty)this.isDirty=e||this.min!==this.oldMin||this.max!==this.oldMax}else if(!this.isXAxis){if(this.oldStacks)a= this.stacks=this.oldStacks;for(b in a)for(c in a[b])a[b][c].cum=a[b][c].total}this.setMaxTicks()},setExtremes:function(a,b,c,d,e){var f=this,g=f.chart,c=p(c,!0),e=r(e,{min:a,max:b});K(f,"setExtremes",e,function(){f.userMin=a;f.userMax=b;f.eventArgs=e;f.isDirtyExtremes=!0;c&&g.redraw(d)})},zoom:function(a,b){var c=this.dataMin,d=this.dataMax,e=this.options;this.allowZoomOutside||(s(c)&&a<=C(c,p(e.min,c))&&(a=t),s(d)&&b>=u(d,p(e.max,d))&&(b=t));this.displayBtn=a!==t||b!==t;this.setExtremes(a,b,!1,t, {trigger:"zoom"});return!0},setAxisSize:function(){var a=this.chart,b=this.options,c=b.offsetLeft||0,d=this.horiz,e=p(b.width,a.plotWidth-c+(b.offsetRight||0)),f=p(b.height,a.plotHeight),g=p(b.top,a.plotTop),b=p(b.left,a.plotLeft+c),c=/%$/;c.test(f)&&(f=parseInt(f,10)/100*a.plotHeight);c.test(g)&&(g=parseInt(g,10)/100*a.plotHeight+a.plotTop);this.left=b;this.top=g;this.width=e;this.height=f;this.bottom=a.chartHeight-f-g;this.right=a.chartWidth-e-b;this.len=u(d?e:f,0);this.pos=d?b:g},getExtremes:function(){var a= this.isLog;return{min:a?ea(ja(this.min)):this.min,max:a?ea(ja(this.max)):this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},getThreshold:function(a){var b=this.isLog,c=b?ja(this.min):this.min,b=b?ja(this.max):this.max;c>a||a===null?a=c:b<a&&(a=b);return this.translate(a,0,1,0,1)},autoLabelAlign:function(a){a=(p(a,0)-this.side*90+720)%360;return a>15&&a<165?"right":a>195&&a<345?"left":"center"},getOffset:function(){var a=this,b=a.chart,c=b.renderer,d=a.options, e=a.tickPositions,f=a.ticks,g=a.horiz,h=a.side,i=b.inverted?[1,0,3,2][h]:h,j,k,l=0,m,n=0,o=d.title,Y=d.labels,E=0,I=b.axisOffset,b=b.clipOffset,D=[-1,1,1,-1][h],r,v=1,w=p(Y.maxStaggerLines,5),x,z,C,y,R;a.hasData=j=a.hasVisibleSeries||s(a.min)&&s(a.max)&&!!e;a.showAxis=k=j||p(d.showEmpty,!0);a.staggerLines=a.horiz&&Y.staggerLines;if(!a.axisGroup)a.gridGroup=c.g("grid").attr({zIndex:d.gridZIndex||1}).add(),a.axisGroup=c.g("axis").attr({zIndex:d.zIndex||2}).add(),a.labelGroup=c.g("axis-labels").attr({zIndex:Y.zIndex|| 7}).addClass("highcharts-"+a.coll.toLowerCase()+"-labels").add();if(j||a.isLinked){a.labelAlign=p(Y.align||a.autoLabelAlign(Y.rotation));q(e,function(b){f[b]?f[b].addLabel():f[b]=new Sa(a,b)});if(a.horiz&&!a.staggerLines&&w&&!Y.rotation){for(j=a.reversed?[].concat(e).reverse():e;v<w;){x=[];z=!1;for(r=0;r<j.length;r++)C=j[r],y=(y=f[C].label&&f[C].label.getBBox())?y.width:0,R=r%v,y&&(C=a.translate(C),x[R]!==t&&C<x[R]&&(z=!0),x[R]=C+y);if(z)v++;else break}if(v>1)a.staggerLines=v}q(e,function(b){if(h=== 0||h===2||{1:"left",3:"right"}[h]===a.labelAlign)E=u(f[b].getLabelSize(),E)});if(a.staggerLines)E*=a.staggerLines,a.labelOffset=E}else for(r in f)f[r].destroy(),delete f[r];if(o&&o.text&&o.enabled!==!1){if(!a.axisTitle)a.axisTitle=c.text(o.text,0,0,o.useHTML).attr({zIndex:7,rotation:o.rotation||0,align:o.textAlign||{low:"left",middle:"center",high:"right"}[o.align]}).addClass("highcharts-"+this.coll.toLowerCase()+"-title").css(o.style).add(a.axisGroup),a.axisTitle.isNew=!0;if(k)l=a.axisTitle.getBBox()[g? "height":"width"],m=o.offset,n=s(m)?0:p(o.margin,g?5:10);a.axisTitle[k?"show":"hide"]()}a.offset=D*p(d.offset,I[h]);c=h===2?a.tickBaseline:0;g=E+n+(E&&D*(g?p(Y.y,a.tickBaseline+8):Y.x)-c);a.axisTitleMargin=p(m,g);I[h]=u(I[h],a.axisTitleMargin+l+D*a.offset,g);b[i]=u(b[i],U(d.lineWidth/2)*2)},getLinePath:function(a){var b=this.chart,c=this.opposite,d=this.offset,e=this.horiz,f=this.left+(c?this.width:0)+d,d=b.chartHeight-this.bottom-(c?this.height:0)+d;c&&(a*=-1);return b.renderer.crispLine(["M",e? this.left:f,e?d:this.top,"L",e?b.chartWidth-this.right:f,e?d:b.chartHeight-this.bottom],a)},getTitlePosition:function(){var a=this.horiz,b=this.left,c=this.top,d=this.len,e=this.options.title,f=a?b:c,g=this.opposite,h=this.offset,i=z(e.style.fontSize||12),d={low:f+(a?0:d),middle:f+d/2,high:f+(a?d:0)}[e.align],b=(a?c+this.height:b)+(a?1:-1)*(g?-1:1)*this.axisTitleMargin+(this.side===2?i:0);return{x:a?d:b+(g?this.width:0)+h+(e.x||0),y:a?b-(g?this.height:0)+h:d+(e.y||0)}},render:function(){var a=this, b=a.horiz,c=a.reversed,d=a.chart,e=d.renderer,f=a.options,g=a.isLog,h=a.isLinked,i=a.tickPositions,j,k=a.axisTitle,l=a.ticks,m=a.minorTicks,n=a.alternateBands,o=f.stackLabels,p=f.alternateGridColor,E=a.tickmarkOffset,I=f.lineWidth,D=d.hasRendered&&s(a.oldMin)&&!isNaN(a.oldMin),r=a.hasData,u=a.showAxis,v,w=f.labels.overflow,x=a.justifyLabels=b&&w!==!1,z;a.labelEdge.length=0;a.justifyToPlot=w==="justify";q([l,m,n],function(a){for(var b in a)a[b].isActive=!1});if(r||h)if(a.minorTickInterval&&!a.categories&& q(a.getMinorTickPositions(),function(b){m[b]||(m[b]=new Sa(a,b,"minor"));D&&m[b].isNew&&m[b].render(null,!0);m[b].render(null,!1,1)}),i.length&&(j=i.slice(),(b&&c||!b&&!c)&&j.reverse(),x&&(j=j.slice(1).concat([j[0]])),q(j,function(b,c){x&&(c=c===j.length-1?0:c+1);if(!h||b>=a.min&&b<=a.max)l[b]||(l[b]=new Sa(a,b)),D&&l[b].isNew&&l[b].render(c,!0,0.1),l[b].render(c)}),E&&a.min===0&&(l[-1]||(l[-1]=new Sa(a,-1,null,!0)),l[-1].render(-1))),p&&q(i,function(b,c){if(c%2===0&&b<a.max)n[b]||(n[b]=new S.PlotLineOrBand(a)), v=b+E,z=i[c+1]!==t?i[c+1]+E:a.max,n[b].options={from:g?ja(v):v,to:g?ja(z):z,color:p},n[b].render(),n[b].isActive=!0}),!a._addedPlotLB)q((f.plotLines||[]).concat(f.plotBands||[]),function(b){a.addPlotBandOrLine(b)}),a._addedPlotLB=!0;q([l,m,n],function(a){var b,c,e=[],f=va?va.duration||500:0,g=function(){for(c=e.length;c--;)a[e[c]]&&!a[e[c]].isActive&&(a[e[c]].destroy(),delete a[e[c]])};for(b in a)if(!a[b].isActive)a[b].render(b,!1,0),a[b].isActive=!1,e.push(b);a===n||!d.hasRendered||!f?g():f&&setTimeout(g, f)});if(I)b=a.getLinePath(I),a.axisLine?a.axisLine.animate({d:b}):a.axisLine=e.path(b).attr({stroke:f.lineColor,"stroke-width":I,zIndex:7}).add(a.axisGroup),a.axisLine[u?"show":"hide"]();if(k&&u)k[k.isNew?"attr":"animate"](a.getTitlePosition()),k.isNew=!1;o&&o.enabled&&a.renderStackTotals();a.isDirty=!1},redraw:function(){this.render();q(this.plotLinesAndBands,function(a){a.render()});q(this.series,function(a){a.isDirty=!0})},destroy:function(a){var b=this,c=b.stacks,d,e=b.plotLinesAndBands;a||X(b); for(d in c)Oa(c[d]),c[d]=null;q([b.ticks,b.minorTicks,b.alternateBands],function(a){Oa(a)});for(a=e.length;a--;)e[a].destroy();q("stackTotalGroup,axisLine,axisTitle,axisGroup,cross,gridGroup,labelGroup".split(","),function(a){b[a]&&(b[a]=b[a].destroy())});this.cross&&this.cross.destroy()},drawCrosshair:function(a,b){if(this.crosshair)if((s(b)||!p(this.crosshair.snap,!0))===!1)this.hideCrosshair();else{var c,d=this.crosshair,e=d.animation;p(d.snap,!0)?s(b)&&(c=this.chart.inverted!=this.horiz?b.plotX: this.len-b.plotY):c=this.horiz?a.chartX-this.pos:this.len-a.chartY+this.pos;c=this.isRadial?this.getPlotLinePath(this.isXAxis?b.x:p(b.stackY,b.y)):this.getPlotLinePath(null,null,null,null,c);if(c===null)this.hideCrosshair();else if(this.cross)this.cross.attr({visibility:"visible"})[e?"animate":"attr"]({d:c},e);else{e={"stroke-width":d.width||1,stroke:d.color||"#C0C0C0",zIndex:d.zIndex||2};if(d.dashStyle)e.dashstyle=d.dashStyle;this.cross=this.chart.renderer.path(c).attr(e).add()}}},hideCrosshair:function(){this.cross&& this.cross.hide()}};r(ma.prototype,{getPlotBandPath:function(a,b){var c=this.getPlotLinePath(b),d=this.getPlotLinePath(a);d&&c?d.push(c[4],c[5],c[1],c[2]):d=null;return d},addPlotBand:function(a){return this.addPlotBandOrLine(a,"plotBands")},addPlotLine:function(a){return this.addPlotBandOrLine(a,"plotLines")},addPlotBandOrLine:function(a,b){var c=(new S.PlotLineOrBand(this,a)).render(),d=this.userOptions;c&&(b&&(d[b]=d[b]||[],d[b].push(a)),this.plotLinesAndBands.push(c));return c},removePlotBandOrLine:function(a){for(var b= this.plotLinesAndBands,c=this.options,d=this.userOptions,e=b.length;e--;)b[e].id===a&&b[e].destroy();q([c.plotLines||[],d.plotLines||[],c.plotBands||[],d.plotBands||[]],function(b){for(e=b.length;e--;)b[e].id===a&&ka(b,b[e])})}});ma.prototype.getTimeTicks=function(a,b,c,d){var e=[],f={},g=L.global.useUTC,h,i=new Date(b-Ra),j=a.unitRange,k=a.count;if(s(b)){j>=B.second&&(i.setMilliseconds(0),i.setSeconds(j>=B.minute?0:k*U(i.getSeconds()/k)));if(j>=B.minute)i[Bb](j>=B.hour?0:k*U(i[ob]()/k));if(j>=B.hour)i[Cb](j>= B.day?0:k*U(i[pb]()/k));if(j>=B.day)i[rb](j>=B.month?1:k*U(i[Wa]()/k));j>=B.month&&(i[Db](j>=B.year?0:k*U(i[eb]()/k)),h=i[fb]());j>=B.year&&(h-=h%k,i[Eb](h));if(j===B.week)i[rb](i[Wa]()-i[qb]()+p(d,1));b=1;Ra&&(i=new Date(i.getTime()+Ra));h=i[fb]();for(var d=i.getTime(),l=i[eb](),m=i[Wa](),n=g?Ra:(864E5+i.getTimezoneOffset()*6E4)%864E5;d<c;)e.push(d),j===B.year?d=db(h+b*k,0):j===B.month?d=db(h,l+b*k):!g&&(j===B.day||j===B.week)?d=db(h,l,m+b*k*(j===B.day?1:7)):d+=j*k,b++;e.push(d);q(vb(e,function(a){return j<= B.hour&&a%B.day===n}),function(a){f[a]="day"})}e.info=r(a,{higherRanks:f,totalRange:j*k});return e};ma.prototype.normalizeTimeTickInterval=function(a,b){var c=b||[["millisecond",[1,2,5,10,20,25,50,100,200,500]],["second",[1,2,5,10,15,30]],["minute",[1,2,5,10,15,30]],["hour",[1,2,3,4,6,8,12]],["day",[1,2]],["week",[1,2]],["month",[1,2,3,4,6]],["year",null]],d=c[c.length-1],e=B[d[0]],f=d[1],g;for(g=0;g<c.length;g++)if(d=c[g],e=B[d[0]],f=d[1],c[g+1]&&a<=(e*f[f.length-1]+B[c[g+1][0]])/2)break;e===B.year&& a<5*e&&(f=[1,2,5]);c=mb(a/e,f,d[0]==="year"?u(lb(a/e),1):1);return{unitRange:e,count:c,unitName:d[0]}};ma.prototype.getLogTickPositions=function(a,b,c,d){var e=this.options,f=this.len,g=[];if(!d)this._minorAutoInterval=null;if(a>=0.5)a=v(a),g=this.getLinearTickPositions(a,b,c);else if(a>=0.08)for(var f=U(b),h,i,j,k,l,e=a>0.3?[1,2,4]:a>0.15?[1,2,4,6,8]:[1,2,3,4,5,6,7,8,9];f<c+1&&!l;f++){i=e.length;for(h=0;h<i&&!l;h++)j=za(ja(f)*e[h]),j>b&&(!d||k<=c)&&k!==t&&g.push(k),k>c&&(l=!0),k=j}else if(b=ja(b), c=ja(c),a=e[d?"minorTickInterval":"tickInterval"],a=p(a==="auto"?null:a,this._minorAutoInterval,(c-b)*(e.tickPixelInterval/(d?5:1))/((d?f/this.tickPositions.length:f)||1)),a=mb(a,null,lb(a)),g=Ua(this.getLinearTickPositions(a,b,c),za),!d)this._minorAutoInterval=a/5;if(!d)this.tickInterval=a;return g};var Mb=S.Tooltip=function(){this.init.apply(this,arguments)};Mb.prototype={init:function(a,b){var c=b.borderWidth,d=b.style,e=z(d.padding);this.chart=a;this.options=b;this.crosshairs=[];this.now={x:0, y:0};this.isHidden=!0;this.label=a.renderer.label("",0,0,b.shape||"callout",null,null,b.useHTML,null,"tooltip").attr({padding:e,fill:b.backgroundColor,"stroke-width":c,r:b.borderRadius,zIndex:8}).css(d).css({padding:0}).add().attr({y:-9999});ga||this.label.shadow(b.shadow);this.shared=b.shared},destroy:function(){if(this.label)this.label=this.label.destroy();clearTimeout(this.hideTimer);clearTimeout(this.tooltipTimeout)},move:function(a,b,c,d){var e=this,f=e.now,g=e.options.animation!==!1&&!e.isHidden&& (Q(a-f.x)>1||Q(b-f.y)>1),h=e.followPointer||e.len>1;r(f,{x:g?(2*f.x+a)/3:a,y:g?(f.y+b)/2:b,anchorX:h?t:g?(2*f.anchorX+c)/3:c,anchorY:h?t:g?(f.anchorY+d)/2:d});e.label.attr(f);if(g)clearTimeout(this.tooltipTimeout),this.tooltipTimeout=setTimeout(function(){e&&e.move(a,b,c,d)},32)},hide:function(){var a=this,b;clearTimeout(this.hideTimer);if(!this.isHidden)b=this.chart.hoverPoints,this.hideTimer=setTimeout(function(){a.label.fadeOut();a.isHidden=!0},p(this.options.hideDelay,500)),b&&q(b,function(a){a.setState()}), this.chart.hoverPoints=null},getAnchor:function(a,b){var c,d=this.chart,e=d.inverted,f=d.plotTop,g=0,h=0,i,a=ra(a);c=a[0].tooltipPos;this.followPointer&&b&&(b.chartX===t&&(b=d.pointer.normalize(b)),c=[b.chartX-d.plotLeft,b.chartY-f]);c||(q(a,function(a){i=a.series.yAxis;g+=a.plotX;h+=(a.plotLow?(a.plotLow+a.plotHigh)/2:a.plotY)+(!e&&i?i.top-f:0)}),g/=a.length,h/=a.length,c=[e?d.plotWidth-h:g,this.shared&&!e&&a.length>1&&b?b.chartY-f:e?d.plotHeight-g:h]);return Ua(c,v)},getPosition:function(a,b,c){var d= this.chart,e=this.distance,f={},g,h=["y",d.chartHeight,b,c.plotY+d.plotTop],i=["x",d.chartWidth,a,c.plotX+d.plotLeft],j=c.ttBelow||d.inverted&&!c.negative||!d.inverted&&c.negative,k=function(a,b,c,d){var g=c<d-e,b=d+e+c<b,c=d-e-c;d+=e;if(j&&b)f[a]=d;else if(!j&&g)f[a]=c;else if(g)f[a]=c;else if(b)f[a]=d;else return!1},l=function(a,b,c,d){if(d<e||d>b-e)return!1;else f[a]=d<c/2?1:d>b-c/2?b-c-2:d-c/2},m=function(a){var b=h;h=i;i=b;g=a},n=function(){k.apply(0,h)!==!1?l.apply(0,i)===!1&&!g&&(m(!0),n()): g?f.x=f.y=0:(m(!0),n())};(d.inverted||this.len>1)&&m();n();return f},defaultFormatter:function(a){var b=this.points||ra(this),c=b[0].series,d;d=[a.tooltipHeaderFormatter(b[0])];q(b,function(a){c=a.series;d.push(c.tooltipFormatter&&c.tooltipFormatter(a)||a.point.tooltipFormatter(c.tooltipOptions.pointFormat))});d.push(a.options.footerFormat||"");return d.join("")},refresh:function(a,b){var c=this.chart,d=this.label,e=this.options,f,g,h={},i,j=[];i=e.formatter||this.defaultFormatter;var h=c.hoverPoints, k,l=this.shared;clearTimeout(this.hideTimer);this.followPointer=ra(a)[0].series.tooltipOptions.followPointer;g=this.getAnchor(a,b);f=g[0];g=g[1];l&&(!a.series||!a.series.noSharedTooltip)?(c.hoverPoints=a,h&&q(h,function(a){a.setState()}),q(a,function(a){a.setState("hover");j.push(a.getLabelConfig())}),h={x:a[0].category,y:a[0].y},h.points=j,this.len=j.length,a=a[0]):h=a.getLabelConfig();i=i.call(h,this);h=a.series;this.distance=p(h.tooltipOptions.distance,16);i===!1?this.hide():(this.isHidden&&(ab(d), d.attr("opacity",1).show()),d.attr({text:i}),k=e.borderColor||a.color||h.color||"#606060",d.attr({stroke:k}),this.updatePosition({plotX:f,plotY:g,negative:a.negative,ttBelow:a.ttBelow}),this.isHidden=!1);K(c,"tooltipRefresh",{text:i,x:f+c.plotLeft,y:g+c.plotTop,borderColor:k})},updatePosition:function(a){var b=this.chart,c=this.label,c=(this.options.positioner||this.getPosition).call(this,c.width,c.height,a);this.move(v(c.x),v(c.y),a.plotX+b.plotLeft,a.plotY+b.plotTop)},tooltipHeaderFormatter:function(a){var b= a.series,c=b.tooltipOptions,d=c.dateTimeLabelFormats,e=c.xDateFormat,f=b.xAxis,g=f&&f.options.type==="datetime"&&ia(a.key),c=c.headerFormat,f=f&&f.closestPointRange,h;if(g&&!e){if(f)for(h in B){if(B[h]>=f||B[h]<=B.day&&a.key%B[h]>0){e=d[h];break}}else e=d.day;e=e||d.year}g&&e&&(c=c.replace("{point.key}","{point.key:"+e+"}"));return Ia(c,{point:a,series:b})}};var pa;Za=x.documentElement.ontouchstart!==t;var Va=S.Pointer=function(a,b){this.init(a,b)};Va.prototype={init:function(a,b){var c=b.chart,d= c.events,e=ga?"":c.zoomType,c=a.inverted,f;this.options=b;this.chart=a;this.zoomX=f=/x/.test(e);this.zoomY=e=/y/.test(e);this.zoomHor=f&&!c||e&&c;this.zoomVert=e&&!c||f&&c;this.hasZoom=f||e;this.runChartClick=d&&!!d.click;this.pinchDown=[];this.lastValidTouch={};if(S.Tooltip&&b.tooltip.enabled)a.tooltip=new Mb(a,b.tooltip),this.followTouchMove=b.tooltip.followTouchMove;this.setDOMEvents()},normalize:function(a,b){var c,d,a=a||window.event,a=Sb(a);if(!a.target)a.target=a.srcElement;d=a.touches?a.touches.length? a.touches.item(0):a.changedTouches[0]:a;if(!b)this.chartPosition=b=Rb(this.chart.container);d.pageX===t?(c=u(a.x,a.clientX-b.left),d=a.y):(c=d.pageX-b.left,d=d.pageY-b.top);return r(a,{chartX:v(c),chartY:v(d)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};q(this.chart.axes,function(c){b[c.isXAxis?"xAxis":"yAxis"].push({axis:c,value:c.toValue(a[c.horiz?"chartX":"chartY"])})});return b},getIndex:function(a){var b=this.chart;return b.inverted?b.plotHeight+b.plotTop-a.chartY:a.chartX-b.plotLeft}, runPointActions:function(a){var b=this.chart,c=b.series,d=b.tooltip,e,f,g=b.hoverPoint,h=b.hoverSeries,i,j,k=b.chartWidth,l=this.getIndex(a);if(d&&this.options.tooltip.shared&&(!h||!h.noSharedTooltip)){f=[];i=c.length;for(j=0;j<i;j++)if(c[j].visible&&c[j].options.enableMouseTracking!==!1&&!c[j].noSharedTooltip&&c[j].singularTooltips!==!0&&c[j].tooltipPoints.length&&(e=c[j].tooltipPoints[l])&&e.series)e._dist=Q(l-e.clientX),k=C(k,e._dist),f.push(e);for(i=f.length;i--;)f[i]._dist>k&&f.splice(i,1);if(f.length&& f[0].clientX!==this.hoverX)d.refresh(f,a),this.hoverX=f[0].clientX}c=h&&h.tooltipOptions.followPointer;if(h&&h.tracker&&!c){if((e=h.tooltipPoints[l])&&e!==g)e.onMouseOver(a)}else d&&c&&!d.isHidden&&(h=d.getAnchor([{}],a),d.updatePosition({plotX:h[0],plotY:h[1]}));if(d&&!this._onDocumentMouseMove)this._onDocumentMouseMove=function(a){if(W[pa])W[pa].pointer.onDocumentMouseMove(a)},N(x,"mousemove",this._onDocumentMouseMove);q(b.axes,function(b){b.drawCrosshair(a,p(e,g))})},reset:function(a){var b=this.chart, c=b.hoverSeries,d=b.hoverPoint,e=b.tooltip,f=e&&e.shared?b.hoverPoints:d;(a=a&&e&&f)&&ra(f)[0].plotX===t&&(a=!1);if(a)e.refresh(f),d&&d.setState(d.state,!0);else{if(d)d.onMouseOut();if(c)c.onMouseOut();e&&e.hide();if(this._onDocumentMouseMove)X(x,"mousemove",this._onDocumentMouseMove),this._onDocumentMouseMove=null;q(b.axes,function(a){a.hideCrosshair()});this.hoverX=null}},scaleGroups:function(a,b){var c=this.chart,d;q(c.series,function(e){d=a||e.getPlotBox();e.xAxis&&e.xAxis.zoomEnabled&&(e.group.attr(d), e.markerGroup&&(e.markerGroup.attr(d),e.markerGroup.clip(b?c.clipRect:null)),e.dataLabelsGroup&&e.dataLabelsGroup.attr(d))});c.clipRect.attr(b||c.clipBox)},dragStart:function(a){var b=this.chart;b.mouseIsDown=a.type;b.cancelClick=!1;b.mouseDownX=this.mouseDownX=a.chartX;b.mouseDownY=this.mouseDownY=a.chartY},drag:function(a){var b=this.chart,c=b.options.chart,d=a.chartX,e=a.chartY,f=this.zoomHor,g=this.zoomVert,h=b.plotLeft,i=b.plotTop,j=b.plotWidth,k=b.plotHeight,l,m=this.mouseDownX,n=this.mouseDownY, o=c.panKey&&a[c.panKey+"Key"];d<h?d=h:d>h+j&&(d=h+j);e<i?e=i:e>i+k&&(e=i+k);this.hasDragged=Math.sqrt(Math.pow(m-d,2)+Math.pow(n-e,2));if(this.hasDragged>10){l=b.isInsidePlot(m-h,n-i);if(b.hasCartesianSeries&&(this.zoomX||this.zoomY)&&l&&!o&&!this.selectionMarker)this.selectionMarker=b.renderer.rect(h,i,f?1:j,g?1:k,0).attr({fill:c.selectionMarkerFill||"rgba(69,114,167,0.25)",zIndex:7}).add();this.selectionMarker&&f&&(d-=m,this.selectionMarker.attr({width:Q(d),x:(d>0?0:d)+m}));this.selectionMarker&& g&&(d=e-n,this.selectionMarker.attr({height:Q(d),y:(d>0?0:d)+n}));l&&!this.selectionMarker&&c.panning&&b.pan(a,c.panning)}},drop:function(a){var b=this.chart,c=this.hasPinched;if(this.selectionMarker){var d={xAxis:[],yAxis:[],originalEvent:a.originalEvent||a},e=this.selectionMarker,f=e.attr?e.attr("x"):e.x,g=e.attr?e.attr("y"):e.y,h=e.attr?e.attr("width"):e.width,i=e.attr?e.attr("height"):e.height,j;if(this.hasDragged||c)q(b.axes,function(b){if(b.zoomEnabled){var c=b.horiz,e=a.type==="touchend"?b.minPixelPadding: 0,n=b.toValue((c?f:g)+e),c=b.toValue((c?f+h:g+i)-e);!isNaN(n)&&!isNaN(c)&&(d[b.coll].push({axis:b,min:C(n,c),max:u(n,c)}),j=!0)}}),j&&K(b,"selection",d,function(a){b.zoom(r(a,c?{animation:!1}:null))});this.selectionMarker=this.selectionMarker.destroy();c&&this.scaleGroups()}if(b)A(b.container,{cursor:b._cursor}),b.cancelClick=this.hasDragged>10,b.mouseIsDown=this.hasDragged=this.hasPinched=!1,this.pinchDown=[]},onContainerMouseDown:function(a){a=this.normalize(a);a.preventDefault&&a.preventDefault(); this.dragStart(a)},onDocumentMouseUp:function(a){W[pa]&&W[pa].pointer.drop(a)},onDocumentMouseMove:function(a){var b=this.chart,c=this.chartPosition,d=b.hoverSeries,a=this.normalize(a,c);c&&d&&!this.inClass(a.target,"highcharts-tracker")&&!b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)&&this.reset()},onContainerMouseLeave:function(){var a=W[pa];if(a)a.pointer.reset(),a.pointer.chartPosition=null},onContainerMouseMove:function(a){var b=this.chart;pa=b.index;a=this.normalize(a);a.returnValue= !1;b.mouseIsDown==="mousedown"&&this.drag(a);(this.inClass(a.target,"highcharts-tracker")||b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop))&&!b.openMenu&&this.runPointActions(a)},inClass:function(a,b){for(var c;a;){if(c=F(a,"class"))if(c.indexOf(b)!==-1)return!0;else if(c.indexOf("highcharts-container")!==-1)return!1;a=a.parentNode}},onTrackerMouseOut:function(a){var b=this.chart.hoverSeries,c=(a=a.relatedTarget||a.toElement)&&a.point&&a.point.series;if(b&&!b.options.stickyTracking&&!this.inClass(a, "highcharts-tooltip")&&c!==b)b.onMouseOut()},onContainerClick:function(a){var b=this.chart,c=b.hoverPoint,d=b.plotLeft,e=b.plotTop,a=this.normalize(a);a.cancelBubble=!0;b.cancelClick||(c&&this.inClass(a.target,"highcharts-tracker")?(K(c.series,"click",r(a,{point:c})),b.hoverPoint&&c.firePointEvent("click",a)):(r(a,this.getCoordinates(a)),b.isInsidePlot(a.chartX-d,a.chartY-e)&&K(b,"click",a)))},setDOMEvents:function(){var a=this,b=a.chart.container;b.onmousedown=function(b){a.onContainerMouseDown(b)}; b.onmousemove=function(b){a.onContainerMouseMove(b)};b.onclick=function(b){a.onContainerClick(b)};N(b,"mouseleave",a.onContainerMouseLeave);$a===1&&N(x,"mouseup",a.onDocumentMouseUp);if(Za)b.ontouchstart=function(b){a.onContainerTouchStart(b)},b.ontouchmove=function(b){a.onContainerTouchMove(b)},$a===1&&N(x,"touchend",a.onDocumentTouchEnd)},destroy:function(){var a;X(this.chart.container,"mouseleave",this.onContainerMouseLeave);$a||(X(x,"mouseup",this.onDocumentMouseUp),X(x,"touchend",this.onDocumentTouchEnd)); clearInterval(this.tooltipTimeout);for(a in this)this[a]=null}};r(S.Pointer.prototype,{pinchTranslate:function(a,b,c,d,e,f){(this.zoomHor||this.pinchHor)&&this.pinchTranslateDirection(!0,a,b,c,d,e,f);(this.zoomVert||this.pinchVert)&&this.pinchTranslateDirection(!1,a,b,c,d,e,f)},pinchTranslateDirection:function(a,b,c,d,e,f,g,h){var i=this.chart,j=a?"x":"y",k=a?"X":"Y",l="chart"+k,m=a?"width":"height",n=i["plot"+(a?"Left":"Top")],o,p,q=h||1,r=i.inverted,D=i.bounds[a?"h":"v"],u=b.length===1,s=b[0][l], v=c[0][l],t=!u&&b[1][l],w=!u&&c[1][l],x,c=function(){!u&&Q(s-t)>20&&(q=h||Q(v-w)/Q(s-t));p=(n-v)/q+s;o=i["plot"+(a?"Width":"Height")]/q};c();b=p;b<D.min?(b=D.min,x=!0):b+o>D.max&&(b=D.max-o,x=!0);x?(v-=0.8*(v-g[j][0]),u||(w-=0.8*(w-g[j][1])),c()):g[j]=[v,w];r||(f[j]=p-n,f[m]=o);f=r?1/q:q;e[m]=o;e[j]=b;d[r?a?"scaleY":"scaleX":"scale"+k]=q;d["translate"+k]=f*n+(v-f*s)},pinch:function(a){var b=this,c=b.chart,d=b.pinchDown,e=b.followTouchMove,f=a.touches,g=f.length,h=b.lastValidTouch,i=b.hasZoom,j=b.selectionMarker, k={},l=g===1&&(b.inClass(a.target,"highcharts-tracker")&&c.runTrackerClick||c.runChartClick),m={};(i||e)&&!l&&a.preventDefault();Ua(f,function(a){return b.normalize(a)});if(a.type==="touchstart")q(f,function(a,b){d[b]={chartX:a.chartX,chartY:a.chartY}}),h.x=[d[0].chartX,d[1]&&d[1].chartX],h.y=[d[0].chartY,d[1]&&d[1].chartY],q(c.axes,function(a){if(a.zoomEnabled){var b=c.bounds[a.horiz?"h":"v"],d=a.minPixelPadding,e=a.toPixels(p(a.options.min,a.dataMin)),f=a.toPixels(p(a.options.max,a.dataMax)),g= C(e,f),e=u(e,f);b.min=C(a.pos,g-d);b.max=u(a.pos+a.len,e+d)}});else if(d.length){if(!j)b.selectionMarker=j=r({destroy:sa},c.plotBox);b.pinchTranslate(d,f,k,j,m,h);b.hasPinched=i;b.scaleGroups(k,m);!i&&e&&g===1&&this.runPointActions(b.normalize(a))}},onContainerTouchStart:function(a){var b=this.chart;pa=b.index;a.touches.length===1?(a=this.normalize(a),b.isInsidePlot(a.chartX-b.plotLeft,a.chartY-b.plotTop)?(this.runPointActions(a),this.pinch(a)):this.reset()):a.touches.length===2&&this.pinch(a)},onContainerTouchMove:function(a){(a.touches.length=== 1||a.touches.length===2)&&this.pinch(a)},onDocumentTouchEnd:function(a){W[pa]&&W[pa].pointer.drop(a)}});if(H.PointerEvent||H.MSPointerEvent){var ua={},yb=!!H.PointerEvent,Wb=function(){var a,b=[];b.item=function(a){return this[a]};for(a in ua)ua.hasOwnProperty(a)&&b.push({pageX:ua[a].pageX,pageY:ua[a].pageY,target:ua[a].target});return b},zb=function(a,b,c,d){a=a.originalEvent||a;if((a.pointerType==="touch"||a.pointerType===a.MSPOINTER_TYPE_TOUCH)&&W[pa])d(a),d=W[pa].pointer,d[b]({type:c,target:a.currentTarget, preventDefault:sa,touches:Wb()})};r(Va.prototype,{onContainerPointerDown:function(a){zb(a,"onContainerTouchStart","touchstart",function(a){ua[a.pointerId]={pageX:a.pageX,pageY:a.pageY,target:a.currentTarget}})},onContainerPointerMove:function(a){zb(a,"onContainerTouchMove","touchmove",function(a){ua[a.pointerId]={pageX:a.pageX,pageY:a.pageY};if(!ua[a.pointerId].target)ua[a.pointerId].target=a.currentTarget})},onDocumentPointerUp:function(a){zb(a,"onContainerTouchEnd","touchend",function(a){delete ua[a.pointerId]})}, batchMSEvents:function(a){a(this.chart.container,yb?"pointerdown":"MSPointerDown",this.onContainerPointerDown);a(this.chart.container,yb?"pointermove":"MSPointerMove",this.onContainerPointerMove);a(x,yb?"pointerup":"MSPointerUp",this.onDocumentPointerUp)}});Ma(Va.prototype,"init",function(a,b,c){a.call(this,b,c);(this.hasZoom||this.followTouchMove)&&A(b.container,{"-ms-touch-action":P,"touch-action":P})});Ma(Va.prototype,"setDOMEvents",function(a){a.apply(this);(this.hasZoom||this.followTouchMove)&& this.batchMSEvents(N)});Ma(Va.prototype,"destroy",function(a){this.batchMSEvents(X);a.call(this)})}var kb=S.Legend=function(a,b){this.init(a,b)};kb.prototype={init:function(a,b){var c=this,d=b.itemStyle,e=p(b.padding,8),f=b.itemMarginTop||0;this.options=b;if(b.enabled)c.itemStyle=d,c.itemHiddenStyle=w(d,b.itemHiddenStyle),c.itemMarginTop=f,c.padding=e,c.initialItemX=e,c.initialItemY=e-5,c.maxItemWidth=0,c.chart=a,c.itemHeight=0,c.lastLineHeight=0,c.symbolWidth=p(b.symbolWidth,16),c.pages=[],c.render(), N(c.chart,"endResize",function(){c.positionCheckboxes()})},colorizeItem:function(a,b){var c=this.options,d=a.legendItem,e=a.legendLine,f=a.legendSymbol,g=this.itemHiddenStyle.color,c=b?c.itemStyle.color:g,h=b?a.legendColor||a.color||"#CCC":g,g=a.options&&a.options.marker,i={fill:h},j;d&&d.css({fill:c,color:c});e&&e.attr({stroke:h});if(f){if(g&&f.isMarker)for(j in i.stroke=h,g=a.convertAttribs(g),g)d=g[j],d!==t&&(i[j]=d);f.attr(i)}},positionItem:function(a){var b=this.options,c=b.symbolPadding,b=!b.rtl, d=a._legendItemPos,e=d[0],d=d[1],f=a.checkbox;a.legendGroup&&a.legendGroup.translate(b?e:this.legendWidth-e-2*c-4,d);if(f)f.x=e,f.y=d},destroyItem:function(a){var b=a.checkbox;q(["legendItem","legendLine","legendSymbol","legendGroup"],function(b){a[b]&&(a[b]=a[b].destroy())});b&&Pa(a.checkbox)},destroy:function(){var a=this.group,b=this.box;if(b)this.box=b.destroy();if(a)this.group=a.destroy()},positionCheckboxes:function(a){var b=this.group.alignAttr,c,d=this.clipHeight||this.legendHeight;if(b)c= b.translateY,q(this.allItems,function(e){var f=e.checkbox,g;f&&(g=c+f.y+(a||0)+3,A(f,{left:b.translateX+e.checkboxOffset+f.x-20+"px",top:g+"px",display:g>c-6&&g<c+d-6?"":P}))})},renderTitle:function(){var a=this.padding,b=this.options.title,c=0;if(b.text){if(!this.title)this.title=this.chart.renderer.label(b.text,a-3,a-4,null,null,null,null,null,"legend-title").attr({zIndex:1}).css(b.style).add(this.group);a=this.title.getBBox();c=a.height;this.offsetWidth=a.width;this.contentGroup.attr({translateY:c})}this.titleHeight= c},renderItem:function(a){var b=this.chart,c=b.renderer,d=this.options,e=d.layout==="horizontal",f=this.symbolWidth,g=d.symbolPadding,h=this.itemStyle,i=this.itemHiddenStyle,j=this.padding,k=e?p(d.itemDistance,20):0,l=!d.rtl,m=d.width,n=d.itemMarginBottom||0,o=this.itemMarginTop,q=this.initialItemX,r=a.legendItem,s=a.series&&a.series.drawLegendSymbol?a.series:a,D=s.options,D=this.createCheckboxForItem&&D&&D.showCheckbox,t=d.useHTML;if(!r){a.legendGroup=c.g("legend-item").attr({zIndex:1}).add(this.scrollGroup); a.legendItem=r=c.text(d.labelFormat?Ia(d.labelFormat,a):d.labelFormatter.call(a),l?f+g:-g,this.baseline||0,t).css(w(a.visible?h:i)).attr({align:l?"left":"right",zIndex:2}).add(a.legendGroup);if(!this.baseline)this.baseline=c.fontMetrics(h.fontSize,r).f+3+o,r.attr("y",this.baseline);s.drawLegendSymbol(this,a);this.setItemEvents&&this.setItemEvents(a,r,t,h,i);this.colorizeItem(a,a.visible);D&&this.createCheckboxForItem(a)}c=r.getBBox();f=a.checkboxOffset=d.itemWidth||a.legendItemWidth||f+g+c.width+ k+(D?20:0);this.itemHeight=g=v(a.legendItemHeight||c.height);if(e&&this.itemX-q+f>(m||b.chartWidth-2*j-q-d.x))this.itemX=q,this.itemY+=o+this.lastLineHeight+n,this.lastLineHeight=0;this.maxItemWidth=u(this.maxItemWidth,f);this.lastItemY=o+this.itemY+n;this.lastLineHeight=u(g,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];e?this.itemX+=f:(this.itemY+=o+g+n,this.lastLineHeight=g);this.offsetWidth=m||u((e?this.itemX-q-k:f)+j,this.offsetWidth)},getAllItems:function(){var a=[];q(this.chart.series, function(b){var c=b.options;if(p(c.showInLegend,!s(c.linkedTo)?t:!1,!0))a=a.concat(b.legendItems||(c.legendType==="point"?b.data:b))});return a},render:function(){var a=this,b=a.chart,c=b.renderer,d=a.group,e,f,g,h,i=a.box,j=a.options,k=a.padding,l=j.borderWidth,m=j.backgroundColor;a.itemX=a.initialItemX;a.itemY=a.initialItemY;a.offsetWidth=0;a.lastItemY=0;if(!d)a.group=d=c.g("legend").attr({zIndex:7}).add(),a.contentGroup=c.g().attr({zIndex:1}).add(d),a.scrollGroup=c.g().add(a.contentGroup);a.renderTitle(); e=a.getAllItems();nb(e,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});j.reversed&&e.reverse();a.allItems=e;a.display=f=!!e.length;q(e,function(b){a.renderItem(b)});g=j.width||a.offsetWidth;h=a.lastItemY+a.lastLineHeight+a.titleHeight;h=a.handleOverflow(h);if(l||m){g+=k;h+=k;if(i){if(g>0&&h>0)i[i.isNew?"attr":"animate"](i.crisp({width:g,height:h})),i.isNew=!1}else a.box=i=c.rect(0,0,g,h,j.borderRadius,l||0).attr({stroke:j.borderColor,"stroke-width":l|| 0,fill:m||P}).add(d).shadow(j.shadow),i.isNew=!0;i[f?"show":"hide"]()}a.legendWidth=g;a.legendHeight=h;q(e,function(b){a.positionItem(b)});f&&d.align(r({width:g,height:h},j),!0,"spacingBox");b.isResizing||this.positionCheckboxes()},handleOverflow:function(a){var b=this,c=this.chart,d=c.renderer,e=this.options,f=e.y,f=c.spacingBox.height+(e.verticalAlign==="top"?-f:f)-this.padding,g=e.maxHeight,h,i=this.clipRect,j=e.navigation,k=p(j.animation,!0),l=j.arrowSize||12,m=this.nav,n=this.pages,o,r=this.allItems; e.layout==="horizontal"&&(f/=2);g&&(f=C(f,g));n.length=0;if(a>f&&!e.useHTML){this.clipHeight=h=u(f-20-this.titleHeight-this.padding,0);this.currentPage=p(this.currentPage,1);this.fullHeight=a;q(r,function(a,b){var c=a._legendItemPos[1],d=v(a.legendItem.getBBox().height),e=n.length;if(!e||c-n[e-1]>h&&(o||c)!==n[e-1])n.push(o||c),e++;b===r.length-1&&c+d-n[e-1]>h&&n.push(c);c!==o&&(o=c)});if(!i)i=b.clipRect=d.clipRect(0,this.padding,9999,0),b.contentGroup.clip(i);i.attr({height:h});if(!m)this.nav=m= d.g().attr({zIndex:1}).add(this.group),this.up=d.symbol("triangle",0,0,l,l).on("click",function(){b.scroll(-1,k)}).add(m),this.pager=d.text("",15,10).css(j.style).add(m),this.down=d.symbol("triangle-down",0,0,l,l).on("click",function(){b.scroll(1,k)}).add(m);b.scroll(0);a=f}else if(m)i.attr({height:c.chartHeight}),m.hide(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0;return a},scroll:function(a,b){var c=this.pages,d=c.length,e=this.currentPage+a,f=this.clipHeight,g=this.options.navigation, h=g.activeColor,g=g.inactiveColor,i=this.pager,j=this.padding;e>d&&(e=d);if(e>0)b!==t&&Qa(b,this.chart),this.nav.attr({translateX:j,translateY:f+this.padding+7+this.titleHeight,visibility:"visible"}),this.up.attr({fill:e===1?g:h}).css({cursor:e===1?"default":"pointer"}),i.attr({text:e+"/"+d}),this.down.attr({x:18+this.pager.getBBox().width,fill:e===d?g:h}).css({cursor:e===d?"default":"pointer"}),c=-c[e-1]+this.initialItemY,this.scrollGroup.animate({translateY:c}),this.currentPage=e,this.positionCheckboxes(c)}}; M=S.LegendSymbolMixin={drawRectangle:function(a,b){var c=a.options.symbolHeight||12;b.legendSymbol=this.chart.renderer.rect(0,a.baseline-5-c/2,a.symbolWidth,c,a.options.symbolRadius||0).attr({zIndex:3}).add(b.legendGroup)},drawLineMarker:function(a){var b=this.options,c=b.marker,d;d=a.symbolWidth;var e=this.chart.renderer,f=this.legendGroup,a=a.baseline-v(e.fontMetrics(a.options.itemStyle.fontSize,this.legendItem).b*0.3),g;if(b.lineWidth){g={"stroke-width":b.lineWidth};if(b.dashStyle)g.dashstyle= b.dashStyle;this.legendLine=e.path(["M",0,a,"L",d,a]).attr(g).add(f)}if(c&&c.enabled!==!1)b=c.radius,this.legendSymbol=d=e.symbol(this.symbol,d/2-b,a-b,2*b,2*b).add(f),d.isMarker=!0}};(/Trident\/7\.0/.test(wa)||Ta)&&Ma(kb.prototype,"positionItem",function(a,b){var c=this,d=function(){b._legendItemPos&&a.call(c,b)};d();setTimeout(d)});Xa.prototype={init:function(a,b){var c,d=a.series;a.series=null;c=w(L,a);c.series=a.series=d;this.userOptions=a;d=c.chart;this.margin=this.splashArray("margin",d);this.spacing= this.splashArray("spacing",d);var e=d.events;this.bounds={h:{},v:{}};this.callback=b;this.isResizing=0;this.options=c;this.axes=[];this.series=[];this.hasCartesianSeries=d.showAxes;var f=this,g;f.index=W.length;W.push(f);$a++;d.reflow!==!1&&N(f,"load",function(){f.initReflow()});if(e)for(g in e)N(f,g,e[g]);f.xAxis=[];f.yAxis=[];f.animation=ga?!1:p(d.animation,!0);f.pointCount=f.colorCounter=f.symbolCounter=0;f.firstRender()},initSeries:function(a){var b=this.options.chart;(b=J[a.type||b.type||b.defaultSeriesType])|| oa(17,!0);b=new b;b.init(this,a);return b},isInsidePlot:function(a,b,c){var d=c?b:a,a=c?a:b;return d>=0&&d<=this.plotWidth&&a>=0&&a<=this.plotHeight},adjustTickAmounts:function(){this.options.chart.alignTicks!==!1&&q(this.axes,function(a){a.adjustTickAmount()});this.maxTicks=null},redraw:function(a){var b=this.axes,c=this.series,d=this.pointer,e=this.legend,f=this.isDirtyLegend,g,h,i=this.hasCartesianSeries,j=this.isDirtyBox,k=c.length,l=k,m=this.renderer,n=m.isHidden(),o=[];Qa(a,this);n&&this.cloneRenderTo(); for(this.layOutTitles();l--;)if(a=c[l],a.options.stacking&&(g=!0,a.isDirty)){h=!0;break}if(h)for(l=k;l--;)if(a=c[l],a.options.stacking)a.isDirty=!0;q(c,function(a){a.isDirty&&a.options.legendType==="point"&&(f=!0)});if(f&&e.options.enabled)e.render(),this.isDirtyLegend=!1;g&&this.getStacks();if(i){if(!this.isResizing)this.maxTicks=null,q(b,function(a){a.setScale()});this.adjustTickAmounts()}this.getMargins();i&&(q(b,function(a){a.isDirty&&(j=!0)}),q(b,function(a){if(a.isDirtyExtremes)a.isDirtyExtremes= !1,o.push(function(){K(a,"afterSetExtremes",r(a.eventArgs,a.getExtremes()));delete a.eventArgs});(j||g)&&a.redraw()}));j&&this.drawChartBox();q(c,function(a){a.isDirty&&a.visible&&(!a.isCartesian||a.xAxis)&&a.redraw()});d&&d.reset(!0);m.draw();K(this,"redraw");n&&this.cloneRenderTo(!0);q(o,function(a){a.call()})},get:function(a){var b=this.axes,c=this.series,d,e;for(d=0;d<b.length;d++)if(b[d].options.id===a)return b[d];for(d=0;d<c.length;d++)if(c[d].options.id===a)return c[d];for(d=0;d<c.length;d++){e= c[d].points||[];for(b=0;b<e.length;b++)if(e[b].id===a)return e[b]}return null},getAxes:function(){var a=this,b=this.options,c=b.xAxis=ra(b.xAxis||{}),b=b.yAxis=ra(b.yAxis||{});q(c,function(a,b){a.index=b;a.isX=!0});q(b,function(a,b){a.index=b});c=c.concat(b);q(c,function(b){new ma(a,b)});a.adjustTickAmounts()},getSelectedPoints:function(){var a=[];q(this.series,function(b){a=a.concat(vb(b.points||[],function(a){return a.selected}))});return a},getSelectedSeries:function(){return vb(this.series,function(a){return a.selected})}, getStacks:function(){var a=this;q(a.yAxis,function(a){if(a.stacks&&a.hasVisibleSeries)a.oldStacks=a.stacks});q(a.series,function(b){if(b.options.stacking&&(b.visible===!0||a.options.chart.ignoreHiddenSeries===!1))b.stackKey=b.type+p(b.options.stack,"")})},setTitle:function(a,b,c){var g;var d=this,e=d.options,f;f=e.title=w(e.title,a);g=e.subtitle=w(e.subtitle,b),e=g;q([["title",a,f],["subtitle",b,e]],function(a){var b=a[0],c=d[b],e=a[1],a=a[2];c&&e&&(d[b]=c=c.destroy());a&&a.text&&!c&&(d[b]=d.renderer.text(a.text, 0,0,a.useHTML).attr({align:a.align,"class":"highcharts-"+b,zIndex:a.zIndex||4}).css(a.style).add())});d.layOutTitles(c)},layOutTitles:function(a){var b=0,c=this.title,d=this.subtitle,e=this.options,f=e.title,e=e.subtitle,g=this.renderer,h=this.spacingBox.width-44;if(c&&(c.css({width:(f.width||h)+"px"}).align(r({y:g.fontMetrics(f.style.fontSize,c).b-3},f),!1,"spacingBox"),!f.floating&&!f.verticalAlign))b=c.getBBox().height;d&&(d.css({width:(e.width||h)+"px"}).align(r({y:b+(f.margin-13)+g.fontMetrics(f.style.fontSize, d).b},e),!1,"spacingBox"),!e.floating&&!e.verticalAlign&&(b=Ka(b+d.getBBox().height)));c=this.titleOffset!==b;this.titleOffset=b;if(!this.isDirtyBox&&c)this.isDirtyBox=c,this.hasRendered&&p(a,!0)&&this.isDirtyBox&&this.redraw()},getChartSize:function(){var a=this.options.chart,b=a.width,a=a.height,c=this.renderToClone||this.renderTo;if(!s(b))this.containerWidth=hb(c,"width");if(!s(a))this.containerHeight=hb(c,"height");this.chartWidth=u(0,b||this.containerWidth||600);this.chartHeight=u(0,p(a,this.containerHeight> 19?this.containerHeight:400))},cloneRenderTo:function(a){var b=this.renderToClone,c=this.container;a?b&&(this.renderTo.appendChild(c),Pa(b),delete this.renderToClone):(c&&c.parentNode===this.renderTo&&this.renderTo.removeChild(c),this.renderToClone=b=this.renderTo.cloneNode(0),A(b,{position:"absolute",top:"-9999px",display:"block"}),b.style.setProperty&&b.style.setProperty("display","block","important"),x.body.appendChild(b),c&&b.appendChild(c))},getContainer:function(){var a,b=this.options.chart, c,d,e;this.renderTo=a=b.renderTo;e="highcharts-"+tb++;if(Fa(a))this.renderTo=a=x.getElementById(a);a||oa(13,!0);c=z(F(a,"data-highcharts-chart"));!isNaN(c)&&W[c]&&W[c].hasRendered&&W[c].destroy();F(a,"data-highcharts-chart",this.index);a.innerHTML="";!b.skipClone&&!a.offsetWidth&&this.cloneRenderTo();this.getChartSize();c=this.chartWidth;d=this.chartHeight;this.container=a=$(Ja,{className:"highcharts-container"+(b.className?" "+b.className:""),id:e},r({position:"relative",overflow:"hidden",width:c+ "px",height:d+"px",textAlign:"left",lineHeight:"normal",zIndex:0,"-webkit-tap-highlight-color":"rgba(0,0,0,0)"},b.style),this.renderToClone||a);this._cursor=a.style.cursor;this.renderer=b.forExport?new ta(a,c,d,b.style,!0):new Ya(a,c,d,b.style);ga&&this.renderer.create(this,a,c,d)},getMargins:function(){var a=this.spacing,b,c=this.legend,d=this.margin,e=this.options.legend,f=p(e.margin,20),g=e.x,h=e.y,i=e.align,j=e.verticalAlign,k=this.titleOffset;this.resetMargins();b=this.axisOffset;if(k&&!s(d[0]))this.plotTop= u(this.plotTop,k+this.options.title.margin+a[0]);if(c.display&&!e.floating)if(i==="right"){if(!s(d[1]))this.marginRight=u(this.marginRight,c.legendWidth-g+f+a[1])}else if(i==="left"){if(!s(d[3]))this.plotLeft=u(this.plotLeft,c.legendWidth+g+f+a[3])}else if(j==="top"){if(!s(d[0]))this.plotTop=u(this.plotTop,c.legendHeight+h+f+a[0])}else if(j==="bottom"&&!s(d[2]))this.marginBottom=u(this.marginBottom,c.legendHeight-h+f+a[2]);this.extraBottomMargin&&(this.marginBottom+=this.extraBottomMargin);this.extraTopMargin&& (this.plotTop+=this.extraTopMargin);this.hasCartesianSeries&&q(this.axes,function(a){a.getOffset()});s(d[3])||(this.plotLeft+=b[3]);s(d[0])||(this.plotTop+=b[0]);s(d[2])||(this.marginBottom+=b[2]);s(d[1])||(this.marginRight+=b[1]);this.setChartSize()},reflow:function(a){var b=this,c=b.options.chart,d=b.renderTo,e=c.width||hb(d,"width"),f=c.height||hb(d,"height"),c=a?a.target:H,d=function(){if(b.container)b.setSize(e,f,!1),b.hasUserSize=null};if(!b.hasUserSize&&e&&f&&(c===H||c===x)){if(e!==b.containerWidth|| f!==b.containerHeight)clearTimeout(b.reflowTimeout),a?b.reflowTimeout=setTimeout(d,100):d();b.containerWidth=e;b.containerHeight=f}},initReflow:function(){var a=this,b=function(b){a.reflow(b)};N(H,"resize",b);N(a,"destroy",function(){X(H,"resize",b)})},setSize:function(a,b,c){var d=this,e,f,g;d.isResizing+=1;g=function(){d&&K(d,"endResize",null,function(){d.isResizing-=1})};Qa(c,d);d.oldChartHeight=d.chartHeight;d.oldChartWidth=d.chartWidth;if(s(a))d.chartWidth=e=u(0,v(a)),d.hasUserSize=!!e;if(s(b))d.chartHeight= f=u(0,v(b));(va?ib:A)(d.container,{width:e+"px",height:f+"px"},va);d.setChartSize(!0);d.renderer.setSize(e,f,c);d.maxTicks=null;q(d.axes,function(a){a.isDirty=!0;a.setScale()});q(d.series,function(a){a.isDirty=!0});d.isDirtyLegend=!0;d.isDirtyBox=!0;d.layOutTitles();d.getMargins();d.redraw(c);d.oldChartHeight=null;K(d,"resize");va===!1?g():setTimeout(g,va&&va.duration||500)},setChartSize:function(a){var b=this.inverted,c=this.renderer,d=this.chartWidth,e=this.chartHeight,f=this.options.chart,g=this.spacing, h=this.clipOffset,i,j,k,l;this.plotLeft=i=v(this.plotLeft);this.plotTop=j=v(this.plotTop);this.plotWidth=k=u(0,v(d-i-this.marginRight));this.plotHeight=l=u(0,v(e-j-this.marginBottom));this.plotSizeX=b?l:k;this.plotSizeY=b?k:l;this.plotBorderWidth=f.plotBorderWidth||0;this.spacingBox=c.spacingBox={x:g[3],y:g[0],width:d-g[3]-g[1],height:e-g[0]-g[2]};this.plotBox=c.plotBox={x:i,y:j,width:k,height:l};d=2*U(this.plotBorderWidth/2);b=Ka(u(d,h[3])/2);c=Ka(u(d,h[0])/2);this.clipBox={x:b,y:c,width:U(this.plotSizeX- u(d,h[1])/2-b),height:u(0,U(this.plotSizeY-u(d,h[2])/2-c))};a||q(this.axes,function(a){a.setAxisSize();a.setAxisTranslation()})},resetMargins:function(){var a=this.spacing,b=this.margin;this.plotTop=p(b[0],a[0]);this.marginRight=p(b[1],a[1]);this.marginBottom=p(b[2],a[2]);this.plotLeft=p(b[3],a[3]);this.axisOffset=[0,0,0,0];this.clipOffset=[0,0,0,0]},drawChartBox:function(){var a=this.options.chart,b=this.renderer,c=this.chartWidth,d=this.chartHeight,e=this.chartBackground,f=this.plotBackground,g= this.plotBorder,h=this.plotBGImage,i=a.borderWidth||0,j=a.backgroundColor,k=a.plotBackgroundColor,l=a.plotBackgroundImage,m=a.plotBorderWidth||0,n,o=this.plotLeft,p=this.plotTop,q=this.plotWidth,r=this.plotHeight,u=this.plotBox,s=this.clipRect,v=this.clipBox;n=i+(a.shadow?8:0);if(i||j)if(e)e.animate(e.crisp({width:c-n,height:d-n}));else{e={fill:j||P};if(i)e.stroke=a.borderColor,e["stroke-width"]=i;this.chartBackground=b.rect(n/2,n/2,c-n,d-n,a.borderRadius,i).attr(e).addClass("highcharts-background").add().shadow(a.shadow)}if(k)f? f.animate(u):this.plotBackground=b.rect(o,p,q,r,0).attr({fill:k}).add().shadow(a.plotShadow);if(l)h?h.animate(u):this.plotBGImage=b.image(l,o,p,q,r).add();s?s.animate({width:v.width,height:v.height}):this.clipRect=b.clipRect(v);if(m)g?g.animate(g.crisp({x:o,y:p,width:q,height:r})):this.plotBorder=b.rect(o,p,q,r,0,-m).attr({stroke:a.plotBorderColor,"stroke-width":m,fill:P,zIndex:1}).add();this.isDirtyBox=!1},propFromSeries:function(){var a=this,b=a.options.chart,c,d=a.options.series,e,f;q(["inverted", "angular","polar"],function(g){c=J[b.type||b.defaultSeriesType];f=a[g]||b[g]||c&&c.prototype[g];for(e=d&&d.length;!f&&e--;)(c=J[d[e].type])&&c.prototype[g]&&(f=!0);a[g]=f})},linkSeries:function(){var a=this,b=a.series;q(b,function(a){a.linkedSeries.length=0});q(b,function(b){var d=b.options.linkedTo;if(Fa(d)&&(d=d===":previous"?a.series[b.index-1]:a.get(d)))d.linkedSeries.push(b),b.linkedParent=d})},renderSeries:function(){q(this.series,function(a){a.translate();a.setTooltipPoints&&a.setTooltipPoints(); a.render()})},renderLabels:function(){var a=this,b=a.options.labels;b.items&&q(b.items,function(c){var d=r(b.style,c.style),e=z(d.left)+a.plotLeft,f=z(d.top)+a.plotTop+12;delete d.left;delete d.top;a.renderer.text(c.html,e,f).attr({zIndex:2}).css(d).add()})},render:function(){var a=this.axes,b=this.renderer,c=this.options;this.setTitle();this.legend=new kb(this,c.legend);this.getStacks();q(a,function(a){a.setScale()});this.getMargins();this.maxTicks=null;q(a,function(a){a.setTickPositions(!0);a.setMaxTicks()}); this.adjustTickAmounts();this.getMargins();this.drawChartBox();this.hasCartesianSeries&&q(a,function(a){a.render()});if(!this.seriesGroup)this.seriesGroup=b.g("series-group").attr({zIndex:3}).add();this.renderSeries();this.renderLabels();this.showCredits(c.credits);this.hasRendered=!0},showCredits:function(a){if(a.enabled&&!this.credits)this.credits=this.renderer.text(a.text,0,0).on("click",function(){if(a.href)location.href=a.href}).attr({align:a.position.align,zIndex:8}).css(a.style).add().align(a.position)}, destroy:function(){var a=this,b=a.axes,c=a.series,d=a.container,e,f=d&&d.parentNode;K(a,"destroy");W[a.index]=t;$a--;a.renderTo.removeAttribute("data-highcharts-chart");X(a);for(e=b.length;e--;)b[e]=b[e].destroy();for(e=c.length;e--;)c[e]=c[e].destroy();q("title,subtitle,chartBackground,plotBackground,plotBGImage,plotBorder,seriesGroup,clipRect,credits,pointer,scroller,rangeSelector,legend,resetZoomButton,tooltip,renderer".split(","),function(b){var c=a[b];c&&c.destroy&&(a[b]=c.destroy())});if(d)d.innerHTML= "",X(d),f&&Pa(d);for(e in a)delete a[e]},isReadyToRender:function(){var a=this;return!ba&&H==H.top&&x.readyState!=="complete"||ga&&!H.canvg?(ga?Lb.push(function(){a.firstRender()},a.options.global.canvasToolsURL):x.attachEvent("onreadystatechange",function(){x.detachEvent("onreadystatechange",a.firstRender);x.readyState==="complete"&&a.firstRender()}),!1):!0},firstRender:function(){var a=this,b=a.options,c=a.callback;if(a.isReadyToRender()){a.getContainer();K(a,"init");a.resetMargins();a.setChartSize(); a.propFromSeries();a.getAxes();q(b.series||[],function(b){a.initSeries(b)});a.linkSeries();K(a,"beforeRender");if(S.Pointer)a.pointer=new Va(a,b);a.render();a.renderer.draw();c&&c.apply(a,[a]);q(a.callbacks,function(b){b.apply(a,[a])});a.cloneRenderTo(!0);K(a,"load")}},splashArray:function(a,b){var c=b[a],c=da(c)?c:[c,c,c,c];return[p(b[a+"Top"],c[0]),p(b[a+"Right"],c[1]),p(b[a+"Bottom"],c[2]),p(b[a+"Left"],c[3])]}};Xa.prototype.callbacks=[];Z=S.CenteredSeriesMixin={getCenter:function(){var a=this.options, b=this.chart,c=2*(a.slicedOffset||0),d,e=b.plotWidth-2*c,f=b.plotHeight-2*c,b=a.center,a=[p(b[0],"50%"),p(b[1],"50%"),a.size||"100%",a.innerSize||0],g=C(e,f),h;return Ua(a,function(a,b){h=/%$/.test(a);d=b<2||b===2&&h;return(h?[e,f,g,g][b]*z(a)/100:a)+(d?c:0)})}};var Ea=function(){};Ea.prototype={init:function(a,b,c){this.series=a;this.applyOptions(b,c);this.pointAttr={};if(a.options.colorByPoint&&(b=a.options.colors||a.chart.options.colors,this.color=this.color||b[a.colorCounter++],a.colorCounter=== b.length))a.colorCounter=0;a.chart.pointCount++;return this},applyOptions:function(a,b){var c=this.series,d=c.options.pointValKey||c.pointValKey,a=Ea.prototype.optionsToObject.call(this,a);r(this,a);this.options=this.options?r(this.options,a):a;if(d)this.y=this[d];if(this.x===t&&c)this.x=b===t?c.autoIncrement():b;return this},optionsToObject:function(a){var b={},c=this.series,d=c.pointArrayMap||["y"],e=d.length,f=0,g=0;if(typeof a==="number"||a===null)b[d[0]]=a;else if(La(a)){if(a.length>e){c=typeof a[0]; if(c==="string")b.name=a[0];else if(c==="number")b.x=a[0];f++}for(;g<e;)b[d[g++]]=a[f++]}else if(typeof a==="object"){b=a;if(a.dataLabels)c._hasPointLabels=!0;if(a.marker)c._hasPointMarkers=!0}return b},destroy:function(){var a=this.series.chart,b=a.hoverPoints,c;a.pointCount--;if(b&&(this.setState(),ka(b,this),!b.length))a.hoverPoints=null;if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)X(this),this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(c in this)this[c]= null},destroyElements:function(){for(var a="graphic,dataLabel,dataLabelUpper,group,connector,shadowGroup".split(","),b,c=6;c--;)b=a[c],this[b]&&(this[b]=this[b].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,key:this.name||this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(a){var b=this.series,c=b.tooltipOptions,d=p(c.valueDecimals,""),e=c.valuePrefix||"",f=c.valueSuffix||"";q(b.pointArrayMap|| ["y"],function(b){b="{point."+b;if(e||f)a=a.replace(b+"}",e+b+"}"+f);a=a.replace(b+"}",b+":,."+d+"f}")});return Ia(a,{point:this,series:this.series})},firePointEvent:function(a,b,c){var d=this,e=this.series.options;(e.point.events[a]||d.options&&d.options.events&&d.options.events[a])&&this.importEvents();a==="click"&&e.allowPointSelect&&(c=function(a){d.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});K(this,a,b,c)}};var O=function(){};O.prototype={isCartesian:!0,type:"line",pointClass:Ea,sorted:!0, requireSorting:!0,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor",r:"radius"},axisTypes:["xAxis","yAxis"],colorCounter:0,parallelArrays:["x","y"],init:function(a,b){var c=this,d,e,f=a.series,g=function(a,b){return p(a.options.index,a._i)-p(b.options.index,b._i)};c.chart=a;c.options=b=c.setOptions(b);c.linkedSeries=[];c.bindAxes();r(c,{name:b.name,state:"",pointAttr:{},visible:b.visible!==!1,selected:b.selected===!0});if(ga)b.animation=!1;e=b.events;for(d in e)N(c, d,e[d]);if(e&&e.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;c.getColor();c.getSymbol();q(c.parallelArrays,function(a){c[a+"Data"]=[]});c.setData(b.data,!1);if(c.isCartesian)a.hasCartesianSeries=!0;f.push(c);c._i=f.length-1;nb(f,g);this.yAxis&&nb(this.yAxis.series,g);q(f,function(a,b){a.index=b;a.name=a.name||"Series "+(b+1)})},bindAxes:function(){var a=this,b=a.options,c=a.chart,d;q(a.axisTypes||[],function(e){q(c[e],function(c){d=c.options;if(b[e]=== d.index||b[e]!==t&&b[e]===d.id||b[e]===t&&d.index===0)c.series.push(a),a[e]=c,c.isDirty=!0});!a[e]&&a.optionalAxis!==e&&oa(18,!0)})},updateParallelArrays:function(a,b){var c=a.series,d=arguments;q(c.parallelArrays,typeof b==="number"?function(d){var f=d==="y"&&c.toYData?c.toYData(a):a[d];c[d+"Data"][b]=f}:function(a){Array.prototype[b].apply(c[a+"Data"],Array.prototype.slice.call(d,2))})},autoIncrement:function(){var a=this.options,b=this.xIncrement,b=p(b,a.pointStart,0);this.pointInterval=p(this.pointInterval, a.pointInterval,1);this.xIncrement=b+this.pointInterval;return b},getSegments:function(){var a=-1,b=[],c,d=this.points,e=d.length;if(e)if(this.options.connectNulls){for(c=e;c--;)d[c].y===null&&d.splice(c,1);d.length&&(b=[d])}else q(d,function(c,g){c.y===null?(g>a+1&&b.push(d.slice(a+1,g)),a=g):g===e-1&&b.push(d.slice(a+1,g+1))});this.segments=b},setOptions:function(a){var b=this.chart,c=b.options.plotOptions,b=b.userOptions||{},d=b.plotOptions||{},e=c[this.type];this.userOptions=a;c=w(e,c.series, a);this.tooltipOptions=w(L.tooltip,L.plotOptions[this.type].tooltip,b.tooltip,d.series&&d.series.tooltip,d[this.type]&&d[this.type].tooltip,a.tooltip);e.marker===null&&delete c.marker;return c},getCyclic:function(a,b,c){var d=this.userOptions,e="_"+a+"Index",f=a+"Counter";b||(s(d[e])?b=d[e]:(d[e]=b=this.chart[f]%c.length,this.chart[f]+=1),b=c[b]);this[a]=b},getColor:function(){this.options.colorByPoint||this.getCyclic("color",this.options.color||ca[this.type].color,this.chart.options.colors)},getSymbol:function(){var a= this.options.marker;this.getCyclic("symbol",a.symbol,this.chart.options.symbols);if(/^url/.test(this.symbol))a.radius=0},drawLegendSymbol:M.drawLineMarker,setData:function(a,b,c,d){var e=this,f=e.points,g=f&&f.length||0,h,i=e.options,j=e.chart,k=null,l=e.xAxis,m=l&&!!l.categories,n=e.tooltipPoints,o=i.turboThreshold,r=this.xData,u=this.yData,s=(h=e.pointArrayMap)&&h.length,a=a||[];h=a.length;b=p(b,!0);if(d!==!1&&h&&g===h&&!e.cropped&&!e.hasGroupedData)q(a,function(a,b){f[b].update(a,!1)});else{e.xIncrement= null;e.pointRange=m?1:i.pointRange;e.colorCounter=0;q(this.parallelArrays,function(a){e[a+"Data"].length=0});if(o&&h>o){for(c=0;k===null&&c<h;)k=a[c],c++;if(ia(k)){m=p(i.pointStart,0);i=p(i.pointInterval,1);for(c=0;c<h;c++)r[c]=m,u[c]=a[c],m+=i;e.xIncrement=m}else if(La(k))if(s)for(c=0;c<h;c++)i=a[c],r[c]=i[0],u[c]=i.slice(1,s+1);else for(c=0;c<h;c++)i=a[c],r[c]=i[0],u[c]=i[1];else oa(12)}else for(c=0;c<h;c++)if(a[c]!==t&&(i={series:e},e.pointClass.prototype.applyOptions.apply(i,[a[c]]),e.updateParallelArrays(i, c),m&&i.name))l.names[i.x]=i.name;Fa(u[0])&&oa(14,!0);e.data=[];e.options.data=a;for(c=g;c--;)f[c]&&f[c].destroy&&f[c].destroy();if(n)n.length=0;if(l)l.minRange=l.userMinRange;e.isDirty=e.isDirtyData=j.isDirtyBox=!0;c=!1}b&&j.redraw(c)},processData:function(a){var b=this.xData,c=this.yData,d=b.length,e;e=0;var f,g,h=this.xAxis,i=this.options,j=i.cropThreshold,k=0,l=this.isCartesian,m,n;if(l&&!this.isDirty&&!h.isDirty&&!this.yAxis.isDirty&&!a)return!1;if(l&&this.sorted&&(!j||d>j||this.forceCrop))if(m= h.getExtremes(),n=m.min,m=m.max,b[d-1]<n||b[0]>m)b=[],c=[];else if(b[0]<n||b[d-1]>m)e=this.cropData(this.xData,this.yData,n,m),b=e.xData,c=e.yData,e=e.start,f=!0,k=b.length;for(a=b.length-1;a>=0;a--)d=b[a]-b[a-1],!f&&b[a]>n&&b[a]<m&&k++,d>0&&(g===t||d<g)?g=d:d<0&&this.requireSorting&&oa(15);this.cropped=f;this.cropStart=e;this.processedXData=b;this.processedYData=c;this.activePointCount=k;if(i.pointRange===null)this.pointRange=g||1;this.closestPointRange=g},cropData:function(a,b,c,d){var e=a.length, f=0,g=e,h=p(this.cropShoulder,1),i;for(i=0;i<e;i++)if(a[i]>=c){f=u(0,i-h);break}for(;i<e;i++)if(a[i]>d){g=i+h;break}return{xData:a.slice(f,g),yData:b.slice(f,g),start:f,end:g}},generatePoints:function(){var a=this.options.data,b=this.data,c,d=this.processedXData,e=this.processedYData,f=this.pointClass,g=d.length,h=this.cropStart||0,i,j=this.hasGroupedData,k,l=[],m;if(!b&&!j)b=[],b.length=a.length,b=this.data=b;for(m=0;m<g;m++)i=h+m,j?l[m]=(new f).init(this,[d[m]].concat(ra(e[m]))):(b[i]?k=b[i]:a[i]!== t&&(b[i]=k=(new f).init(this,a[i],d[m])),l[m]=k);if(b&&(g!==(c=b.length)||j))for(m=0;m<c;m++)if(m===h&&!j&&(m+=g),b[m])b[m].destroyElements(),b[m].plotX=t;this.data=b;this.points=l},getExtremes:function(a){var b=this.yAxis,c=this.processedXData,d,e=[],f=0;d=this.xAxis.getExtremes();var g=d.min,h=d.max,i,j,k,l,a=a||this.stackedYData||this.processedYData;d=a.length;for(l=0;l<d;l++)if(j=c[l],k=a[l],i=k!==null&&k!==t&&(!b.isLog||k.length||k>0),j=this.getExtremesFromAll||this.cropped||(c[l+1]||j)>=g&& (c[l-1]||j)<=h,i&&j)if(i=k.length)for(;i--;)k[i]!==null&&(e[f++]=k[i]);else e[f++]=k;this.dataMin=p(void 0,Na(e));this.dataMax=p(void 0,Ba(e))},translate:function(){this.processedXData||this.processData();this.generatePoints();for(var a=this.options,b=a.stacking,c=this.xAxis,d=c.categories,e=this.yAxis,f=this.points,g=f.length,h=!!this.modifyValue,i=a.pointPlacement,j=i==="between"||ia(i),k=a.threshold,a=0;a<g;a++){var l=f[a],m=l.x,n=l.y,o=l.low,q=b&&e.stacks[(this.negStacks&&n<k?"-":"")+this.stackKey]; if(e.isLog&&n<=0)l.y=n=null;l.plotX=c.translate(m,0,0,0,1,i,this.type==="flags");if(b&&this.visible&&q&&q[m])q=q[m],n=q.points[this.index+","+a],o=n[0],n=n[1],o===0&&(o=p(k,e.min)),e.isLog&&o<=0&&(o=null),l.total=l.stackTotal=q.total,l.percentage=q.total&&l.y/q.total*100,l.stackY=n,q.setOffset(this.pointXOffset||0,this.barW||0);l.yBottom=s(o)?e.translate(o,0,1,0,1):null;h&&(n=this.modifyValue(n,l));l.plotY=typeof n==="number"&&n!==Infinity?e.translate(n,0,1,0,1):t;l.clientX=j?c.translate(m,0,0,0, 1):l.plotX;l.negative=l.y<(k||0);l.category=d&&d[l.x]!==t?d[l.x]:l.x}this.getSegments()},animate:function(a){var b=this.chart,c=b.renderer,d;d=this.options.animation;var e=this.clipBox||b.clipBox,f=b.inverted,g;if(d&&!da(d))d=ca[this.type].animation;g=["_sharedClip",d.duration,d.easing,e.height].join(",");a?(a=b[g],d=b[g+"m"],a||(b[g]=a=c.clipRect(r(e,{width:0})),b[g+"m"]=d=c.clipRect(-99,f?-b.plotLeft:-b.plotTop,99,f?b.chartWidth:b.chartHeight)),this.group.clip(a),this.markerGroup.clip(d),this.sharedClipKey= g):((a=b[g])&&a.animate({width:b.plotSizeX},d),b[g+"m"]&&b[g+"m"].animate({width:b.plotSizeX+99},d),this.animate=null)},afterAnimate:function(){var a=this.chart,b=this.sharedClipKey,c=this.group,d=this.clipBox;if(c&&this.options.clip!==!1){if(!b||!d)c.clip(d?a.renderer.clipRect(d):a.clipRect);this.markerGroup.clip()}K(this,"afterAnimate");setTimeout(function(){b&&a[b]&&(d||(a[b]=a[b].destroy()),a[b+"m"]&&(a[b+"m"]=a[b+"m"].destroy()))},100)},drawPoints:function(){var a,b=this.points,c=this.chart, d,e,f,g,h,i,j,k;d=this.options.marker;var l=this.pointAttr[""],m,n=this.markerGroup,o=p(d.enabled,this.activePointCount<0.5*this.xAxis.len/d.radius);if(d.enabled!==!1||this._hasPointMarkers)for(f=b.length;f--;)if(g=b[f],d=U(g.plotX),e=g.plotY,k=g.graphic,i=g.marker||{},a=o&&i.enabled===t||i.enabled,m=c.isInsidePlot(v(d),e,c.inverted),a&&e!==t&&!isNaN(e)&&g.y!==null)if(a=g.pointAttr[g.selected?"select":""]||l,h=a.r,i=p(i.symbol,this.symbol),j=i.indexOf("url")===0,k)k[m?"show":"hide"](!0).animate(r({x:d- h,y:e-h},k.symbolName?{width:2*h,height:2*h}:{}));else{if(m&&(h>0||j))g.graphic=c.renderer.symbol(i,d-h,e-h,2*h,2*h).attr(a).add(n)}else if(k)g.graphic=k.destroy()},convertAttribs:function(a,b,c,d){var e=this.pointAttrToOptions,f,g,h={},a=a||{},b=b||{},c=c||{},d=d||{};for(f in e)g=e[f],h[f]=p(a[g],b[f],c[f],d[f]);return h},getAttribs:function(){var a=this,b=a.options,c=ca[a.type].marker?b.marker:b,d=c.states,e=d.hover,f,g=a.color;f={stroke:g,fill:g};var h=a.points||[],i,j=[],k,l=a.pointAttrToOptions; k=a.hasPointSpecificOptions;var m=b.negativeColor,n=c.lineColor,o=c.fillColor;i=b.turboThreshold;var p;b.marker?(e.radius=e.radius||c.radius+e.radiusPlus,e.lineWidth=e.lineWidth||c.lineWidth+e.lineWidthPlus):e.color=e.color||ya(e.color||g).brighten(e.brightness).get();j[""]=a.convertAttribs(c,f);q(["hover","select"],function(b){j[b]=a.convertAttribs(d[b],j[""])});a.pointAttr=j;g=h.length;if(!i||g<i||k)for(;g--;){i=h[g];if((c=i.options&&i.options.marker||i.options)&&c.enabled===!1)c.radius=0;if(i.negative&& m)i.color=i.fillColor=m;k=b.colorByPoint||i.color;if(i.options)for(p in l)s(c[l[p]])&&(k=!0);if(k){c=c||{};k=[];d=c.states||{};f=d.hover=d.hover||{};if(!b.marker)f.color=f.color||!i.options.color&&e.color||ya(i.color).brighten(f.brightness||e.brightness).get();f={color:i.color};if(!o)f.fillColor=i.color;if(!n)f.lineColor=i.color;k[""]=a.convertAttribs(r(f,c),j[""]);k.hover=a.convertAttribs(d.hover,j.hover,k[""]);k.select=a.convertAttribs(d.select,j.select,k[""])}else k=j;i.pointAttr=k}},destroy:function(){var a= this,b=a.chart,c=/AppleWebKit\/533/.test(wa),d,e,f=a.data||[],g,h,i;K(a,"destroy");X(a);q(a.axisTypes||[],function(b){if(i=a[b])ka(i.series,a),i.isDirty=i.forceRedraw=!0});a.legendItem&&a.chart.legend.destroyItem(a);for(e=f.length;e--;)(g=f[e])&&g.destroy&&g.destroy();a.points=null;clearTimeout(a.animationTimeout);q("area,graph,dataLabelsGroup,group,markerGroup,tracker,graphNeg,areaNeg,posClip,negClip".split(","),function(b){a[b]&&(d=c&&b==="group"?"hide":"destroy",a[b][d]())});if(b.hoverSeries=== a)b.hoverSeries=null;ka(b.series,a);for(h in a)delete a[h]},getSegmentPath:function(a){var b=this,c=[],d=b.options.step;q(a,function(e,f){var g=e.plotX,h=e.plotY,i;b.getPointSpline?c.push.apply(c,b.getPointSpline(a,e,f)):(c.push(f?"L":"M"),d&&f&&(i=a[f-1],d==="right"?c.push(i.plotX,h):d==="center"?c.push((i.plotX+g)/2,i.plotY,(i.plotX+g)/2,h):c.push(g,i.plotY)),c.push(e.plotX,e.plotY))});return c},getGraphPath:function(){var a=this,b=[],c,d=[];q(a.segments,function(e){c=a.getSegmentPath(e);e.length> 1?b=b.concat(c):d.push(e[0])});a.singlePoints=d;return a.graphPath=b},drawGraph:function(){var a=this,b=this.options,c=[["graph",b.lineColor||this.color]],d=b.lineWidth,e=b.dashStyle,f=b.linecap!=="square",g=this.getGraphPath(),h=b.negativeColor;h&&c.push(["graphNeg",h]);q(c,function(c,h){var k=c[0],l=a[k];if(l)ab(l),l.animate({d:g});else if(d&&g.length)l={stroke:c[1],"stroke-width":d,fill:P,zIndex:1},e?l.dashstyle=e:f&&(l["stroke-linecap"]=l["stroke-linejoin"]="round"),a[k]=a.chart.renderer.path(g).attr(l).add(a.group).shadow(!h&& b.shadow)})},clipNeg:function(){var a=this.options,b=this.chart,c=b.renderer,d=a.negativeColor||a.negativeFillColor,e,f=this.graph,g=this.area,h=this.posClip,i=this.negClip;e=b.chartWidth;var j=b.chartHeight,k=u(e,j),l=this.yAxis;if(d&&(f||g)){d=v(l.toPixels(a.threshold||0,!0));d<0&&(k-=d);a={x:0,y:0,width:k,height:d};k={x:0,y:d,width:k,height:k};if(b.inverted)a.height=k.y=b.plotWidth-d,c.isVML&&(a={x:b.plotWidth-d-b.plotLeft,y:0,width:e,height:j},k={x:d+b.plotLeft-e,y:0,width:b.plotLeft+d,height:e}); l.reversed?(b=k,e=a):(b=a,e=k);h?(h.animate(b),i.animate(e)):(this.posClip=h=c.clipRect(b),this.negClip=i=c.clipRect(e),f&&this.graphNeg&&(f.clip(h),this.graphNeg.clip(i)),g&&(g.clip(h),this.areaNeg.clip(i)))}},invertGroups:function(){function a(){var a={width:b.yAxis.len,height:b.xAxis.len};q(["group","markerGroup"],function(c){b[c]&&b[c].attr(a).invert()})}var b=this,c=b.chart;if(b.xAxis)N(c,"resize",a),N(b,"destroy",function(){X(c,"resize",a)}),a(),b.invertGroups=a},plotGroup:function(a,b,c,d, e){var f=this[a],g=!f;g&&(this[a]=f=this.chart.renderer.g(b).attr({visibility:c,zIndex:d||0.1}).add(e));f[g?"attr":"animate"](this.getPlotBox());return f},getPlotBox:function(){var a=this.chart,b=this.xAxis,c=this.yAxis;if(a.inverted)b=c,c=this.xAxis;return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:a.plotTop,scaleX:1,scaleY:1}},render:function(){var a=this,b=a.chart,c,d=a.options,e=(c=d.animation)&&!!a.animate&&b.renderer.isSVG&&p(c.duration,500)||0,f=a.visible?"visible":"hidden",g=d.zIndex, h=a.hasRendered,i=b.seriesGroup;c=a.plotGroup("group","series",f,g,i);a.markerGroup=a.plotGroup("markerGroup","markers",f,g,i);e&&a.animate(!0);a.getAttribs();c.inverted=a.isCartesian?b.inverted:!1;a.drawGraph&&(a.drawGraph(),a.clipNeg());a.drawDataLabels&&a.drawDataLabels();a.visible&&a.drawPoints();a.drawTracker&&a.options.enableMouseTracking!==!1&&a.drawTracker();b.inverted&&a.invertGroups();d.clip!==!1&&!a.sharedClipKey&&!h&&c.clip(b.clipRect);e&&a.animate();if(!h)e?a.animationTimeout=setTimeout(function(){a.afterAnimate()}, e):a.afterAnimate();a.isDirty=a.isDirtyData=!1;a.hasRendered=!0},redraw:function(){var a=this.chart,b=this.isDirtyData,c=this.group,d=this.xAxis,e=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:p(d&&d.left,a.plotLeft),translateY:p(e&&e.top,a.plotTop)}));this.translate();this.setTooltipPoints&&this.setTooltipPoints(!0);this.render();b&&K(this,"updatedData")}};Fb.prototype={destroy:function(){Oa(this,this.axis)},render:function(a){var b=this.options, c=b.format,c=c?Ia(c,this):b.formatter.call(this);this.label?this.label.attr({text:c,visibility:"hidden"}):this.label=this.axis.chart.renderer.text(c,null,null,b.useHTML).css(b.style).attr({align:this.textAlign,rotation:b.rotation,visibility:"hidden"}).add(a)},setOffset:function(a,b){var c=this.axis,d=c.chart,e=d.inverted,f=this.isNegative,g=c.translate(c.usePercentage?100:this.total,0,0,0,1),c=c.translate(0),c=Q(g-c),h=d.xAxis[0].translate(this.x)+a,i=d.plotHeight,f={x:e?f?g:g-c:h,y:e?i-h-b:f?i-g- c:i-g,width:e?c:b,height:e?b:c};if(e=this.label)e.align(this.alignOptions,null,f),f=e.alignAttr,e[this.options.crop===!1||d.isInsidePlot(f.x,f.y)?"show":"hide"](!0)}};ma.prototype.buildStacks=function(){var a=this.series,b=p(this.options.reversedStacks,!0),c=a.length;if(!this.isXAxis){for(this.usePercentage=!1;c--;)a[b?c:a.length-c-1].setStackedPoints();if(this.usePercentage)for(c=0;c<a.length;c++)a[c].setPercentStacks()}};ma.prototype.renderStackTotals=function(){var a=this.chart,b=a.renderer,c= this.stacks,d,e,f=this.stackTotalGroup;if(!f)this.stackTotalGroup=f=b.g("stack-labels").attr({visibility:"visible",zIndex:6}).add();f.translate(a.plotLeft,a.plotTop);for(d in c)for(e in a=c[d],a)a[e].render(f)};O.prototype.setStackedPoints=function(){if(this.options.stacking&&!(this.visible!==!0&&this.chart.options.chart.ignoreHiddenSeries!==!1)){var a=this.processedXData,b=this.processedYData,c=[],d=b.length,e=this.options,f=e.threshold,g=e.stack,e=e.stacking,h=this.stackKey,i="-"+h,j=this.negStacks, k=this.yAxis,l=k.stacks,m=k.oldStacks,n,o,p,q,r,s;for(q=0;q<d;q++){r=a[q];s=b[q];p=this.index+","+q;o=(n=j&&s<f)?i:h;l[o]||(l[o]={});if(!l[o][r])m[o]&&m[o][r]?(l[o][r]=m[o][r],l[o][r].total=null):l[o][r]=new Fb(k,k.options.stackLabels,n,r,g);o=l[o][r];o.points[p]=[o.cum||0];e==="percent"?(n=n?h:i,j&&l[n]&&l[n][r]?(n=l[n][r],o.total=n.total=u(n.total,o.total)+Q(s)||0):o.total=ea(o.total+(Q(s)||0))):o.total=ea(o.total+(s||0));o.cum=(o.cum||0)+(s||0);o.points[p].push(o.cum);c[q]=o.cum}if(e==="percent")k.usePercentage= !0;this.stackedYData=c;k.oldStacks={}}};O.prototype.setPercentStacks=function(){var a=this,b=a.stackKey,c=a.yAxis.stacks,d=a.processedXData;q([b,"-"+b],function(b){var e;for(var f=d.length,g,h;f--;)if(g=d[f],e=(h=c[b]&&c[b][g])&&h.points[a.index+","+f],g=e)h=h.total?100/h.total:0,g[0]=ea(g[0]*h),g[1]=ea(g[1]*h),a.stackedYData[f]=g[1]})};r(Xa.prototype,{addSeries:function(a,b,c){var d,e=this;a&&(b=p(b,!0),K(e,"addSeries",{options:a},function(){d=e.initSeries(a);e.isDirtyLegend=!0;e.linkSeries();b&& e.redraw(c)}));return d},addAxis:function(a,b,c,d){var e=b?"xAxis":"yAxis",f=this.options;new ma(this,w(a,{index:this[e].length,isX:b}));f[e]=ra(f[e]||{});f[e].push(a);p(c,!0)&&this.redraw(d)},showLoading:function(a){var b=this,c=b.options,d=b.loadingDiv,e=c.loading,f=function(){d&&A(d,{left:b.plotLeft+"px",top:b.plotTop+"px",width:b.plotWidth+"px",height:b.plotHeight+"px"})};if(!d)b.loadingDiv=d=$(Ja,{className:"highcharts-loading"},r(e.style,{zIndex:10,display:P}),b.container),b.loadingSpan=$("span", null,e.labelStyle,d),N(b,"redraw",f);b.loadingSpan.innerHTML=a||c.lang.loading;if(!b.loadingShown)A(d,{opacity:0,display:""}),ib(d,{opacity:e.style.opacity},{duration:e.showDuration||0}),b.loadingShown=!0;f()},hideLoading:function(){var a=this.options,b=this.loadingDiv;b&&ib(b,{opacity:0},{duration:a.loading.hideDuration||100,complete:function(){A(b,{display:P})}});this.loadingShown=!1}});r(Ea.prototype,{update:function(a,b,c){var d=this,e=d.series,f=d.graphic,g,h=e.data,i=e.chart,j=e.options,b=p(b, !0);d.firePointEvent("update",{options:a},function(){d.applyOptions(a);if(da(a)){e.getAttribs();if(f)a&&a.marker&&a.marker.symbol?d.graphic=f.destroy():f.attr(d.pointAttr[d.state||""]);if(a&&a.dataLabels&&d.dataLabel)d.dataLabel=d.dataLabel.destroy()}g=Da(d,h);e.updateParallelArrays(d,g);j.data[g]=d.options;e.isDirty=e.isDirtyData=!0;if(!e.fixedBox&&e.hasCartesianSeries)i.isDirtyBox=!0;j.legendType==="point"&&i.legend.destroyItem(d);b&&i.redraw(c)})},remove:function(a,b){var c=this,d=c.series,e=d.points, f=d.chart,g,h=d.data;Qa(b,f);a=p(a,!0);c.firePointEvent("remove",null,function(){g=Da(c,h);h.length===e.length&&e.splice(g,1);h.splice(g,1);d.options.data.splice(g,1);d.updateParallelArrays(c,"splice",g,1);c.destroy();d.isDirty=!0;d.isDirtyData=!0;a&&f.redraw()})}});r(O.prototype,{addPoint:function(a,b,c,d){var e=this.options,f=this.data,g=this.graph,h=this.area,i=this.chart,j=this.xAxis&&this.xAxis.names,k=g&&g.shift||0,l=e.data,m,n=this.xData;Qa(d,i);c&&q([g,h,this.graphNeg,this.areaNeg],function(a){if(a)a.shift= k+1});if(h)h.isArea=!0;b=p(b,!0);d={series:this};this.pointClass.prototype.applyOptions.apply(d,[a]);g=d.x;h=n.length;if(this.requireSorting&&g<n[h-1])for(m=!0;h&&n[h-1]>g;)h--;this.updateParallelArrays(d,"splice",h,0,0);this.updateParallelArrays(d,h);if(j)j[g]=d.name;l.splice(h,0,a);m&&(this.data.splice(h,0,null),this.processData());e.legendType==="point"&&this.generatePoints();c&&(f[0]&&f[0].remove?f[0].remove(!1):(f.shift(),this.updateParallelArrays(d,"shift"),l.shift()));this.isDirtyData=this.isDirty= !0;b&&(this.getAttribs(),i.redraw())},remove:function(a,b){var c=this,d=c.chart,a=p(a,!0);if(!c.isRemoving)c.isRemoving=!0,K(c,"remove",null,function(){c.destroy();d.isDirtyLegend=d.isDirtyBox=!0;d.linkSeries();a&&d.redraw(b)});c.isRemoving=!1},update:function(a,b){var c=this,d=this.chart,e=this.userOptions,f=this.type,g=J[f].prototype,h=["group","markerGroup","dataLabelsGroup"],i;q(h,function(a){h[a]=c[a];delete c[a]});a=w(e,{animation:!1,index:this.index,pointStart:this.xData[0]},{data:this.options.data}, a);this.remove(!1);for(i in g)g.hasOwnProperty(i)&&(this[i]=t);r(this,J[a.type||f].prototype);q(h,function(a){c[a]=h[a]});this.init(d,a);d.linkSeries();p(b,!0)&&d.redraw(!1)}});r(ma.prototype,{update:function(a,b){var c=this.chart,a=c.options[this.coll][this.options.index]=w(this.userOptions,a);this.destroy(!0);this._addedPlotLB=t;this.init(c,r(a,{events:t}));c.isDirtyBox=!0;p(b,!0)&&c.redraw()},remove:function(a){for(var b=this.chart,c=this.coll,d=this.series,e=d.length;e--;)d[e]&&d[e].remove(!1); ka(b.axes,this);ka(b[c],this);b.options[c].splice(this.options.index,1);q(b[c],function(a,b){a.options.index=b});this.destroy();b.isDirtyBox=!0;p(a,!0)&&b.redraw()},setTitle:function(a,b){this.update({title:a},b)},setCategories:function(a,b){this.update({categories:a},b)}});ha=la(O);J.line=ha;ca.area=w(T,{threshold:0});var qa=la(O,{type:"area",getSegments:function(){var a=this,b=[],c=[],d=[],e=this.xAxis,f=this.yAxis,g=f.stacks[this.stackKey],h={},i,j,k=this.points,l=this.options.connectNulls,m,n; if(this.options.stacking&&!this.cropped){for(m=0;m<k.length;m++)h[k[m].x]=k[m];for(n in g)g[n].total!==null&&d.push(+n);d.sort(function(a,b){return a-b});q(d,function(b){var d=0,k;if(!l||h[b]&&h[b].y!==null)if(h[b])c.push(h[b]);else{for(m=a.index;m<=f.series.length;m++)if(k=g[b].points[m+","+b]){d=k[1];break}i=e.translate(b);j=f.toPixels(d,!0);c.push({y:null,plotX:i,clientX:i,plotY:j,yBottom:j,onMouseOver:sa})}});c.length&&b.push(c)}else O.prototype.getSegments.call(this),b=this.segments;this.segments= b},getSegmentPath:function(a){var b=O.prototype.getSegmentPath.call(this,a),c=[].concat(b),d,e=this.options;d=b.length;var f=this.yAxis.getThreshold(e.threshold),g;d===3&&c.push("L",b[1],b[2]);if(e.stacking&&!this.closedStacks)for(d=a.length-1;d>=0;d--)g=p(a[d].yBottom,f),d<a.length-1&&e.step&&c.push(a[d+1].plotX,g),c.push(a[d].plotX,g);else this.closeSegment(c,a,f);this.areaPath=this.areaPath.concat(c);return b},closeSegment:function(a,b,c){a.push("L",b[b.length-1].plotX,c,"L",b[0].plotX,c)},drawGraph:function(){this.areaPath= [];O.prototype.drawGraph.apply(this);var a=this,b=this.areaPath,c=this.options,d=c.negativeColor,e=c.negativeFillColor,f=[["area",this.color,c.fillColor]];(d||e)&&f.push(["areaNeg",d,e]);q(f,function(d){var e=d[0],f=a[e];f?f.animate({d:b}):a[e]=a.chart.renderer.path(b).attr({fill:p(d[2],ya(d[1]).setOpacity(p(c.fillOpacity,0.75)).get()),zIndex:0}).add(a.group)})},drawLegendSymbol:M.drawRectangle});J.area=qa;ca.spline=w(T);ha=la(O,{type:"spline",getPointSpline:function(a,b,c){var d=b.plotX,e=b.plotY, f=a[c-1],g=a[c+1],h,i,j,k;if(f&&g){a=f.plotY;j=g.plotX;var g=g.plotY,l;h=(1.5*d+f.plotX)/2.5;i=(1.5*e+a)/2.5;j=(1.5*d+j)/2.5;k=(1.5*e+g)/2.5;l=(k-i)*(j-d)/(j-h)+e-k;i+=l;k+=l;i>a&&i>e?(i=u(a,e),k=2*e-i):i<a&&i<e&&(i=C(a,e),k=2*e-i);k>g&&k>e?(k=u(g,e),i=2*e-k):k<g&&k<e&&(k=C(g,e),i=2*e-k);b.rightContX=j;b.rightContY=k}c?(b=["C",f.rightContX||f.plotX,f.rightContY||f.plotY,h||d,i||e,d,e],f.rightContX=f.rightContY=null):b=["M",d,e];return b}});J.spline=ha;ca.areaspline=w(ca.area);qa=qa.prototype;ha=la(ha, {type:"areaspline",closedStacks:!0,getSegmentPath:qa.getSegmentPath,closeSegment:qa.closeSegment,drawGraph:qa.drawGraph,drawLegendSymbol:M.drawRectangle});J.areaspline=ha;ca.column=w(T,{borderColor:"#FFFFFF",borderRadius:0,groupPadding:0.2,marker:null,pointPadding:0.1,minPointLength:0,cropThreshold:50,pointRange:null,states:{hover:{brightness:0.1,shadow:!1,halo:!1},select:{color:"#C0C0C0",borderColor:"#000000",shadow:!1}},dataLabels:{align:null,verticalAlign:null,y:null},stickyTracking:!1,tooltip:{distance:6}, threshold:0});ha=la(O,{type:"column",pointAttrToOptions:{stroke:"borderColor",fill:"color",r:"borderRadius"},cropShoulder:0,trackerGroups:["group","dataLabelsGroup"],negStacks:!0,init:function(){O.prototype.init.apply(this,arguments);var a=this,b=a.chart;b.hasRendered&&q(b.series,function(b){if(b.type===a.type)b.isDirty=!0})},getColumnMetrics:function(){var a=this,b=a.options,c=a.xAxis,d=a.yAxis,e=c.reversed,f,g={},h,i=0;b.grouping===!1?i=1:q(a.chart.series,function(b){var c=b.options,e=b.yAxis;if(b.type=== a.type&&b.visible&&d.len===e.len&&d.pos===e.pos)c.stacking?(f=b.stackKey,g[f]===t&&(g[f]=i++),h=g[f]):c.grouping!==!1&&(h=i++),b.columnIndex=h});var c=C(Q(c.transA)*(c.ordinalSlope||b.pointRange||c.closestPointRange||c.tickInterval||1),c.len),j=c*b.groupPadding,k=(c-2*j)/i,l=b.pointWidth,b=s(l)?(k-l)/2:k*b.pointPadding,l=p(l,k-2*b);return a.columnMetrics={width:l,offset:b+(j+((e?i-(a.columnIndex||0):a.columnIndex)||0)*k-c/2)*(e?-1:1)}},translate:function(){var a=this,b=a.chart,c=a.options,d=a.borderWidth= p(c.borderWidth,a.activePointCount>0.5*a.xAxis.len?0:1),e=a.yAxis,f=a.translatedThreshold=e.getThreshold(c.threshold),g=p(c.minPointLength,5),h=a.getColumnMetrics(),i=h.width,j=a.barW=u(i,1+2*d),k=a.pointXOffset=h.offset,l=-(d%2?0.5:0),m=d%2?0.5:1;b.renderer.isVML&&b.inverted&&(m+=1);c.pointPadding&&(j=Ka(j));O.prototype.translate.apply(a);q(a.points,function(c){var d=p(c.yBottom,f),h=C(u(-999-d,c.plotY),e.len+999+d),q=c.plotX+k,r=j,s=C(h,d),t;t=u(h,d)-s;Q(t)<g&&g&&(t=g,s=v(Q(s-f)>g?d-g:f-(e.translate(c.y, 0,1,0,1)<=f?g:0)));c.barX=q;c.pointWidth=i;c.tooltipPos=b.inverted?[e.len-h,a.xAxis.len-q-r/2]:[q+r/2,h];r=v(q+r)+l;q=v(q)+l;r-=q;d=Q(s)<0.5;t=v(s+t)+m;s=v(s)+m;t-=s;d&&(s-=1,t+=1);c.shapeType="rect";c.shapeArgs={x:q,y:s,width:r,height:t}})},getSymbol:sa,drawLegendSymbol:M.drawRectangle,drawGraph:sa,drawPoints:function(){var a=this,b=this.chart,c=a.options,d=b.renderer,e=c.animationLimit||250,f,g;q(a.points,function(h){var i=h.plotY,j=h.graphic;if(i!==t&&!isNaN(i)&&h.y!==null)f=h.shapeArgs,i=s(a.borderWidth)? {"stroke-width":a.borderWidth}:{},g=h.pointAttr[h.selected?"select":""]||a.pointAttr[""],j?(ab(j),j.attr(i)[b.pointCount<e?"animate":"attr"](w(f))):h.graphic=d[h.shapeType](f).attr(g).attr(i).add(a.group).shadow(c.shadow,null,c.stacking&&!c.borderRadius);else if(j)h.graphic=j.destroy()})},animate:function(a){var b=this.yAxis,c=this.options,d=this.chart.inverted,e={};if(ba)a?(e.scaleY=0.001,a=C(b.pos+b.len,u(b.pos,b.toPixels(c.threshold))),d?e.translateX=a-b.len:e.translateY=a,this.group.attr(e)): (e.scaleY=1,e[d?"translateX":"translateY"]=b.pos,this.group.animate(e,this.options.animation),this.animate=null)},remove:function(){var a=this,b=a.chart;b.hasRendered&&q(b.series,function(b){if(b.type===a.type)b.isDirty=!0});O.prototype.remove.apply(a,arguments)}});J.column=ha;ca.bar=w(ca.column);qa=la(ha,{type:"bar",inverted:!0});J.bar=qa;ca.scatter=w(T,{lineWidth:0,tooltip:{headerFormat:'<span style="color:{series.color}">??</span> <span style="font-size: 10px;"> {series.name}</span><br/>',pointFormat:"x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>"}, stickyTracking:!1});qa=la(O,{type:"scatter",sorted:!1,requireSorting:!1,noSharedTooltip:!0,trackerGroups:["markerGroup","dataLabelsGroup"],takeOrdinalPosition:!1,singularTooltips:!0,drawGraph:function(){this.options.lineWidth&&O.prototype.drawGraph.call(this)}});J.scatter=qa;ca.pie=w(T,{borderColor:"#FFFFFF",borderWidth:1,center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{distance:30,enabled:!0,formatter:function(){return this.point.name}},ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null, showInLegend:!1,slicedOffset:10,states:{hover:{brightness:0.1,shadow:!1}},stickyTracking:!1,tooltip:{followPointer:!0}});T={type:"pie",isCartesian:!1,pointClass:la(Ea,{init:function(){Ea.prototype.init.apply(this,arguments);var a=this,b;if(a.y<0)a.y=null;r(a,{visible:a.visible!==!1,name:p(a.name,"Slice")});b=function(b){a.slice(b.type==="select")};N(a,"select",b);N(a,"unselect",b);return a},setVisible:function(a){var b=this,c=b.series,d=c.chart;b.visible=b.options.visible=a=a===t?!b.visible:a;c.options.data[Da(b, c.data)]=b.options;q(["graphic","dataLabel","connector","shadowGroup"],function(c){if(b[c])b[c][a?"show":"hide"](!0)});b.legendItem&&d.legend.colorizeItem(b,a);if(!c.isDirty&&c.options.ignoreHiddenPoint)c.isDirty=!0,d.redraw()},slice:function(a,b,c){var d=this.series;Qa(c,d.chart);p(b,!0);this.sliced=this.options.sliced=a=s(a)?a:!this.sliced;d.options.data[Da(this,d.data)]=this.options;a=a?this.slicedTranslation:{translateX:0,translateY:0};this.graphic.animate(a);this.shadowGroup&&this.shadowGroup.animate(a)}, haloPath:function(a){var b=this.shapeArgs,c=this.series.chart;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(c.plotLeft+b.x,c.plotTop+b.y,b.r+a,b.r+a,{innerR:this.shapeArgs.r,start:b.start,end:b.end})}}),requireSorting:!1,noSharedTooltip:!0,trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color"},singularTooltips:!0,getColor:sa,animate:function(a){var b=this,c=b.points,d=b.startAngleRad; if(!a)q(c,function(a){var c=a.graphic,a=a.shapeArgs;c&&(c.attr({r:b.center[3]/2,start:d,end:d}),c.animate({r:a.r,start:a.start,end:a.end},b.options.animation))}),b.animate=null},setData:function(a,b,c,d){O.prototype.setData.call(this,a,!1,c,d);this.processData();this.generatePoints();p(b,!0)&&this.chart.redraw(c)},generatePoints:function(){var a,b=0,c,d,e,f=this.options.ignoreHiddenPoint;O.prototype.generatePoints.call(this);c=this.points;d=c.length;for(a=0;a<d;a++)e=c[a],b+=f&&!e.visible?0:e.y;this.total= b;for(a=0;a<d;a++)e=c[a],e.percentage=b>0?e.y/b*100:0,e.total=b},translate:function(a){this.generatePoints();var b=0,c=this.options,d=c.slicedOffset,e=d+c.borderWidth,f,g,h,i=c.startAngle||0,j=this.startAngleRad=na/180*(i-90),i=(this.endAngleRad=na/180*(p(c.endAngle,i+360)-90))-j,k=this.points,l=c.dataLabels.distance,c=c.ignoreHiddenPoint,m,n=k.length,o;if(!a)this.center=a=this.getCenter();this.getX=function(b,c){h=V.asin(C((b-a[1])/(a[2]/2+l),1));return a[0]+(c?-1:1)*aa(h)*(a[2]/2+l)};for(m=0;m< n;m++){o=k[m];f=j+b*i;if(!c||o.visible)b+=o.percentage/100;g=j+b*i;o.shapeType="arc";o.shapeArgs={x:a[0],y:a[1],r:a[2]/2,innerR:a[3]/2,start:v(f*1E3)/1E3,end:v(g*1E3)/1E3};h=(g+f)/2;h>1.5*na?h-=2*na:h<-na/2&&(h+=2*na);o.slicedTranslation={translateX:v(aa(h)*d),translateY:v(fa(h)*d)};f=aa(h)*a[2]/2;g=fa(h)*a[2]/2;o.tooltipPos=[a[0]+f*0.7,a[1]+g*0.7];o.half=h<-na/2||h>na/2?1:0;o.angle=h;e=C(e,l/2);o.labelPos=[a[0]+f+aa(h)*l,a[1]+g+fa(h)*l,a[0]+f+aa(h)*e,a[1]+g+fa(h)*e,a[0]+f,a[1]+g,l<0?"center":o.half? "right":"left",h]}},drawGraph:null,drawPoints:function(){var a=this,b=a.chart.renderer,c,d,e=a.options.shadow,f,g;if(e&&!a.shadowGroup)a.shadowGroup=b.g("shadow").add(a.group);q(a.points,function(h){d=h.graphic;g=h.shapeArgs;f=h.shadowGroup;if(e&&!f)f=h.shadowGroup=b.g("shadow").add(a.shadowGroup);c=h.sliced?h.slicedTranslation:{translateX:0,translateY:0};f&&f.attr(c);d?d.animate(r(g,c)):h.graphic=d=b[h.shapeType](g).setRadialReference(a.center).attr(h.pointAttr[h.selected?"select":""]).attr({"stroke-linejoin":"round"}).attr(c).add(a.group).shadow(e, f);h.visible!==void 0&&h.setVisible(h.visible)})},sortByAngle:function(a,b){a.sort(function(a,d){return a.angle!==void 0&&(d.angle-a.angle)*b})},drawLegendSymbol:M.drawRectangle,getCenter:Z.getCenter,getSymbol:sa};T=la(O,T);J.pie=T;O.prototype.drawDataLabels=function(){var a=this,b=a.options,c=b.cursor,d=b.dataLabels,e=a.points,f,g,h,i;if(d.enabled||a._hasPointLabels)a.dlProcessOptions&&a.dlProcessOptions(d),i=a.plotGroup("dataLabelsGroup","data-labels",d.defer?"hidden":"visible",d.zIndex||6),!a.hasRendered&& p(d.defer,!0)&&(i.attr({opacity:0}),N(a,"afterAnimate",function(){a.visible&&i.show();i[b.animation?"animate":"attr"]({opacity:1},{duration:200})})),g=d,q(e,function(b){var e,l=b.dataLabel,m,n,o=b.connector,q=!0;f=b.options&&b.options.dataLabels;e=p(f&&f.enabled,g.enabled);if(l&&!e)b.dataLabel=l.destroy();else if(e){d=w(g,f);e=d.rotation;m=b.getLabelConfig();h=d.format?Ia(d.format,m):d.formatter.call(m,d);d.style.color=p(d.color,d.style.color,a.color,"black");if(l)if(s(h))l.attr({text:h}),q=!1;else{if(b.dataLabel= l=l.destroy(),o)b.connector=o.destroy()}else if(s(h)){l={fill:d.backgroundColor,stroke:d.borderColor,"stroke-width":d.borderWidth,r:d.borderRadius||0,rotation:e,padding:d.padding,zIndex:1};for(n in l)l[n]===t&&delete l[n];l=b.dataLabel=a.chart.renderer[e?"text":"label"](h,0,-999,null,null,null,d.useHTML).attr(l).css(r(d.style,c&&{cursor:c})).add(i).shadow(d.shadow)}l&&a.alignDataLabel(b,l,d,null,q)}})};O.prototype.alignDataLabel=function(a,b,c,d,e){var f=this.chart,g=f.inverted,h=p(a.plotX,-999), i=p(a.plotY,-999),j=b.getBBox();if(a=this.visible&&(a.series.forceDL||f.isInsidePlot(h,v(i),g)||d&&f.isInsidePlot(h,g?d.x+1:d.y+d.height-1,g)))d=r({x:g?f.plotWidth-i:h,y:v(g?f.plotHeight-h:i),width:0,height:0},d),r(c,{width:j.width,height:j.height}),c.rotation?b[e?"attr":"animate"]({x:d.x+c.x+d.width/2,y:d.y+c.y+d.height/2}).attr({align:c.align}):(b.align(c,null,d),g=b.alignAttr,p(c.overflow,"justify")==="justify"?this.justifyDataLabel(b,c,g,j,d,e):p(c.crop,!0)&&(a=f.isInsidePlot(g.x,g.y)&&f.isInsidePlot(g.x+ j.width,g.y+j.height)));if(!a)b.attr({y:-999}),b.placed=!1};O.prototype.justifyDataLabel=function(a,b,c,d,e,f){var g=this.chart,h=b.align,i=b.verticalAlign,j,k;j=c.x;if(j<0)h==="right"?b.align="left":b.x=-j,k=!0;j=c.x+d.width;if(j>g.plotWidth)h==="left"?b.align="right":b.x=g.plotWidth-j,k=!0;j=c.y;if(j<0)i==="bottom"?b.verticalAlign="top":b.y=-j,k=!0;j=c.y+d.height;if(j>g.plotHeight)i==="top"?b.verticalAlign="bottom":b.y=g.plotHeight-j,k=!0;if(k)a.placed=!f,a.align(b,null,e)};if(J.pie)J.pie.prototype.drawDataLabels= function(){var a=this,b=a.data,c,d=a.chart,e=a.options.dataLabels,f=p(e.connectorPadding,10),g=p(e.connectorWidth,1),h=d.plotWidth,i=d.plotHeight,j,k,l=p(e.softConnector,!0),m=e.distance,n=a.center,o=n[2]/2,r=n[1],s=m>0,t,w,x,z=[[],[]],B,A,K,J,y,R=[0,0,0,0],N=function(a,b){return b.y-a.y};if(a.visible&&(e.enabled||a._hasPointLabels)){O.prototype.drawDataLabels.apply(a);q(b,function(a){a.dataLabel&&a.visible&&z[a.half].push(a)});for(J=2;J--;){var H=[],M=[],F=z[J],L=F.length,G;if(L){a.sortByAngle(F, J-0.5);for(y=b=0;!b&&F[y];)b=F[y]&&F[y].dataLabel&&(F[y].dataLabel.getBBox().height||21),y++;if(m>0){w=C(r+o+m,d.plotHeight);for(y=u(0,r-o-m);y<=w;y+=b)H.push(y);w=H.length;if(L>w){c=[].concat(F);c.sort(N);for(y=L;y--;)c[y].rank=y;for(y=L;y--;)F[y].rank>=w&&F.splice(y,1);L=F.length}for(y=0;y<L;y++){c=F[y];x=c.labelPos;c=9999;var S,P;for(P=0;P<w;P++)S=Q(H[P]-x[1]),S<c&&(c=S,G=P);if(G<y&&H[y]!==null)G=y;else for(w<L-y+G&&H[y]!==null&&(G=w-L+y);H[G]===null;)G++;M.push({i:G,y:H[G]});H[G]=null}M.sort(N)}for(y= 0;y<L;y++){c=F[y];x=c.labelPos;t=c.dataLabel;K=c.visible===!1?"hidden":"visible";c=x[1];if(m>0){if(w=M.pop(),G=w.i,A=w.y,c>A&&H[G+1]!==null||c<A&&H[G-1]!==null)A=C(u(0,c),d.plotHeight)}else A=c;B=e.justify?n[0]+(J?-1:1)*(o+m):a.getX(A===r-o-m||A===r+o+m?c:A,J);t._attr={visibility:K,align:x[6]};t._pos={x:B+e.x+({left:f,right:-f}[x[6]]||0),y:A+e.y-10};t.connX=B;t.connY=A;if(this.options.size===null)w=t.width,B-w<f?R[3]=u(v(w-B+f),R[3]):B+w>h-f&&(R[1]=u(v(B+w-h+f),R[1])),A-b/2<0?R[0]=u(v(-A+b/2),R[0]): A+b/2>i&&(R[2]=u(v(A+b/2-i),R[2]))}}}if(Ba(R)===0||this.verifyDataLabelOverflow(R))this.placeDataLabels(),s&&g&&q(this.points,function(b){j=b.connector;x=b.labelPos;if((t=b.dataLabel)&&t._pos)K=t._attr.visibility,B=t.connX,A=t.connY,k=l?["M",B+(x[6]==="left"?5:-5),A,"C",B,A,2*x[2]-x[4],2*x[3]-x[5],x[2],x[3],"L",x[4],x[5]]:["M",B+(x[6]==="left"?5:-5),A,"L",x[2],x[3],"L",x[4],x[5]],j?(j.animate({d:k}),j.attr("visibility",K)):b.connector=j=a.chart.renderer.path(k).attr({"stroke-width":g,stroke:e.connectorColor|| b.color||"#606060",visibility:K}).add(a.dataLabelsGroup);else if(j)b.connector=j.destroy()})}},J.pie.prototype.placeDataLabels=function(){q(this.points,function(a){var a=a.dataLabel,b;if(a)(b=a._pos)?(a.attr(a._attr),a[a.moved?"animate":"attr"](b),a.moved=!0):a&&a.attr({y:-999})})},J.pie.prototype.alignDataLabel=sa,J.pie.prototype.verifyDataLabelOverflow=function(a){var b=this.center,c=this.options,d=c.center,e=c=c.minSize||80,f;d[0]!==null?e=u(b[2]-u(a[1],a[3]),c):(e=u(b[2]-a[1]-a[3],c),b[0]+=(a[3]- a[1])/2);d[1]!==null?e=u(C(e,b[2]-u(a[0],a[2])),c):(e=u(C(e,b[2]-a[0]-a[2]),c),b[1]+=(a[0]-a[2])/2);e<b[2]?(b[2]=e,this.translate(b),q(this.points,function(a){if(a.dataLabel)a.dataLabel._pos=null}),this.drawDataLabels&&this.drawDataLabels()):f=!0;return f};if(J.column)J.column.prototype.alignDataLabel=function(a,b,c,d,e){var f=this.chart,g=f.inverted,h=a.dlBox||a.shapeArgs,i=a.below||a.plotY>p(this.translatedThreshold,f.plotSizeY),j=p(c.inside,!!this.options.stacking);if(h&&(d=w(h),g&&(d={x:f.plotWidth- d.y-d.height,y:f.plotHeight-d.x-d.width,width:d.height,height:d.width}),!j))g?(d.x+=i?0:d.width,d.width=0):(d.y+=i?d.height:0,d.height=0);c.align=p(c.align,!g||j?"center":i?"right":"left");c.verticalAlign=p(c.verticalAlign,g||j?"middle":i?"top":"bottom");O.prototype.alignDataLabel.call(this,a,b,c,d,e)};T=S.TrackerMixin={drawTrackerPoint:function(){var a=this,b=a.chart,c=b.pointer,d=a.options.cursor,e=d&&{cursor:d},f=function(c){var d=c.target,e;if(b.hoverSeries!==a)a.onMouseOver();for(;d&&!e;)e=d.point, d=d.parentNode;if(e!==t&&e!==b.hoverPoint)e.onMouseOver(c)};q(a.points,function(a){if(a.graphic)a.graphic.element.point=a;if(a.dataLabel)a.dataLabel.element.point=a});if(!a._hasTracking)q(a.trackerGroups,function(b){if(a[b]&&(a[b].addClass("highcharts-tracker").on("mouseover",f).on("mouseout",function(a){c.onTrackerMouseOut(a)}).css(e),Za))a[b].on("touchstart",f)}),a._hasTracking=!0},drawTrackerGraph:function(){var a=this,b=a.options,c=b.trackByArea,d=[].concat(c?a.areaPath:a.graphPath),e=d.length, f=a.chart,g=f.pointer,h=f.renderer,i=f.options.tooltip.snap,j=a.tracker,k=b.cursor,l=k&&{cursor:k},k=a.singlePoints,m,n=function(){if(f.hoverSeries!==a)a.onMouseOver()},o="rgba(192,192,192,"+(ba?1.0E-4:0.002)+")";if(e&&!c)for(m=e+1;m--;)d[m]==="M"&&d.splice(m+1,0,d[m+1]-i,d[m+2],"L"),(m&&d[m]==="M"||m===e)&&d.splice(m,0,"L",d[m-2]+i,d[m-1]);for(m=0;m<k.length;m++)e=k[m],d.push("M",e.plotX-i,e.plotY,"L",e.plotX+i,e.plotY);j?j.attr({d:d}):(a.tracker=h.path(d).attr({"stroke-linejoin":"round",visibility:a.visible? "visible":"hidden",stroke:o,fill:c?o:P,"stroke-width":b.lineWidth+(c?0:2*i),zIndex:2}).add(a.group),q([a.tracker,a.markerGroup],function(a){a.addClass("highcharts-tracker").on("mouseover",n).on("mouseout",function(a){g.onTrackerMouseOut(a)}).css(l);if(Za)a.on("touchstart",n)}))}};if(J.column)ha.prototype.drawTracker=T.drawTrackerPoint;if(J.pie)J.pie.prototype.drawTracker=T.drawTrackerPoint;if(J.scatter)qa.prototype.drawTracker=T.drawTrackerPoint;r(kb.prototype,{setItemEvents:function(a,b,c,d,e){var f= this;(c?b:a.legendGroup).on("mouseover",function(){a.setState("hover");b.css(f.options.itemHoverStyle)}).on("mouseout",function(){b.css(a.visible?d:e);a.setState()}).on("click",function(b){var c=function(){a.setVisible()},b={browserEvent:b};a.firePointEvent?a.firePointEvent("legendItemClick",b,c):K(a,"legendItemClick",b,c)})},createCheckboxForItem:function(a){a.checkbox=$("input",{type:"checkbox",checked:a.selected,defaultChecked:a.selected},this.options.itemCheckboxStyle,this.chart.container);N(a.checkbox, "click",function(b){K(a,"checkboxClick",{checked:b.target.checked},function(){a.select()})})}});L.legend.itemStyle.cursor="pointer";r(Xa.prototype,{showResetZoom:function(){var a=this,b=L.lang,c=a.options.chart.resetZoomButton,d=c.theme,e=d.states,f=c.relativeTo==="chart"?null:"plotBox";this.resetZoomButton=a.renderer.button(b.resetZoom,null,null,function(){a.zoomOut()},d,e&&e.hover).attr({align:c.position.align,title:b.resetZoomTitle}).add().align(c.position,!1,f)},zoomOut:function(){var a=this; K(a,"selection",{resetSelection:!0},function(){a.zoom()})},zoom:function(a){var b,c=this.pointer,d=!1,e;!a||a.resetSelection?q(this.axes,function(a){b=a.zoom()}):q(a.xAxis.concat(a.yAxis),function(a){var e=a.axis,h=e.isXAxis;if(c[h?"zoomX":"zoomY"]||c[h?"pinchX":"pinchY"])b=e.zoom(a.min,a.max),e.displayBtn&&(d=!0)});e=this.resetZoomButton;if(d&&!e)this.showResetZoom();else if(!d&&da(e))this.resetZoomButton=e.destroy();b&&this.redraw(p(this.options.chart.animation,a&&a.animation,this.pointCount<100))}, pan:function(a,b){var c=this,d=c.hoverPoints,e;d&&q(d,function(a){a.setState()});q(b==="xy"?[1,0]:[1],function(b){var d=a[b?"chartX":"chartY"],h=c[b?"xAxis":"yAxis"][0],i=c[b?"mouseDownX":"mouseDownY"],j=(h.pointRange||0)/2,k=h.getExtremes(),l=h.toValue(i-d,!0)+j,i=h.toValue(i+c[b?"plotWidth":"plotHeight"]-d,!0)-j;h.series.length&&l>C(k.dataMin,k.min)&&i<u(k.dataMax,k.max)&&(h.setExtremes(l,i,!1,!1,{trigger:"pan"}),e=!0);c[b?"mouseDownX":"mouseDownY"]=d});e&&c.redraw(!1);A(c.container,{cursor:"move"})}}); r(Ea.prototype,{select:function(a,b){var c=this,d=c.series,e=d.chart,a=p(a,!c.selected);c.firePointEvent(a?"select":"unselect",{accumulate:b},function(){c.selected=c.options.selected=a;d.options.data[Da(c,d.data)]=c.options;c.setState(a&&"select");b||q(e.getSelectedPoints(),function(a){if(a.selected&&a!==c)a.selected=a.options.selected=!1,d.options.data[Da(a,d.data)]=a.options,a.setState(""),a.firePointEvent("unselect")})})},onMouseOver:function(a){var b=this.series,c=b.chart,d=c.tooltip,e=c.hoverPoint; if(e&&e!==this)e.onMouseOut();this.firePointEvent("mouseOver");d&&(!d.shared||b.noSharedTooltip)&&d.refresh(this,a);this.setState("hover");c.hoverPoint=this},onMouseOut:function(){var a=this.series.chart,b=a.hoverPoints;this.firePointEvent("mouseOut");if(!b||Da(this,b)===-1)this.setState(),a.hoverPoint=null},importEvents:function(){if(!this.hasImportedEvents){var a=w(this.series.options.point,this.options).events,b;this.events=a;for(b in a)N(this,b,a[b]);this.hasImportedEvents=!0}},setState:function(a, b){var c=this.plotX,d=this.plotY,e=this.series,f=e.options.states,g=ca[e.type].marker&&e.options.marker,h=g&&!g.enabled,i=g&&g.states[a],j=i&&i.enabled===!1,k=e.stateMarkerGraphic,l=this.marker||{},m=e.chart,n=e.halo,o,a=a||"";o=this.pointAttr[a]||e.pointAttr[a];if(!(a===this.state&&!b||this.selected&&a!=="select"||f[a]&&f[a].enabled===!1||a&&(j||h&&i.enabled===!1)||a&&l.states&&l.states[a]&&l.states[a].enabled===!1)){if(this.graphic)g=g&&this.graphic.symbolName&&o.r,this.graphic.attr(w(o,g?{x:c- g,y:d-g,width:2*g,height:2*g}:{})),k&&k.hide();else{if(a&&i)if(g=i.radius,l=l.symbol||e.symbol,k&&k.currentSymbol!==l&&(k=k.destroy()),k)k[b?"animate":"attr"]({x:c-g,y:d-g});else if(l)e.stateMarkerGraphic=k=m.renderer.symbol(l,c-g,d-g,2*g,2*g).attr(o).add(e.markerGroup),k.currentSymbol=l;if(k)k[a&&m.isInsidePlot(c,d,m.inverted)?"show":"hide"]()}if((c=f[a]&&f[a].halo)&&c.size){if(!n)e.halo=n=m.renderer.path().add(e.seriesGroup);n.attr(r({fill:ya(this.color||e.color).setOpacity(c.opacity).get()},c.attributes))[b? "animate":"attr"]({d:this.haloPath(c.size)})}else n&&n.attr({d:[]});this.state=a}},haloPath:function(a){var b=this.series,c=b.chart,d=b.getPlotBox(),e=c.inverted;return c.renderer.symbols.circle(d.translateX+(e?b.yAxis.len-this.plotY:this.plotX)-a,d.translateY+(e?b.xAxis.len-this.plotX:this.plotY)-a,a*2,a*2)}});r(O.prototype,{onMouseOver:function(){var a=this.chart,b=a.hoverSeries;if(b&&b!==this)b.onMouseOut();this.options.events.mouseOver&&K(this,"mouseOver");this.setState("hover");a.hoverSeries= this},onMouseOut:function(){var a=this.options,b=this.chart,c=b.tooltip,d=b.hoverPoint;if(d)d.onMouseOut();this&&a.events.mouseOut&&K(this,"mouseOut");c&&!a.stickyTracking&&(!c.shared||this.noSharedTooltip)&&c.hide();this.setState();b.hoverSeries=null},setState:function(a){var b=this.options,c=this.graph,d=this.graphNeg,e=b.states,b=b.lineWidth,a=a||"";if(this.state!==a)this.state=a,e[a]&&e[a].enabled===!1||(a&&(b=e[a].lineWidth||b+(e[a].lineWidthPlus||0)),c&&!c.dashstyle&&(a={"stroke-width":b},c.attr(a), d&&d.attr(a)))},setVisible:function(a,b){var c=this,d=c.chart,e=c.legendItem,f,g=d.options.chart.ignoreHiddenSeries,h=c.visible;f=(c.visible=a=c.userOptions.visible=a===t?!h:a)?"show":"hide";q(["group","dataLabelsGroup","markerGroup","tracker"],function(a){if(c[a])c[a][f]()});if(d.hoverSeries===c)c.onMouseOut();e&&d.legend.colorizeItem(c,a);c.isDirty=!0;c.options.stacking&&q(d.series,function(a){if(a.options.stacking&&a.visible)a.isDirty=!0});q(c.linkedSeries,function(b){b.setVisible(a,!1)});if(g)d.isDirtyBox= !0;b!==!1&&d.redraw();K(c,f)},setTooltipPoints:function(a){var b=[],c,d,e=this.xAxis,f=e&&e.getExtremes(),g=e?e.tooltipLen||e.len:this.chart.plotSizeX,h,i,j=[];if(!(this.options.enableMouseTracking===!1||this.singularTooltips)){if(a)this.tooltipPoints=null;q(this.segments||this.points,function(a){b=b.concat(a)});e&&e.reversed&&(b=b.reverse());this.orderTooltipPoints&&this.orderTooltipPoints(b);a=b.length;for(i=0;i<a;i++)if(e=b[i],c=e.x,c>=f.min&&c<=f.max){h=b[i+1];c=d===t?0:d+1;for(d=b[i+1]?C(u(0, U((e.clientX+(h?h.wrappedClientX||h.clientX:g))/2)),g):g;c>=0&&c<=d;)j[c++]=e}this.tooltipPoints=j}},show:function(){this.setVisible(!0)},hide:function(){this.setVisible(!1)},select:function(a){this.selected=a=a===t?!this.selected:a;if(this.checkbox)this.checkbox.checked=a;K(this,a?"select":"unselect")},drawTracker:T.drawTrackerGraph});r(S,{Axis:ma,Chart:Xa,Color:ya,Point:Ea,Tick:Sa,Renderer:Ya,Series:O,SVGElement:G,SVGRenderer:ta,arrayMin:Na,arrayMax:Ba,charts:W,dateFormat:bb,format:Ia,pathAnim:ub, getOptions:function(){return L},hasBidiBug:Nb,isTouchDevice:Hb,numberFormat:Ga,seriesTypes:J,setOptions:function(a){L=w(!0,L,a);Ab();return L},addEvent:N,removeEvent:X,createElement:$,discardElement:Pa,css:A,each:q,extend:r,map:Ua,merge:w,pick:p,splat:ra,extendClass:la,pInt:z,wrap:Ma,svg:ba,canvas:ga,vml:!ba&&!ga,product:"Highcharts",version:"4.0.3"})})(); /* Highcharts JS v4.0.3 (2014-07-03) (c) 2009-2014 Torstein Honsi License: www.highcharts.com/license */ (function(l,C){function K(a,b,c){this.init.call(this,a,b,c)}var P=l.arrayMin,Q=l.arrayMax,s=l.each,F=l.extend,q=l.merge,R=l.map,o=l.pick,x=l.pInt,p=l.getOptions().plotOptions,g=l.seriesTypes,v=l.extendClass,L=l.splat,r=l.wrap,M=l.Axis,y=l.Tick,H=l.Point,S=l.Pointer,T=l.CenteredSeriesMixin,z=l.TrackerMixin,t=l.Series,w=Math,D=w.round,A=w.floor,N=w.max,U=l.Color,u=function(){};F(K.prototype,{init:function(a,b,c){var d=this,e=d.defaultOptions;d.chart=b;if(b.angular)e.background={};d.options=a=q(e,a); (a=a.background)&&s([].concat(L(a)).reverse(),function(a){var b=a.backgroundColor,a=q(d.defaultBackgroundOptions,a);if(b)a.backgroundColor=b;a.color=a.backgroundColor;c.options.plotBands.unshift(a)})},defaultOptions:{center:["50%","50%"],size:"85%",startAngle:0},defaultBackgroundOptions:{shape:"circle",borderWidth:1,borderColor:"silver",backgroundColor:{linearGradient:{x1:0,y1:0,x2:0,y2:1},stops:[[0,"#FFF"],[1,"#DDD"]]},from:-Number.MAX_VALUE,innerRadius:0,to:Number.MAX_VALUE,outerRadius:"105%"}}); var G=M.prototype,y=y.prototype,V={getOffset:u,redraw:function(){this.isDirty=!1},render:function(){this.isDirty=!1},setScale:u,setCategories:u,setTitle:u},O={isRadial:!0,defaultRadialGaugeOptions:{labels:{align:"center",x:0,y:null},minorGridLineWidth:0,minorTickInterval:"auto",minorTickLength:10,minorTickPosition:"inside",minorTickWidth:1,tickLength:10,tickPosition:"inside",tickWidth:2,title:{rotation:0},zIndex:2},defaultRadialXOptions:{gridLineWidth:1,labels:{align:null,distance:15,x:0,y:null}, maxPadding:0,minPadding:0,showLastLabel:!1,tickLength:0},defaultRadialYOptions:{gridLineInterpolation:"circle",labels:{align:"right",x:-3,y:-2},showLastLabel:!1,title:{x:4,text:null,rotation:90}},setOptions:function(a){a=this.options=q(this.defaultOptions,this.defaultRadialOptions,a);if(!a.plotBands)a.plotBands=[]},getOffset:function(){G.getOffset.call(this);this.chart.axisOffset[this.side]=0;this.center=this.pane.center=T.getCenter.call(this.pane)},getLinePath:function(a,b){var c=this.center,b=o(b, c[2]/2-this.offset);return this.chart.renderer.symbols.arc(this.left+c[0],this.top+c[1],b,b,{start:this.startAngleRad,end:this.endAngleRad,open:!0,innerR:0})},setAxisTranslation:function(){G.setAxisTranslation.call(this);if(this.center)this.transA=this.isCircular?(this.endAngleRad-this.startAngleRad)/(this.max-this.min||1):this.center[2]/2/(this.max-this.min||1),this.minPixelPadding=this.isXAxis?this.transA*this.minPointOffset:0},beforeSetTickPositions:function(){this.autoConnect&&(this.max+=this.categories&& 1||this.pointRange||this.closestPointRange||0)},setAxisSize:function(){G.setAxisSize.call(this);if(this.isRadial){this.center=this.pane.center=l.CenteredSeriesMixin.getCenter.call(this.pane);if(this.isCircular)this.sector=this.endAngleRad-this.startAngleRad;this.len=this.width=this.height=this.center[2]*o(this.sector,1)/2}},getPosition:function(a,b){return this.postTranslate(this.isCircular?this.translate(a):0,o(this.isCircular?b:this.translate(a),this.center[2]/2)-this.offset)},postTranslate:function(a, b){var c=this.chart,d=this.center,a=this.startAngleRad+a;return{x:c.plotLeft+d[0]+Math.cos(a)*b,y:c.plotTop+d[1]+Math.sin(a)*b}},getPlotBandPath:function(a,b,c){var d=this.center,e=this.startAngleRad,f=d[2]/2,h=[o(c.outerRadius,"100%"),c.innerRadius,o(c.thickness,10)],j=/%$/,k,m=this.isCircular;this.options.gridLineInterpolation==="polygon"?d=this.getPlotLinePath(a).concat(this.getPlotLinePath(b,!0)):(m||(h[0]=this.translate(a),h[1]=this.translate(b)),h=R(h,function(a){j.test(a)&&(a=x(a,10)*f/100); return a}),c.shape==="circle"||!m?(a=-Math.PI/2,b=Math.PI*1.5,k=!0):(a=e+this.translate(a),b=e+this.translate(b)),d=this.chart.renderer.symbols.arc(this.left+d[0],this.top+d[1],h[0],h[0],{start:a,end:b,innerR:o(h[1],h[0]-h[2]),open:k}));return d},getPlotLinePath:function(a,b){var c=this,d=c.center,e=c.chart,f=c.getPosition(a),h,j,k;c.isCircular?k=["M",d[0]+e.plotLeft,d[1]+e.plotTop,"L",f.x,f.y]:c.options.gridLineInterpolation==="circle"?(a=c.translate(a))&&(k=c.getLinePath(0,a)):(s(e.xAxis,function(a){a.pane=== c.pane&&(h=a)}),k=[],a=c.translate(a),d=h.tickPositions,h.autoConnect&&(d=d.concat([d[0]])),b&&(d=[].concat(d).reverse()),s(d,function(f,c){j=h.getPosition(f,a);k.push(c?"L":"M",j.x,j.y)}));return k},getTitlePosition:function(){var a=this.center,b=this.chart,c=this.options.title;return{x:b.plotLeft+a[0]+(c.x||0),y:b.plotTop+a[1]-{high:0.5,middle:0.25,low:0}[c.align]*a[2]+(c.y||0)}}};r(G,"init",function(a,b,c){var i;var d=b.angular,e=b.polar,f=c.isX,h=d&&f,j,k;k=b.options;var m=c.pane||0;if(d){if(F(this, h?V:O),j=!f)this.defaultRadialOptions=this.defaultRadialGaugeOptions}else if(e)F(this,O),this.defaultRadialOptions=(j=f)?this.defaultRadialXOptions:q(this.defaultYAxisOptions,this.defaultRadialYOptions);a.call(this,b,c);if(!h&&(d||e)){a=this.options;if(!b.panes)b.panes=[];this.pane=(i=b.panes[m]=b.panes[m]||new K(L(k.pane)[m],b,this),m=i);m=m.options;b.inverted=!1;k.chart.zoomType=null;this.startAngleRad=b=(m.startAngle-90)*Math.PI/180;this.endAngleRad=k=(o(m.endAngle,m.startAngle+360)-90)*Math.PI/ 180;this.offset=a.offset||0;if((this.isCircular=j)&&c.max===C&&k-b===2*Math.PI)this.autoConnect=!0}});r(y,"getPosition",function(a,b,c,d,e){var f=this.axis;return f.getPosition?f.getPosition(c):a.call(this,b,c,d,e)});r(y,"getLabelPosition",function(a,b,c,d,e,f,h,j,k){var m=this.axis,i=f.y,n=f.align,g=(m.translate(this.pos)+m.startAngleRad+Math.PI/2)/Math.PI*180%360;m.isRadial?(a=m.getPosition(this.pos,m.center[2]/2+o(f.distance,-25)),f.rotation==="auto"?d.attr({rotation:g}):i===null&&(i=m.chart.renderer.fontMetrics(d.styles.fontSize).b- d.getBBox().height/2),n===null&&(n=m.isCircular?g>20&&g<160?"left":g>200&&g<340?"right":"center":"center",d.attr({align:n})),a.x+=f.x,a.y+=i):a=a.call(this,b,c,d,e,f,h,j,k);return a});r(y,"getMarkPath",function(a,b,c,d,e,f,h){var j=this.axis;j.isRadial?(a=j.getPosition(this.pos,j.center[2]/2+d),b=["M",b,c,"L",a.x,a.y]):b=a.call(this,b,c,d,e,f,h);return b});p.arearange=q(p.area,{lineWidth:1,marker:null,threshold:null,tooltip:{pointFormat:'<span style="color:{series.color}">??</span> {series.name}: <b>{point.low}</b> - <b>{point.high}</b><br/>'}, trackByArea:!0,dataLabels:{align:null,verticalAlign:null,xLow:0,xHigh:0,yLow:0,yHigh:0},states:{hover:{halo:!1}}});g.arearange=v(g.area,{type:"arearange",pointArrayMap:["low","high"],toYData:function(a){return[a.low,a.high]},pointValKey:"low",getSegments:function(){var a=this;s(a.points,function(b){if(!a.options.connectNulls&&(b.low===null||b.high===null))b.y=null;else if(b.low===null&&b.high!==null)b.y=b.high});t.prototype.getSegments.call(this)},translate:function(){var a=this.yAxis;g.area.prototype.translate.apply(this); s(this.points,function(b){var c=b.low,d=b.high,e=b.plotY;d===null&&c===null?b.y=null:c===null?(b.plotLow=b.plotY=null,b.plotHigh=a.translate(d,0,1,0,1)):d===null?(b.plotLow=e,b.plotHigh=null):(b.plotLow=e,b.plotHigh=a.translate(d,0,1,0,1))})},getSegmentPath:function(a){var b,c=[],d=a.length,e=t.prototype.getSegmentPath,f,h;h=this.options;var j=h.step;for(b=HighchartsAdapter.grep(a,function(a){return a.plotLow!==null});d--;)f=a[d],f.plotHigh!==null&&c.push({plotX:f.plotX,plotY:f.plotHigh});a=e.call(this, b);if(j)j===!0&&(j="left"),h.step={left:"right",center:"center",right:"left"}[j];c=e.call(this,c);h.step=j;h=[].concat(a,c);c[0]="L";this.areaPath=this.areaPath.concat(a,c);return h},drawDataLabels:function(){var a=this.data,b=a.length,c,d=[],e=t.prototype,f=this.options.dataLabels,h=f.align,j,k=this.chart.inverted;if(f.enabled||this._hasPointLabels){for(c=b;c--;)if(j=a[c],j.y=j.high,j._plotY=j.plotY,j.plotY=j.plotHigh,d[c]=j.dataLabel,j.dataLabel=j.dataLabelUpper,j.below=!1,k){if(!h)f.align="left"; f.x=f.xHigh}else f.y=f.yHigh;e.drawDataLabels&&e.drawDataLabels.apply(this,arguments);for(c=b;c--;)if(j=a[c],j.dataLabelUpper=j.dataLabel,j.dataLabel=d[c],j.y=j.low,j.plotY=j._plotY,j.below=!0,k){if(!h)f.align="right";f.x=f.xLow}else f.y=f.yLow;e.drawDataLabels&&e.drawDataLabels.apply(this,arguments)}f.align=h},alignDataLabel:function(){g.column.prototype.alignDataLabel.apply(this,arguments)},getSymbol:u,drawPoints:u});p.areasplinerange=q(p.arearange);g.areasplinerange=v(g.arearange,{type:"areasplinerange", getPointSpline:g.spline.prototype.getPointSpline});(function(){var a=g.column.prototype;p.columnrange=q(p.column,p.arearange,{lineWidth:1,pointRange:null});g.columnrange=v(g.arearange,{type:"columnrange",translate:function(){var b=this,c=b.yAxis,d;a.translate.apply(b);s(b.points,function(a){var f=a.shapeArgs,h=b.options.minPointLength,j;a.tooltipPos=null;a.plotHigh=d=c.translate(a.high,0,1,0,1);a.plotLow=a.plotY;j=d;a=a.plotY-d;a<h&&(h-=a,a+=h,j-=h/2);f.height=a;f.y=j})},trackerGroups:["group","dataLabelsGroup"], drawGraph:u,pointAttrToOptions:a.pointAttrToOptions,drawPoints:a.drawPoints,drawTracker:a.drawTracker,animate:a.animate,getColumnMetrics:a.getColumnMetrics})})();p.gauge=q(p.line,{dataLabels:{enabled:!0,defer:!1,y:15,borderWidth:1,borderColor:"silver",borderRadius:3,crop:!1,style:{fontWeight:"bold"},verticalAlign:"top",zIndex:2},dial:{},pivot:{},tooltip:{headerFormat:""},showInLegend:!1});z={type:"gauge",pointClass:v(H,{setState:function(a){this.state=a}}),angular:!0,drawGraph:u,fixedBox:!0,forceDL:!0, trackerGroups:["group","dataLabelsGroup"],translate:function(){var a=this.yAxis,b=this.options,c=a.center;this.generatePoints();s(this.points,function(d){var e=q(b.dial,d.dial),f=x(o(e.radius,80))*c[2]/200,h=x(o(e.baseLength,70))*f/100,j=x(o(e.rearLength,10))*f/100,k=e.baseWidth||3,m=e.topWidth||1,i=b.overshoot,n=a.startAngleRad+a.translate(d.y,null,null,null,!0);i&&typeof i==="number"?(i=i/180*Math.PI,n=Math.max(a.startAngleRad-i,Math.min(a.endAngleRad+i,n))):b.wrap===!1&&(n=Math.max(a.startAngleRad, Math.min(a.endAngleRad,n)));n=n*180/Math.PI;d.shapeType="path";d.shapeArgs={d:e.path||["M",-j,-k/2,"L",h,-k/2,f,-m/2,f,m/2,h,k/2,-j,k/2,"z"],translateX:c[0],translateY:c[1],rotation:n};d.plotX=c[0];d.plotY=c[1]})},drawPoints:function(){var a=this,b=a.yAxis.center,c=a.pivot,d=a.options,e=d.pivot,f=a.chart.renderer;s(a.points,function(c){var b=c.graphic,k=c.shapeArgs,e=k.d,i=q(d.dial,c.dial);b?(b.animate(k),k.d=e):c.graphic=f[c.shapeType](k).attr({stroke:i.borderColor||"none","stroke-width":i.borderWidth|| 0,fill:i.backgroundColor||"black",rotation:k.rotation}).add(a.group)});c?c.animate({translateX:b[0],translateY:b[1]}):a.pivot=f.circle(0,0,o(e.radius,5)).attr({"stroke-width":e.borderWidth||0,stroke:e.borderColor||"silver",fill:e.backgroundColor||"black"}).translate(b[0],b[1]).add(a.group)},animate:function(a){var b=this;if(!a)s(b.points,function(a){var d=a.graphic;d&&(d.attr({rotation:b.yAxis.startAngleRad*180/Math.PI}),d.animate({rotation:a.shapeArgs.rotation},b.options.animation))}),b.animate= null},render:function(){this.group=this.plotGroup("group","series",this.visible?"visible":"hidden",this.options.zIndex,this.chart.seriesGroup);t.prototype.render.call(this);this.group.clip(this.chart.clipRect)},setData:function(a,b){t.prototype.setData.call(this,a,!1);this.processData();this.generatePoints();o(b,!0)&&this.chart.redraw()},drawTracker:z&&z.drawTrackerPoint};g.gauge=v(g.line,z);p.boxplot=q(p.column,{fillColor:"#FFFFFF",lineWidth:1,medianWidth:2,states:{hover:{brightness:-0.3}},threshold:null, tooltip:{pointFormat:'<span style="color:{series.color}">??</span> <b> {series.name}</b><br/>Maximum: {point.high}<br/>Upper quartile: {point.q3}<br/>Median: {point.median}<br/>Lower quartile: {point.q1}<br/>Minimum: {point.low}<br/>'},whiskerLength:"50%",whiskerWidth:2});g.boxplot=v(g.column,{type:"boxplot",pointArrayMap:["low","q1","median","q3","high"],toYData:function(a){return[a.low,a.q1,a.median,a.q3,a.high]},pointValKey:"high",pointAttrToOptions:{fill:"fillColor",stroke:"color","stroke-width":"lineWidth"}, drawDataLabels:u,translate:function(){var a=this.yAxis,b=this.pointArrayMap;g.column.prototype.translate.apply(this);s(this.points,function(c){s(b,function(b){c[b]!==null&&(c[b+"Plot"]=a.translate(c[b],0,1,0,1))})})},drawPoints:function(){var a=this,b=a.points,c=a.options,d=a.chart.renderer,e,f,h,j,k,m,i,n,g,l,p,I,r,q,J,u,v,t,w,x,z,y,E=a.doQuartiles!==!1,B=parseInt(a.options.whiskerLength,10)/100;s(b,function(b){g=b.graphic;z=b.shapeArgs;p={};q={};u={};y=b.color||a.color;if(b.plotY!==C)if(e=b.pointAttr[b.selected? "selected":""],v=z.width,t=A(z.x),w=t+v,x=D(v/2),f=A(E?b.q1Plot:b.lowPlot),h=A(E?b.q3Plot:b.lowPlot),j=A(b.highPlot),k=A(b.lowPlot),p.stroke=b.stemColor||c.stemColor||y,p["stroke-width"]=o(b.stemWidth,c.stemWidth,c.lineWidth),p.dashstyle=b.stemDashStyle||c.stemDashStyle,q.stroke=b.whiskerColor||c.whiskerColor||y,q["stroke-width"]=o(b.whiskerWidth,c.whiskerWidth,c.lineWidth),u.stroke=b.medianColor||c.medianColor||y,u["stroke-width"]=o(b.medianWidth,c.medianWidth,c.lineWidth),u["stroke-linecap"]="round", i=p["stroke-width"]%2/2,n=t+x+i,l=["M",n,h,"L",n,j,"M",n,f,"L",n,k],E&&(i=e["stroke-width"]%2/2,n=A(n)+i,f=A(f)+i,h=A(h)+i,t+=i,w+=i,I=["M",t,h,"L",t,f,"L",w,f,"L",w,h,"L",t,h,"z"]),B&&(i=q["stroke-width"]%2/2,j+=i,k+=i,r=["M",n-x*B,j,"L",n+x*B,j,"M",n-x*B,k,"L",n+x*B,k]),i=u["stroke-width"]%2/2,m=D(b.medianPlot)+i,J=["M",t,m,"L",w,m],g)b.stem.animate({d:l}),B&&b.whiskers.animate({d:r}),E&&b.box.animate({d:I}),b.medianShape.animate({d:J});else{b.graphic=g=d.g().add(a.group);b.stem=d.path(l).attr(p).add(g); if(B)b.whiskers=d.path(r).attr(q).add(g);if(E)b.box=d.path(I).attr(e).add(g);b.medianShape=d.path(J).attr(u).add(g)}})}});p.errorbar=q(p.boxplot,{color:"#000000",grouping:!1,linkedTo:":previous",tooltip:{pointFormat:'<span style="color:{series.color}">??</span> {series.name}: <b>{point.low}</b> - <b>{point.high}</b><br/>'},whiskerWidth:null});g.errorbar=v(g.boxplot,{type:"errorbar",pointArrayMap:["low","high"],toYData:function(a){return[a.low,a.high]},pointValKey:"high",doQuartiles:!1,drawDataLabels:g.arearange? g.arearange.prototype.drawDataLabels:u,getColumnMetrics:function(){return this.linkedParent&&this.linkedParent.columnMetrics||g.column.prototype.getColumnMetrics.call(this)}});p.waterfall=q(p.column,{lineWidth:1,lineColor:"#333",dashStyle:"dot",borderColor:"#333",states:{hover:{lineWidthPlus:0}}});g.waterfall=v(g.column,{type:"waterfall",upColorProp:"fill",pointArrayMap:["low","y"],pointValKey:"y",init:function(a,b){b.stacking=!0;g.column.prototype.init.call(this,a,b)},translate:function(){var a= this.yAxis,b,c,d,e,f,h,j,k,m,i;b=this.options.threshold;g.column.prototype.translate.apply(this);k=m=b;d=this.points;for(c=0,b=d.length;c<b;c++){e=d[c];f=e.shapeArgs;h=this.getStack(c);i=h.points[this.index+","+c];if(isNaN(e.y))e.y=this.yData[c];j=N(k,k+e.y)+i[0];f.y=a.translate(j,0,1);e.isSum?(f.y=a.translate(i[1],0,1),f.height=a.translate(i[0],0,1)-f.y):e.isIntermediateSum?(f.y=a.translate(i[1],0,1),f.height=a.translate(m,0,1)-f.y,m=i[1]):k+=h.total;f.height<0&&(f.y+=f.height,f.height*=-1);e.plotY= f.y=D(f.y)-this.borderWidth%2/2;f.height=N(D(f.height),0.001);e.yBottom=f.y+f.height;f=e.plotY+(e.negative?f.height:0);this.chart.inverted?e.tooltipPos[0]=a.len-f:e.tooltipPos[1]=f}},processData:function(a){var b=this.yData,c=this.points,d,e=b.length,f,h,j,k,m,i;h=f=j=k=this.options.threshold||0;for(i=0;i<e;i++)m=b[i],d=c&&c[i]?c[i]:{},m==="sum"||d.isSum?b[i]=h:m==="intermediateSum"||d.isIntermediateSum?b[i]=f:(h+=m,f+=m),j=Math.min(h,j),k=Math.max(h,k);t.prototype.processData.call(this,a);this.dataMin= j;this.dataMax=k},toYData:function(a){if(a.isSum)return"sum";else if(a.isIntermediateSum)return"intermediateSum";return a.y},getAttribs:function(){g.column.prototype.getAttribs.apply(this,arguments);var a=this.options,b=a.states,c=a.upColor||this.color,a=l.Color(c).brighten(0.1).get(),d=q(this.pointAttr),e=this.upColorProp;d[""][e]=c;d.hover[e]=b.hover.upColor||a;d.select[e]=b.select.upColor||c;s(this.points,function(a){if(a.y>0&&!a.color)a.pointAttr=d,a.color=c})},getGraphPath:function(){var a=this.data, b=a.length,c=D(this.options.lineWidth+this.borderWidth)%2/2,d=[],e,f,h;for(h=1;h<b;h++)f=a[h].shapeArgs,e=a[h-1].shapeArgs,f=["M",e.x+e.width,e.y+c,"L",f.x,e.y+c],a[h-1].y<0&&(f[2]+=e.height,f[5]+=e.height),d=d.concat(f);return d},getExtremes:u,getStack:function(a){var b=this.yAxis.stacks,c=this.stackKey;this.processedYData[a]<this.options.threshold&&(c="-"+c);return b[c][a]},drawGraph:t.prototype.drawGraph});p.bubble=q(p.scatter,{dataLabels:{formatter:function(){return this.point.z},inside:!0,style:{color:"white", textShadow:"0px 0px 3px black"},verticalAlign:"middle"},marker:{lineColor:null,lineWidth:1},minSize:8,maxSize:"20%",states:{hover:{halo:{size:5}}},tooltip:{pointFormat:"({point.x}, {point.y}), Size: {point.z}"},turboThreshold:0,zThreshold:0});z=v(H,{haloPath:function(){return H.prototype.haloPath.call(this,this.shapeArgs.r+this.series.options.states.hover.halo.size)}});g.bubble=v(g.scatter,{type:"bubble",pointClass:z,pointArrayMap:["y","z"],parallelArrays:["x","y","z"],trackerGroups:["group","dataLabelsGroup"], bubblePadding:!0,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor"},applyOpacity:function(a){var b=this.options.marker,c=o(b.fillOpacity,0.5),a=a||b.fillColor||this.color;c!==1&&(a=U(a).setOpacity(c).get("rgba"));return a},convertAttribs:function(){var a=t.prototype.convertAttribs.apply(this,arguments);a.fill=this.applyOpacity(a.fill);return a},getRadii:function(a,b,c,d){var e,f,h,j=this.zData,k=[],m=this.options.sizeBy!=="width";for(f=0,e=j.length;f<e;f++)h=b-a,h= h>0?(j[f]-a)/(b-a):0.5,m&&h>=0&&(h=Math.sqrt(h)),k.push(w.ceil(c+h*(d-c))/2);this.radii=k},animate:function(a){var b=this.options.animation;if(!a)s(this.points,function(a){var d=a.graphic,a=a.shapeArgs;d&&a&&(d.attr("r",1),d.animate({r:a.r},b))}),this.animate=null},translate:function(){var a,b=this.data,c,d,e=this.radii;g.scatter.prototype.translate.call(this);for(a=b.length;a--;)c=b[a],d=e?e[a]:0,c.negative=c.z<(this.options.zThreshold||0),d>=this.minPxSize/2?(c.shapeType="circle",c.shapeArgs={x:c.plotX, y:c.plotY,r:d},c.dlBox={x:c.plotX-d,y:c.plotY-d,width:2*d,height:2*d}):c.shapeArgs=c.plotY=c.dlBox=C},drawLegendSymbol:function(a,b){var c=x(a.itemStyle.fontSize)/2;b.legendSymbol=this.chart.renderer.circle(c,a.baseline-c,c).attr({zIndex:3}).add(b.legendGroup);b.legendSymbol.isMarker=!0},drawPoints:g.column.prototype.drawPoints,alignDataLabel:g.column.prototype.alignDataLabel});M.prototype.beforePadding=function(){var a=this,b=this.len,c=this.chart,d=0,e=b,f=this.isXAxis,h=f?"xData":"yData",j=this.min, k={},m=w.min(c.plotWidth,c.plotHeight),i=Number.MAX_VALUE,n=-Number.MAX_VALUE,g=this.max-j,l=b/g,p=[];this.tickPositions&&(s(this.series,function(b){var h=b.options;if(b.bubblePadding&&(b.visible||!c.options.chart.ignoreHiddenSeries))if(a.allowZoomOutside=!0,p.push(b),f)s(["minSize","maxSize"],function(a){var b=h[a],f=/%$/.test(b),b=x(b);k[a]=f?m*b/100:b}),b.minPxSize=k.minSize,b=b.zData,b.length&&(i=o(h.zMin,w.min(i,w.max(P(b),h.displayNegative===!1?h.zThreshold:-Number.MAX_VALUE))),n=o(h.zMax,w.max(n, Q(b))))}),s(p,function(a){var b=a[h],c=b.length,m;f&&a.getRadii(i,n,k.minSize,k.maxSize);if(g>0)for(;c--;)typeof b[c]==="number"&&(m=a.radii[c],d=Math.min((b[c]-j)*l-m,d),e=Math.max((b[c]-j)*l+m,e))}),p.length&&g>0&&o(this.options.min,this.userMin)===C&&o(this.options.max,this.userMax)===C&&(e-=b,l*=(b+d-e)/b,this.min+=d/l,this.max+=e/l))};(function(){function a(a,b,c){a.call(this,b,c);if(this.chart.polar)this.closeSegment=function(a){var b=this.xAxis.center;a.push("L",b[0],b[1])},this.closedStacks= !0}function b(a,b){var c=this.chart,d=this.options.animation,e=this.group,i=this.markerGroup,n=this.xAxis.center,g=c.plotLeft,l=c.plotTop;if(c.polar){if(c.renderer.isSVG)d===!0&&(d={}),b?(c={translateX:n[0]+g,translateY:n[1]+l,scaleX:0.001,scaleY:0.001},e.attr(c),i&&i.attr(c)):(c={translateX:g,translateY:l,scaleX:1,scaleY:1},e.animate(c,d),i&&i.animate(c,d),this.animate=null)}else a.call(this,b)}var c=t.prototype,d=S.prototype,e;c.toXY=function(a){var b,c=this.chart,d=a.plotX;b=a.plotY;a.rectPlotX= d;a.rectPlotY=b;d=(d/Math.PI*180+this.xAxis.pane.options.startAngle)%360;d<0&&(d+=360);a.clientX=d;b=this.xAxis.postTranslate(a.plotX,this.yAxis.len-b);a.plotX=a.polarPlotX=b.x-c.plotLeft;a.plotY=a.polarPlotY=b.y-c.plotTop};c.orderTooltipPoints=function(a){if(this.chart.polar&&(a.sort(function(a,b){return a.clientX-b.clientX}),a[0]))a[0].wrappedClientX=a[0].clientX+360,a.push(a[0])};g.area&&r(g.area.prototype,"init",a);g.areaspline&&r(g.areaspline.prototype,"init",a);g.spline&&r(g.spline.prototype, "getPointSpline",function(a,b,c,d){var e,i,n,g,l,p,o;if(this.chart.polar){e=c.plotX;i=c.plotY;a=b[d-1];n=b[d+1];this.connectEnds&&(a||(a=b[b.length-2]),n||(n=b[1]));if(a&&n)g=a.plotX,l=a.plotY,b=n.plotX,p=n.plotY,g=(1.5*e+g)/2.5,l=(1.5*i+l)/2.5,n=(1.5*e+b)/2.5,o=(1.5*i+p)/2.5,b=Math.sqrt(Math.pow(g-e,2)+Math.pow(l-i,2)),p=Math.sqrt(Math.pow(n-e,2)+Math.pow(o-i,2)),g=Math.atan2(l-i,g-e),l=Math.atan2(o-i,n-e),o=Math.PI/2+(g+l)/2,Math.abs(g-o)>Math.PI/2&&(o-=Math.PI),g=e+Math.cos(o)*b,l=i+Math.sin(o)* b,n=e+Math.cos(Math.PI+o)*p,o=i+Math.sin(Math.PI+o)*p,c.rightContX=n,c.rightContY=o;d?(c=["C",a.rightContX||a.plotX,a.rightContY||a.plotY,g||e,l||i,e,i],a.rightContX=a.rightContY=null):c=["M",e,i]}else c=a.call(this,b,c,d);return c});r(c,"translate",function(a){a.call(this);if(this.chart.polar&&!this.preventPostTranslate)for(var a=this.points,b=a.length;b--;)this.toXY(a[b])});r(c,"getSegmentPath",function(a,b){var c=this.points;if(this.chart.polar&&this.options.connectEnds!==!1&&b[b.length-1]===c[c.length- 1]&&c[0].y!==null)this.connectEnds=!0,b=[].concat(b,[c[0]]);return a.call(this,b)});r(c,"animate",b);r(c,"setTooltipPoints",function(a,b){this.chart.polar&&F(this.xAxis,{tooltipLen:360});return a.call(this,b)});if(g.column)e=g.column.prototype,r(e,"animate",b),r(e,"translate",function(a){var b=this.xAxis,c=this.yAxis.len,d=b.center,e=b.startAngleRad,i=this.chart.renderer,g,l;this.preventPostTranslate=!0;a.call(this);if(b.isRadial){b=this.points;for(l=b.length;l--;)g=b[l],a=g.barX+e,g.shapeType="path", g.shapeArgs={d:i.symbols.arc(d[0],d[1],c-g.plotY,null,{start:a,end:a+g.pointWidth,innerR:c-o(g.yBottom,c)})},this.toXY(g),g.tooltipPos=[g.plotX,g.plotY],g.ttBelow=g.plotY>d[1]}}),r(e,"alignDataLabel",function(a,b,d,e,g,i){if(this.chart.polar){a=b.rectPlotX/Math.PI*180;if(e.align===null)e.align=a>20&&a<160?"left":a>200&&a<340?"right":"center";if(e.verticalAlign===null)e.verticalAlign=a<45||a>315?"bottom":a>135&&a<225?"top":"middle";c.alignDataLabel.call(this,b,d,e,g,i)}else a.call(this,b,d,e,g,i)}); r(d,"getIndex",function(a,b){var c,d=this.chart,e;d.polar?(e=d.xAxis[0].center,c=b.chartX-e[0]-d.plotLeft,d=b.chartY-e[1]-d.plotTop,c=180-Math.round(Math.atan2(c,d)/Math.PI*180)):c=a.call(this,b);return c});r(d,"getCoordinates",function(a,b){var c=this.chart,d={xAxis:[],yAxis:[]};c.polar?s(c.axes,function(a){var e=a.isXAxis,f=a.center,g=b.chartX-f[0]-c.plotLeft,f=b.chartY-f[1]-c.plotTop;d[e?"xAxis":"yAxis"].push({axis:a,value:a.translate(e?Math.PI-Math.atan2(g,f):Math.sqrt(Math.pow(g,2)+Math.pow(f, 2)),!0)})}):d=a.call(this,b);return d})})()})(Highcharts); /* Highcharts JS v4.0.3 (2014-07-03) Exporting module (c) 2010-2014 Torstein Honsi License: www.highcharts.com/license */ (function(f){var A=f.Chart,t=f.addEvent,B=f.removeEvent,l=f.createElement,o=f.discardElement,v=f.css,k=f.merge,r=f.each,p=f.extend,D=Math.max,j=document,C=window,E=f.isTouchDevice,F=f.Renderer.prototype.symbols,s=f.getOptions(),y;p(s.lang,{printChart:"Print chart",downloadPNG:"Download PNG image",downloadJPEG:"Download JPEG image",downloadPDF:"Download PDF document",downloadSVG:"Download SVG vector image",contextButtonTitle:"Chart context menu"});s.navigation={menuStyle:{border:"1px solid #A0A0A0", background:"#FFFFFF",padding:"5px 0"},menuItemStyle:{padding:"0 10px",background:"none",color:"#303030",fontSize:E?"14px":"11px"},menuItemHoverStyle:{background:"#4572A5",color:"#FFFFFF"},buttonOptions:{symbolFill:"#E0E0E0",symbolSize:14,symbolStroke:"#666",symbolStrokeWidth:3,symbolX:12.5,symbolY:10.5,align:"right",buttonSpacing:3,height:22,theme:{fill:"white",stroke:"none"},verticalAlign:"top",width:24}};s.exporting={type:"image/png",url:"http://export.highcharts.com/",buttons:{contextButton:{menuClassName:"highcharts-contextmenu", symbol:"menu",_titleKey:"contextButtonTitle",menuItems:[{textKey:"printChart",onclick:function(){this.print()}},{separator:!0},{textKey:"downloadPNG",onclick:function(){this.exportChart()}},{textKey:"downloadJPEG",onclick:function(){this.exportChart({type:"image/jpeg"})}},{textKey:"downloadPDF",onclick:function(){this.exportChart({type:"application/pdf"})}},{textKey:"downloadSVG",onclick:function(){this.exportChart({type:"image/svg+xml"})}}]}}};f.post=function(b,a,d){var c,b=l("form",k({method:"post", action:b,enctype:"multipart/form-data"},d),{display:"none"},j.body);for(c in a)l("input",{type:"hidden",name:c,value:a[c]},null,b);b.submit();o(b)};p(A.prototype,{getSVG:function(b){var a=this,d,c,z,h,g=k(a.options,b);if(!j.createElementNS)j.createElementNS=function(a,b){return j.createElement(b)};b=l("div",null,{position:"absolute",top:"-9999em",width:a.chartWidth+"px",height:a.chartHeight+"px"},j.body);c=a.renderTo.style.width;h=a.renderTo.style.height;c=g.exporting.sourceWidth||g.chart.width|| /px$/.test(c)&&parseInt(c,10)||600;h=g.exporting.sourceHeight||g.chart.height||/px$/.test(h)&&parseInt(h,10)||400;p(g.chart,{animation:!1,renderTo:b,forExport:!0,width:c,height:h});g.exporting.enabled=!1;g.series=[];r(a.series,function(a){z=k(a.options,{animation:!1,enableMouseTracking:!1,showCheckbox:!1,visible:a.visible});z.isInternal||g.series.push(z)});d=new f.Chart(g,a.callback);r(["xAxis","yAxis"],function(b){r(a[b],function(a,c){var g=d[b][c],f=a.getExtremes(),h=f.userMin,f=f.userMax;g&&(h!== void 0||f!==void 0)&&g.setExtremes(h,f,!0,!1)})});c=d.container.innerHTML;g=null;d.destroy();o(b);c=c.replace(/zIndex="[^"]+"/g,"").replace(/isShadow="[^"]+"/g,"").replace(/symbolName="[^"]+"/g,"").replace(/jQuery[0-9]+="[^"]+"/g,"").replace(/url\([^#]+#/g,"url(#").replace(/<svg /,'<svg xmlns:xlink="http://www.w3.org/1999/xlink" ').replace(/ href=/g," xlink:href=").replace(/\n/," ").replace(/<\/svg>.*?$/,"</svg>").replace(/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g,'$1="rgb($2)" $1-opacity="$3"').replace(/ /g, "?").replace(/­/g,"?").replace(/<IMG /g,"<image ").replace(/height=([^" ]+)/g,'height="$1"').replace(/width=([^" ]+)/g,'width="$1"').replace(/hc-svg-href="([^"]+)">/g,'xlink:href="$1"/>').replace(/id=([^" >]+)/g,'id="$1"').replace(/class=([^" >]+)/g,'class="$1"').replace(/ transform /g," ").replace(/:(path|rect)/g,"$1").replace(/style="([^"]+)"/g,function(a){return a.toLowerCase()});return c=c.replace(/(url\(#highcharts-[0-9]+)"/g,"$1").replace(/"/g,"'")},exportChart:function(b,a){var b= b||{},d=this.options.exporting,d=this.getSVG(k({chart:{borderRadius:0}},d.chartOptions,a,{exporting:{sourceWidth:b.sourceWidth||d.sourceWidth,sourceHeight:b.sourceHeight||d.sourceHeight}})),b=k(this.options.exporting,b);f.post(b.url,{filename:b.filename||"chart",type:b.type,width:b.width||0,scale:b.scale||2,svg:d},b.formAttributes)},print:function(){var b=this,a=b.container,d=[],c=a.parentNode,f=j.body,h=f.childNodes;if(!b.isPrinting)b.isPrinting=!0,r(h,function(a,b){if(a.nodeType===1)d[b]=a.style.display, a.style.display="none"}),f.appendChild(a),C.focus(),C.print(),setTimeout(function(){c.appendChild(a);r(h,function(a,b){if(a.nodeType===1)a.style.display=d[b]});b.isPrinting=!1},1E3)},contextMenu:function(b,a,d,c,f,h,g){var e=this,k=e.options.navigation,q=k.menuItemStyle,m=e.chartWidth,n=e.chartHeight,j="cache-"+b,i=e[j],u=D(f,h),w,x,o,s=function(a){e.pointer.inClass(a.target,b)||x()};if(!i)e[j]=i=l("div",{className:b},{position:"absolute",zIndex:1E3,padding:u+"px"},e.container),w=l("div",null,p({MozBoxShadow:"3px 3px 10px #888", WebkitBoxShadow:"3px 3px 10px #888",boxShadow:"3px 3px 10px #888"},k.menuStyle),i),x=function(){v(i,{display:"none"});g&&g.setState(0);e.openMenu=!1},t(i,"mouseleave",function(){o=setTimeout(x,500)}),t(i,"mouseenter",function(){clearTimeout(o)}),t(document,"mouseup",s),t(e,"destroy",function(){B(document,"mouseup",s)}),r(a,function(a){if(a){var b=a.separator?l("hr",null,null,w):l("div",{onmouseover:function(){v(this,k.menuItemHoverStyle)},onmouseout:function(){v(this,q)},onclick:function(){x();a.onclick.apply(e, arguments)},innerHTML:a.text||e.options.lang[a.textKey]},p({cursor:"pointer"},q),w);e.exportDivElements.push(b)}}),e.exportDivElements.push(w,i),e.exportMenuWidth=i.offsetWidth,e.exportMenuHeight=i.offsetHeight;a={display:"block"};d+e.exportMenuWidth>m?a.right=m-d-f-u+"px":a.left=d-u+"px";c+h+e.exportMenuHeight>n&&g.alignOptions.verticalAlign!=="top"?a.bottom=n-c-u+"px":a.top=c+h-u+"px";v(i,a);e.openMenu=!0},addButton:function(b){var a=this,d=a.renderer,c=k(a.options.navigation.buttonOptions,b),j= c.onclick,h=c.menuItems,g,e,l={stroke:c.symbolStroke,fill:c.symbolFill},q=c.symbolSize||12;if(!a.btnCount)a.btnCount=0;if(!a.exportDivElements)a.exportDivElements=[],a.exportSVGElements=[];if(c.enabled!==!1){var m=c.theme,n=m.states,o=n&&n.hover,n=n&&n.select,i;delete m.states;j?i=function(){j.apply(a,arguments)}:h&&(i=function(){a.contextMenu(e.menuClassName,h,e.translateX,e.translateY,e.width,e.height,e);e.setState(2)});c.text&&c.symbol?m.paddingLeft=f.pick(m.paddingLeft,25):c.text||p(m,{width:c.width, height:c.height,padding:0});e=d.button(c.text,0,0,i,m,o,n).attr({title:a.options.lang[c._titleKey],"stroke-linecap":"round"});e.menuClassName=b.menuClassName||"highcharts-menu-"+a.btnCount++;c.symbol&&(g=d.symbol(c.symbol,c.symbolX-q/2,c.symbolY-q/2,q,q).attr(p(l,{"stroke-width":c.symbolStrokeWidth||1,zIndex:1})).add(e));e.add().align(p(c,{width:e.width,x:f.pick(c.x,y)}),!0,"spacingBox");y+=(e.width+c.buttonSpacing)*(c.align==="right"?-1:1);a.exportSVGElements.push(e,g)}},destroyExport:function(b){var b= b.target,a,d;for(a=0;a<b.exportSVGElements.length;a++)if(d=b.exportSVGElements[a])d.onclick=d.ontouchstart=null,b.exportSVGElements[a]=d.destroy();for(a=0;a<b.exportDivElements.length;a++)d=b.exportDivElements[a],B(d,"mouseleave"),b.exportDivElements[a]=d.onmouseout=d.onmouseover=d.ontouchstart=d.onclick=null,o(d)}});F.menu=function(b,a,d,c){return["M",b,a+2.5,"L",b+d,a+2.5,"M",b,a+c/2+0.5,"L",b+d,a+c/2+0.5,"M",b,a+c-1.5,"L",b+d,a+c-1.5]};A.prototype.callbacks.push(function(b){var a,d=b.options.exporting, c=d.buttons;y=0;if(d.enabled!==!1){for(a in c)b.addButton(c[a]);t(b,"destroy",b.destroyExport)}})})(Highcharts); /* * jPlayer Plugin for jQuery JavaScript Library * http://www.jplayer.org * * Copyright (c) 2009 - 2014 Happyworm Ltd * Licensed under the MIT license. * http://opensource.org/licenses/MIT * * Author: Mark J Panaghiston * Version: 2.6.3 * Date: 30th May 2014 */ /* Code verified using http://www.jshint.com/ */ /*jshint asi:false, bitwise:false, boss:false, browser:true, curly:true, debug:false, eqeqeq:true, eqnull:false, evil:false, forin:false, immed:false, jquery:true, laxbreak:false, newcap:true, noarg:true, noempty:true, nonew:true, onevar:false, passfail:false, plusplus:false, regexp:false, undef:true, sub:false, strict:false, white:false, smarttabs:true */ /*global define:false, ActiveXObject:false, alert:false */ /* Support for Zepto 1.0 compiled with optional data module. * For AMD support, you will need to manually switch the 2 lines in the code below. * Search terms: "jQuery Switch" and "Zepto Switch" */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); // jQuery Switch // define(['zepto'], factory); // Zepto Switch } else { // Browser globals if(root.jQuery) { // Use jQuery if available factory(root.jQuery); } else { // Otherwise, use Zepto factory(root.Zepto); } } }(this, function ($, undefined) { // Adapted from jquery.ui.widget.js (1.8.7): $.widget.bridge - Tweaked $.data(this,XYZ) to $(this).data(XYZ) for Zepto $.fn.jPlayer = function( options ) { var name = "jPlayer"; var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $(this).data( name ), methodValue = instance && $.isFunction( instance[options] ) ? instance[ options ].apply( instance, args ) : instance; if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $(this).data( name ); if ( instance ) { // instance.option( options || {} )._init(); // Orig jquery.ui.widget.js code: Not recommend for jPlayer. ie., Applying new options to an existing instance (via the jPlayer constructor) and performing the _init(). The _init() is what concerns me. It would leave a lot of event handlers acting on jPlayer instance and the interface. instance.option( options || {} ); // The new constructor only changes the options. Changing options only has basic support atm. } else { $(this).data( name, new $.jPlayer( options, this ) ); } }); } return returnValue; }; $.jPlayer = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this.element = $(element); this.options = $.extend(true, {}, this.options, options ); var self = this; this.element.bind( "remove.jPlayer", function() { self.destroy(); }); this._init(); } }; // End of: (Adapted from jquery.ui.widget.js (1.8.7)) // Zepto is missing one of the animation methods. if(typeof $.fn.stop !== 'function') { $.fn.stop = function() {}; } // Emulated HTML5 methods and properties $.jPlayer.emulateMethods = "load play pause"; $.jPlayer.emulateStatus = "src readyState networkState currentTime duration paused ended playbackRate"; $.jPlayer.emulateOptions = "muted volume"; // Reserved event names generated by jPlayer that are not part of the HTML5 Media element spec $.jPlayer.reservedEvent = "ready flashreset resize repeat error warning"; // Events generated by jPlayer $.jPlayer.event = {}; $.each( [ 'ready', 'setmedia', // Fires when the media is set 'flashreset', // Similar to the ready event if the Flash solution is set to display:none and then shown again or if it's reloaded for another reason by the browser. For example, using CSS position:fixed on Firefox for the full screen feature. 'resize', // Occurs when the size changes through a full/restore screen operation or if the size/sizeFull options are changed. 'repeat', // Occurs when the repeat status changes. Usually through clicks on the repeat button of the interface. 'click', // Occurs when the user clicks on one of the following: poster image, html video, flash video. 'error', // Event error code in event.jPlayer.error.type. See $.jPlayer.error 'warning', // Event warning code in event.jPlayer.warning.type. See $.jPlayer.warning // Other events match HTML5 spec. 'loadstart', 'progress', 'suspend', 'abort', 'emptied', 'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata', 'waiting', 'playing', 'canplay', 'canplaythrough', 'seeking', 'seeked', 'timeupdate', 'ended', 'ratechange', 'durationchange', 'volumechange' ], function() { $.jPlayer.event[ this ] = 'jPlayer_' + this; } ); $.jPlayer.htmlEvent = [ // These HTML events are bubbled through to the jPlayer event, without any internal action. "loadstart", // "progress", // jPlayer uses internally before bubbling. // "suspend", // jPlayer uses internally before bubbling. "abort", // "error", // jPlayer uses internally before bubbling. "emptied", "stalled", // "play", // jPlayer uses internally before bubbling. // "pause", // jPlayer uses internally before bubbling. "loadedmetadata", "loadeddata", // "waiting", // jPlayer uses internally before bubbling. // "playing", // jPlayer uses internally before bubbling. "canplay", "canplaythrough" // "seeking", // jPlayer uses internally before bubbling. // "seeked", // jPlayer uses internally before bubbling. // "timeupdate", // jPlayer uses internally before bubbling. // "ended", // jPlayer uses internally before bubbling. // "ratechange" // jPlayer uses internally before bubbling. // "durationchange" // jPlayer uses internally before bubbling. // "volumechange" // jPlayer uses internally before bubbling. ]; $.jPlayer.pause = function() { $.each($.jPlayer.prototype.instances, function(i, element) { if(element.data("jPlayer").status.srcSet) { // Check that media is set otherwise would cause error event. element.jPlayer("pause"); } }); }; // Default for jPlayer option.timeFormat $.jPlayer.timeFormat = { showHour: false, showMin: true, showSec: true, padHour: false, padMin: true, padSec: true, sepHour: ":", sepMin: ":", sepSec: "" }; var ConvertTime = function() { this.init(); }; ConvertTime.prototype = { init: function() { this.options = { timeFormat: $.jPlayer.timeFormat }; }, time: function(s) { // function used on jPlayer.prototype._convertTime to enable per instance options. s = (s && typeof s === 'number') ? s : 0; var myTime = new Date(s * 1000), hour = myTime.getUTCHours(), min = this.options.timeFormat.showHour ? myTime.getUTCMinutes() : myTime.getUTCMinutes() + hour * 60, sec = this.options.timeFormat.showMin ? myTime.getUTCSeconds() : myTime.getUTCSeconds() + min * 60, strHour = (this.options.timeFormat.padHour && hour < 10) ? "0" + hour : hour, strMin = (this.options.timeFormat.padMin && min < 10) ? "0" + min : min, strSec = (this.options.timeFormat.padSec && sec < 10) ? "0" + sec : sec, strTime = ""; strTime += this.options.timeFormat.showHour ? strHour + this.options.timeFormat.sepHour : ""; strTime += this.options.timeFormat.showMin ? strMin + this.options.timeFormat.sepMin : ""; strTime += this.options.timeFormat.showSec ? strSec + this.options.timeFormat.sepSec : ""; return strTime; } }; var myConvertTime = new ConvertTime(); $.jPlayer.convertTime = function(s) { return myConvertTime.time(s); }; // Adapting jQuery 1.4.4 code for jQuery.browser. Required since jQuery 1.3.2 does not detect Chrome as webkit. $.jPlayer.uaBrowser = function( userAgent ) { var ua = userAgent.toLowerCase(); // Useragent RegExp var rwebkit = /(webkit)[ \/]([\w.]+)/; var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/; var rmsie = /(msie) ([\w.]+)/; var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/; var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }; // Platform sniffer for detecting mobile devices $.jPlayer.uaPlatform = function( userAgent ) { var ua = userAgent.toLowerCase(); // Useragent RegExp var rplatform = /(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/; var rtablet = /(ipad|playbook)/; var randroid = /(android)/; var rmobile = /(mobile)/; var platform = rplatform.exec( ua ) || []; var tablet = rtablet.exec( ua ) || !rmobile.exec( ua ) && randroid.exec( ua ) || []; if(platform[1]) { platform[1] = platform[1].replace(/\s/g, "_"); // Change whitespace to underscore. Enables dot notation. } return { platform: platform[1] || "", tablet: tablet[1] || "" }; }; $.jPlayer.browser = { }; $.jPlayer.platform = { }; var browserMatch = $.jPlayer.uaBrowser(navigator.userAgent); if ( browserMatch.browser ) { $.jPlayer.browser[ browserMatch.browser ] = true; $.jPlayer.browser.version = browserMatch.version; } var platformMatch = $.jPlayer.uaPlatform(navigator.userAgent); if ( platformMatch.platform ) { $.jPlayer.platform[ platformMatch.platform ] = true; $.jPlayer.platform.mobile = !platformMatch.tablet; $.jPlayer.platform.tablet = !!platformMatch.tablet; } // Internet Explorer (IE) Browser Document Mode Sniffer. Based on code at: // http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#GetMode $.jPlayer.getDocMode = function() { var docMode; if ($.jPlayer.browser.msie) { if (document.documentMode) { // IE8 or later docMode = document.documentMode; } else { // IE 5-7 docMode = 5; // Assume quirks mode unless proven otherwise if (document.compatMode) { if (document.compatMode === "CSS1Compat") { docMode = 7; // standards mode } } } } return docMode; }; $.jPlayer.browser.documentMode = $.jPlayer.getDocMode(); $.jPlayer.nativeFeatures = { init: function() { /* Fullscreen function naming influenced by W3C naming. * No support for: Mozilla Proposal: https://wiki.mozilla.org/Gecko:FullScreenAPI */ var d = document, v = d.createElement('video'), spec = { // http://www.w3.org/TR/fullscreen/ w3c: [ 'fullscreenEnabled', 'fullscreenElement', 'requestFullscreen', 'exitFullscreen', 'fullscreenchange', 'fullscreenerror' ], // https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode moz: [ 'mozFullScreenEnabled', 'mozFullScreenElement', 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozfullscreenchange', 'mozfullscreenerror' ], // http://developer.apple.com/library/safari/#documentation/WebKit/Reference/ElementClassRef/Element/Element.html // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html webkit: [ '', 'webkitCurrentFullScreenElement', 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitfullscreenchange', '' ], // http://developer.apple.com/library/safari/#documentation/AudioVideo/Reference/HTMLVideoElementClassReference/HTMLVideoElement/HTMLVideoElement.html // https://developer.apple.com/library/safari/samplecode/HTML5VideoEventFlow/Listings/events_js.html#//apple_ref/doc/uid/DTS40010085-events_js-DontLinkElementID_5 // Events: 'webkitbeginfullscreen' and 'webkitendfullscreen' webkitVideo: [ 'webkitSupportsFullscreen', 'webkitDisplayingFullscreen', 'webkitEnterFullscreen', 'webkitExitFullscreen', '', '' ] }, specOrder = [ 'w3c', 'moz', 'webkit', 'webkitVideo' ], fs, i, il; this.fullscreen = fs = { support: { w3c: !!d[spec.w3c[0]], moz: !!d[spec.moz[0]], webkit: typeof d[spec.webkit[3]] === 'function', webkitVideo: typeof v[spec.webkitVideo[2]] === 'function' }, used: {} }; // Store the name of the spec being used and as a handy boolean. for(i = 0, il = specOrder.length; i < il; i++) { var n = specOrder[i]; if(fs.support[n]) { fs.spec = n; fs.used[n] = true; break; } } if(fs.spec) { var s = spec[fs.spec]; fs.api = { fullscreenEnabled: true, fullscreenElement: function(elem) { elem = elem ? elem : d; // Video element required for webkitVideo return elem[s[1]]; }, requestFullscreen: function(elem) { return elem[s[2]](); }, exitFullscreen: function(elem) { elem = elem ? elem : d; // Video element required for webkitVideo return elem[s[3]](); } }; fs.event = { fullscreenchange: s[4], fullscreenerror: s[5] }; } else { fs.api = { fullscreenEnabled: false, fullscreenElement: function() { return null; }, requestFullscreen: function() {}, exitFullscreen: function() {} }; fs.event = {}; } } }; $.jPlayer.nativeFeatures.init(); // The keyboard control system. // The current jPlayer instance in focus. $.jPlayer.focus = null; // (fallback) The list of element node names to ignore with key controls. $.jPlayer.keyIgnoreElementNames = "A INPUT TEXTAREA SELECT BUTTON"; // The function that deals with key presses. var keyBindings = function(event) { var f = $.jPlayer.focus, pageFocus = document.activeElement, ignoreKey; // A jPlayer instance must be in focus. ie., keyEnabled and the last one played. if(f) { // What generated the key press? if(typeof pageFocus !== 'undefined') { if(pageFocus !== null && pageFocus.nodeName.toUpperCase() !== "BODY") { ignoreKey = true; } } else { // Fallback for no document.activeElement support. $.each( $.jPlayer.keyIgnoreElementNames.split(/\s+/g), function(i, name) { // The strings should already be uppercase. if(event.target.nodeName.toUpperCase() === name.toUpperCase()) { ignoreKey = true; return false; // exit each. } }); } if(!ignoreKey) { // See if the key pressed matches any of the bindings. $.each(f.options.keyBindings, function(action, binding) { // The binding could be a null when the default has been disabled. ie., 1st clause in if() if(binding && event.which === binding.key && $.isFunction(binding.fn)) { event.preventDefault(); // Key being used by jPlayer, so prevent default operation. binding.fn(f); return false; // exit each. } }); } } }; $.jPlayer.keys = function(en) { var event = "keydown.jPlayer"; // Remove any binding, just in case enabled more than once. $(document.documentElement).unbind(event); if(en) { $(document.documentElement).bind(event, keyBindings); } }; // Enable the global key control handler ready for any jPlayer instance with the keyEnabled option enabled. $.jPlayer.keys(true); $.jPlayer.prototype = { count: 0, // Static Variable: Change it via prototype. version: { // Static Object script: "2.6.3", needFlash: "2.6.0", flash: "unknown" }, options: { // Instanced in $.jPlayer() constructor swfPath: "js", // Path to Jplayer.swf. Can be relative, absolute or server root relative. solution: "html, flash", // Valid solutions: html, flash. Order defines priority. 1st is highest, supplied: "mp3", // Defines which formats jPlayer will try and support and the priority by the order. 1st is highest, preload: 'metadata', // HTML5 Spec values: none, metadata, auto. volume: 0.8, // The volume. Number 0 to 1. muted: false, remainingDuration: false, // When true, the remaining time is shown in the duration GUI element. toggleDuration: false, // When true, clicks on the duration toggle between the duration and remaining display. captureDuration: true, // When true, clicks on the duration are captured and no longer propagate up the DOM. playbackRate: 1, defaultPlaybackRate: 1, minPlaybackRate: 0.5, maxPlaybackRate: 4, wmode: "opaque", // Valid wmode: window, transparent, opaque, direct, gpu. backgroundColor: "#000000", // To define the jPlayer div and Flash background color. cssSelectorAncestor: "#jp_container_1", cssSelector: { // * denotes properties that should only be required when video media type required. _cssSelector() would require changes to enable splitting these into Audio and Video defaults. videoPlay: ".jp-video-play", // * play: ".jp-play", pause: ".jp-pause", stop: ".jp-stop", seekBar: ".jp-seek-bar", playBar: ".jp-play-bar", mute: ".jp-mute", unmute: ".jp-unmute", volumeBar: ".jp-volume-bar", volumeBarValue: ".jp-volume-bar-value", volumeMax: ".jp-volume-max", playbackRateBar: ".jp-playback-rate-bar", playbackRateBarValue: ".jp-playback-rate-bar-value", currentTime: ".jp-current-time", duration: ".jp-duration", title: ".jp-title", fullScreen: ".jp-full-screen", // * restoreScreen: ".jp-restore-screen", // * repeat: ".jp-repeat", repeatOff: ".jp-repeat-off", gui: ".jp-gui", // The interface used with autohide feature. noSolution: ".jp-no-solution" // For error feedback when jPlayer cannot find a solution. }, smoothPlayBar: false, // Smooths the play bar transitions, which affects clicks and short media with big changes per second. fullScreen: false, // Native Full Screen fullWindow: false, autohide: { restored: false, // Controls the interface autohide feature. full: true, // Controls the interface autohide feature. fadeIn: 200, // Milliseconds. The period of the fadeIn anim. fadeOut: 600, // Milliseconds. The period of the fadeOut anim. hold: 1000 // Milliseconds. The period of the pause before autohide beings. }, loop: false, repeat: function(event) { // The default jPlayer repeat event handler if(event.jPlayer.options.loop) { $(this).unbind(".jPlayerRepeat").bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function() { $(this).jPlayer("play"); }); } else { $(this).unbind(".jPlayerRepeat"); } }, nativeVideoControls: { // Works well on standard browsers. // Phone and tablet browsers can have problems with the controls disappearing. }, noFullWindow: { msie: /msie [0-6]\./, ipad: /ipad.*?os [0-4]\./, iphone: /iphone/, ipod: /ipod/, android_pad: /android [0-3]\.(?!.*?mobile)/, android_phone: /android.*?mobile/, blackberry: /blackberry/, windows_ce: /windows ce/, iemobile: /iemobile/, webos: /webos/ }, noVolume: { ipad: /ipad/, iphone: /iphone/, ipod: /ipod/, android_pad: /android(?!.*?mobile)/, android_phone: /android.*?mobile/, blackberry: /blackberry/, windows_ce: /windows ce/, iemobile: /iemobile/, webos: /webos/, playbook: /playbook/ }, timeFormat: { // Specific time format for this instance. The supported options are defined in $.jPlayer.timeFormat // For the undefined options we use the default from $.jPlayer.timeFormat }, keyEnabled: false, // Enables keyboard controls. audioFullScreen: false, // Enables keyboard controls to enter full screen with audio media. keyBindings: { // The key control object, defining the key codes and the functions to execute. // The parameter, f = $.jPlayer.focus, will be checked truethy before attempting to call any of these functions. // Properties may be added to this object, in key/fn pairs, to enable other key controls. EG, for the playlist add-on. play: { key: 32, // space fn: function(f) { if(f.status.paused) { f.play(); } else { f.pause(); } } }, fullScreen: { key: 13, // enter fn: function(f) { if(f.status.video || f.options.audioFullScreen) { f._setOption("fullScreen", !f.options.fullScreen); } } }, muted: { key: 8, // backspace fn: function(f) { f._muted(!f.options.muted); } }, volumeUp: { key: 38, // UP fn: function(f) { f.volume(f.options.volume + 0.1); } }, volumeDown: { key: 40, // DOWN fn: function(f) { f.volume(f.options.volume - 0.1); } } }, verticalVolume: false, // Calculate volume from the bottom of the volume bar. Default is from the left. Also volume affects either width or height. verticalPlaybackRate: false, globalVolume: false, // Set to make volume and muted changes affect all jPlayer instances with this option enabled idPrefix: "jp", // Prefix for the ids of html elements created by jPlayer. For flash, this must not include characters: . - + * / \ noConflict: "jQuery", emulateHtml: false, // Emulates the HTML5 Media element on the jPlayer element. consoleAlerts: true, // Alerts are sent to the console.log() instead of alert(). errorAlerts: false, warningAlerts: false }, optionsAudio: { size: { width: "0px", height: "0px", cssClass: "" }, sizeFull: { width: "0px", height: "0px", cssClass: "" } }, optionsVideo: { size: { width: "480px", height: "270px", cssClass: "jp-video-270p" }, sizeFull: { width: "100%", height: "100%", cssClass: "jp-video-full" } }, instances: {}, // Static Object status: { // Instanced in _init() src: "", media: {}, paused: true, format: {}, formatType: "", waitForPlay: true, // Same as waitForLoad except in case where preloading. waitForLoad: true, srcSet: false, video: false, // True if playing a video seekPercent: 0, currentPercentRelative: 0, currentPercentAbsolute: 0, currentTime: 0, duration: 0, remaining: 0, videoWidth: 0, // Intrinsic width of the video in pixels. videoHeight: 0, // Intrinsic height of the video in pixels. readyState: 0, networkState: 0, playbackRate: 1, // Warning - Now both an option and a status property ended: 0 /* Persistant status properties created dynamically at _init(): width height cssClass nativeVideoControls noFullWindow noVolume playbackRateEnabled // Warning - Technically, we can have both Flash and HTML, so this might not be correct if the Flash is active. That is a niche case. */ }, internal: { // Instanced in _init() ready: false // instance: undefined // domNode: undefined // htmlDlyCmdId: undefined // autohideId: undefined // cmdsIgnored }, solution: { // Static Object: Defines the solutions built in jPlayer. html: true, flash: true }, // 'MPEG-4 support' : canPlayType('video/mp4; codecs="mp4v.20.8"') format: { // Static Object mp3: { codec: 'audio/mpeg; codecs="mp3"', flashCanPlay: true, media: 'audio' }, m4a: { // AAC / MP4 codec: 'audio/mp4; codecs="mp4a.40.2"', flashCanPlay: true, media: 'audio' }, m3u8a: { // AAC / MP4 / Apple HLS codec: 'application/vnd.apple.mpegurl; codecs="mp4a.40.2"', flashCanPlay: false, media: 'audio' }, m3ua: { // M3U codec: 'audio/mpegurl', flashCanPlay: false, media: 'audio' }, oga: { // OGG codec: 'audio/ogg; codecs="vorbis, opus"', flashCanPlay: false, media: 'audio' }, flac: { // FLAC codec: 'audio/x-flac', flashCanPlay: false, media: 'audio' }, wav: { // PCM codec: 'audio/wav; codecs="1"', flashCanPlay: false, media: 'audio' }, webma: { // WEBM codec: 'audio/webm; codecs="vorbis"', flashCanPlay: false, media: 'audio' }, fla: { // FLV / F4A codec: 'audio/x-flv', flashCanPlay: true, media: 'audio' }, rtmpa: { // RTMP AUDIO codec: 'audio/rtmp; codecs="rtmp"', flashCanPlay: true, media: 'audio' }, m4v: { // H.264 / MP4 codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"', flashCanPlay: true, media: 'video' }, m3u8v: { // H.264 / AAC / MP4 / Apple HLS codec: 'application/vnd.apple.mpegurl; codecs="avc1.42E01E, mp4a.40.2"', flashCanPlay: false, media: 'video' }, m3uv: { // M3U codec: 'audio/mpegurl', flashCanPlay: false, media: 'video' }, ogv: { // OGG codec: 'video/ogg; codecs="theora, vorbis"', flashCanPlay: false, media: 'video' }, webmv: { // WEBM codec: 'video/webm; codecs="vorbis, vp8"', flashCanPlay: false, media: 'video' }, flv: { // FLV / F4V codec: 'video/x-flv', flashCanPlay: true, media: 'video' }, rtmpv: { // RTMP VIDEO codec: 'video/rtmp; codecs="rtmp"', flashCanPlay: true, media: 'video' } }, _init: function() { var self = this; this.element.empty(); this.status = $.extend({}, this.status); // Copy static to unique instance. this.internal = $.extend({}, this.internal); // Copy static to unique instance. // Initialize the time format this.options.timeFormat = $.extend({}, $.jPlayer.timeFormat, this.options.timeFormat); // On iOS, assume commands will be ignored before user initiates them. this.internal.cmdsIgnored = $.jPlayer.platform.ipad || $.jPlayer.platform.iphone || $.jPlayer.platform.ipod; this.internal.domNode = this.element.get(0); // Add key bindings focus to 1st jPlayer instanced with key control enabled. if(this.options.keyEnabled && !$.jPlayer.focus) { $.jPlayer.focus = this; } // A fix for Android where older (2.3) and even some 4.x devices fail to work when changing the *audio* SRC and then playing immediately. this.androidFix = { setMedia: false, // True when media set play: false, // True when a progress event will instruct the media to play pause: false, // True when a progress event will instruct the media to pause at a time. time: NaN // The play(time) parameter }; if($.jPlayer.platform.android) { this.options.preload = this.options.preload !== 'auto' ? 'metadata' : 'auto'; // Default to metadata, but allow auto. } this.formats = []; // Array based on supplied string option. Order defines priority. this.solutions = []; // Array based on solution string option. Order defines priority. this.require = {}; // Which media types are required: video, audio. this.htmlElement = {}; // DOM elements created by jPlayer this.html = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.html.audio = {}; this.html.video = {}; this.flash = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.css = {}; this.css.cs = {}; // Holds the css selector strings this.css.jq = {}; // Holds jQuery selectors. ie., $(css.cs.method) this.ancestorJq = []; // Holds jQuery selector of cssSelectorAncestor. Init would use $() instead of [], but it is only 1.4+ this.options.volume = this._limitValue(this.options.volume, 0, 1); // Limit volume value's bounds. // Create the formats array, with prority based on the order of the supplied formats string $.each(this.options.supplied.toLowerCase().split(","), function(index1, value1) { var format = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.format[format]) { // Check format is valid. var dupFound = false; $.each(self.formats, function(index2, value2) { // Check for duplicates if(format === value2) { dupFound = true; return false; } }); if(!dupFound) { self.formats.push(format); } } }); // Create the solutions array, with prority based on the order of the solution string $.each(this.options.solution.toLowerCase().split(","), function(index1, value1) { var solution = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.solution[solution]) { // Check solution is valid. var dupFound = false; $.each(self.solutions, function(index2, value2) { // Check for duplicates if(solution === value2) { dupFound = true; return false; } }); if(!dupFound) { self.solutions.push(solution); } } }); this.internal.instance = "jp_" + this.count; this.instances[this.internal.instance] = this.element; // Check the jPlayer div has an id and create one if required. Important for Flash to know the unique id for comms. if(!this.element.attr("id")) { this.element.attr("id", this.options.idPrefix + "_jplayer_" + this.count); } this.internal.self = $.extend({}, { id: this.element.attr("id"), jq: this.element }); this.internal.audio = $.extend({}, { id: this.options.idPrefix + "_audio_" + this.count, jq: undefined }); this.internal.video = $.extend({}, { id: this.options.idPrefix + "_video_" + this.count, jq: undefined }); this.internal.flash = $.extend({}, { id: this.options.idPrefix + "_flash_" + this.count, jq: undefined, swf: this.options.swfPath + (this.options.swfPath.toLowerCase().slice(-4) !== ".swf" ? (this.options.swfPath && this.options.swfPath.slice(-1) !== "/" ? "/" : "") + "Jplayer.swf" : "") }); this.internal.poster = $.extend({}, { id: this.options.idPrefix + "_poster_" + this.count, jq: undefined }); // Register listeners defined in the constructor $.each($.jPlayer.event, function(eventName,eventType) { if(self.options[eventName] !== undefined) { self.element.bind(eventType + ".jPlayer", self.options[eventName]); // With .jPlayer namespace. self.options[eventName] = undefined; // Destroy the handler pointer copy on the options. Reason, events can be added/removed in other ways so this could be obsolete and misleading. } }); // Determine if we require solutions for audio, video or both media types. this.require.audio = false; this.require.video = false; $.each(this.formats, function(priority, format) { self.require[self.format[format].media] = true; }); // Now required types are known, finish the options default settings. if(this.require.video) { this.options = $.extend(true, {}, this.optionsVideo, this.options ); } else { this.options = $.extend(true, {}, this.optionsAudio, this.options ); } this._setSize(); // update status and jPlayer element size // Determine the status for Blocklisted options. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); this.status.noFullWindow = this._uaBlocklist(this.options.noFullWindow); this.status.noVolume = this._uaBlocklist(this.options.noVolume); // Create event handlers if native fullscreen is supported if($.jPlayer.nativeFeatures.fullscreen.api.fullscreenEnabled) { this._fullscreenAddEventListeners(); } // The native controls are only for video and are disabled when audio is also used. this._restrictNativeVideoControls(); // Create the poster image. this.htmlElement.poster = document.createElement('img'); this.htmlElement.poster.id = this.internal.poster.id; this.htmlElement.poster.onload = function() { // Note that this did not work on Firefox 3.6: poster.addEventListener("onload", function() {}, false); Did not investigate x-browser. if(!self.status.video || self.status.waitForPlay) { self.internal.poster.jq.show(); } }; this.element.append(this.htmlElement.poster); this.internal.poster.jq = $("#" + this.internal.poster.id); this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height}); this.internal.poster.jq.hide(); this.internal.poster.jq.bind("click.jPlayer", function() { self._trigger($.jPlayer.event.click); }); // Generate the required media elements this.html.audio.available = false; if(this.require.audio) { // If a supplied format is audio this.htmlElement.audio = document.createElement('audio'); this.htmlElement.audio.id = this.internal.audio.id; this.html.audio.available = !!this.htmlElement.audio.canPlayType && this._testCanPlayType(this.htmlElement.audio); // Test is for IE9 on Win Server 2008. } this.html.video.available = false; if(this.require.video) { // If a supplied format is video this.htmlElement.video = document.createElement('video'); this.htmlElement.video.id = this.internal.video.id; this.html.video.available = !!this.htmlElement.video.canPlayType && this._testCanPlayType(this.htmlElement.video); // Test is for IE9 on Win Server 2008. } this.flash.available = this._checkForFlash(10.1); this.html.canPlay = {}; this.flash.canPlay = {}; $.each(this.formats, function(priority, format) { self.html.canPlay[format] = self.html[self.format[format].media].available && "" !== self.htmlElement[self.format[format].media].canPlayType(self.format[format].codec); self.flash.canPlay[format] = self.format[format].flashCanPlay && self.flash.available; }); this.html.desired = false; this.flash.desired = false; $.each(this.solutions, function(solutionPriority, solution) { if(solutionPriority === 0) { self[solution].desired = true; } else { var audioCanPlay = false; var videoCanPlay = false; $.each(self.formats, function(formatPriority, format) { if(self[self.solutions[0]].canPlay[format]) { // The other solution can play if(self.format[format].media === 'video') { videoCanPlay = true; } else { audioCanPlay = true; } } }); self[solution].desired = (self.require.audio && !audioCanPlay) || (self.require.video && !videoCanPlay); } }); // This is what jPlayer will support, based on solution and supplied. this.html.support = {}; this.flash.support = {}; $.each(this.formats, function(priority, format) { self.html.support[format] = self.html.canPlay[format] && self.html.desired; self.flash.support[format] = self.flash.canPlay[format] && self.flash.desired; }); // If jPlayer is supporting any format in a solution, then the solution is used. this.html.used = false; this.flash.used = false; $.each(this.solutions, function(solutionPriority, solution) { $.each(self.formats, function(formatPriority, format) { if(self[solution].support[format]) { self[solution].used = true; return false; } }); }); // Init solution active state and the event gates to false. this._resetActive(); this._resetGate(); // Set up the css selectors for the control and feedback entities. this._cssSelectorAncestor(this.options.cssSelectorAncestor); // If neither html nor flash are being used by this browser, then media playback is not possible. Trigger an error event. if(!(this.html.used || this.flash.used)) { this._error( { type: $.jPlayer.error.NO_SOLUTION, context: "{solution:'" + this.options.solution + "', supplied:'" + this.options.supplied + "'}", message: $.jPlayer.errorMsg.NO_SOLUTION, hint: $.jPlayer.errorHint.NO_SOLUTION }); if(this.css.jq.noSolution.length) { this.css.jq.noSolution.show(); } } else { if(this.css.jq.noSolution.length) { this.css.jq.noSolution.hide(); } } // Add the flash solution if it is being used. if(this.flash.used) { var htmlObj, flashVars = 'jQuery=' + encodeURI(this.options.noConflict) + '&id=' + encodeURI(this.internal.self.id) + '&vol=' + this.options.volume + '&muted=' + this.options.muted; // Code influenced by SWFObject 2.2: http://code.google.com/p/swfobject/ // Non IE browsers have an initial Flash size of 1 by 1 otherwise the wmode affected the Flash ready event. if($.jPlayer.browser.msie && (Number($.jPlayer.browser.version) < 9 || $.jPlayer.browser.documentMode < 9)) { var objStr = '<object id="' + this.internal.flash.id + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0" tabindex="-1"></object>'; var paramStr = [ '<param name="movie" value="' + this.internal.flash.swf + '" />', '<param name="FlashVars" value="' + flashVars + '" />', '<param name="allowScriptAccess" value="always" />', '<param name="bgcolor" value="' + this.options.backgroundColor + '" />', '<param name="wmode" value="' + this.options.wmode + '" />' ]; htmlObj = document.createElement(objStr); for(var i=0; i < paramStr.length; i++) { htmlObj.appendChild(document.createElement(paramStr[i])); } } else { var createParam = function(el, n, v) { var p = document.createElement("param"); p.setAttribute("name", n); p.setAttribute("value", v); el.appendChild(p); }; htmlObj = document.createElement("object"); htmlObj.setAttribute("id", this.internal.flash.id); htmlObj.setAttribute("name", this.internal.flash.id); htmlObj.setAttribute("data", this.internal.flash.swf); htmlObj.setAttribute("type", "application/x-shockwave-flash"); htmlObj.setAttribute("width", "1"); // Non-zero htmlObj.setAttribute("height", "1"); // Non-zero htmlObj.setAttribute("tabindex", "-1"); createParam(htmlObj, "flashvars", flashVars); createParam(htmlObj, "allowscriptaccess", "always"); createParam(htmlObj, "bgcolor", this.options.backgroundColor); createParam(htmlObj, "wmode", this.options.wmode); } this.element.append(htmlObj); this.internal.flash.jq = $(htmlObj); } // Setup playbackRate ability before using _addHtmlEventListeners() if(this.html.used && !this.flash.used) { // If only HTML // Using the audio element capabilities for playbackRate. ie., Assuming video element is the same. this.status.playbackRateEnabled = this._testPlaybackRate('audio'); } else { this.status.playbackRateEnabled = false; } this._updatePlaybackRate(); // Add the HTML solution if being used. if(this.html.used) { // The HTML Audio handlers if(this.html.audio.available) { this._addHtmlEventListeners(this.htmlElement.audio, this.html.audio); this.element.append(this.htmlElement.audio); this.internal.audio.jq = $("#" + this.internal.audio.id); } // The HTML Video handlers if(this.html.video.available) { this._addHtmlEventListeners(this.htmlElement.video, this.html.video); this.element.append(this.htmlElement.video); this.internal.video.jq = $("#" + this.internal.video.id); if(this.status.nativeVideoControls) { this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else { this.internal.video.jq.css({'width':'0px', 'height':'0px'}); // Using size 0x0 since a .hide() causes issues in iOS } this.internal.video.jq.bind("click.jPlayer", function() { self._trigger($.jPlayer.event.click); }); } } // Create the bridge that emulates the HTML Media element on the jPlayer DIV if( this.options.emulateHtml ) { this._emulateHtmlBridge(); } if(this.html.used && !this.flash.used) { // If only HTML, then emulate flash ready() call after 100ms. setTimeout( function() { self.internal.ready = true; self.version.flash = "n/a"; self._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option. self._trigger($.jPlayer.event.ready); }, 100); } // Initialize the interface components with the options. this._updateNativeVideoControls(); // The other controls are now setup in _cssSelectorAncestor() if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } $.jPlayer.prototype.count++; // Change static variable via prototype. }, destroy: function() { // MJP: The background change remains. Would need to store the original to restore it correctly. // MJP: The jPlayer element's size change remains. // Clear the media to reset the GUI and stop any downloads. Streams on some browsers had persited. (Chrome) this.clearMedia(); // Remove the size/sizeFull cssClass from the cssSelectorAncestor this._removeUiClass(); // Remove the times from the GUI if(this.css.jq.currentTime.length) { this.css.jq.currentTime.text(""); } if(this.css.jq.duration.length) { this.css.jq.duration.text(""); } // Remove any bindings from the interface controls. $.each(this.css.jq, function(fn, jq) { // Check selector is valid before trying to execute method. if(jq.length) { jq.unbind(".jPlayer"); } }); // Remove the click handlers for $.jPlayer.event.click this.internal.poster.jq.unbind(".jPlayer"); if(this.internal.video.jq) { this.internal.video.jq.unbind(".jPlayer"); } // Remove the fullscreen event handlers this._fullscreenRemoveEventListeners(); // Remove key bindings if(this === $.jPlayer.focus) { $.jPlayer.focus = null; } // Destroy the HTML bridge. if(this.options.emulateHtml) { this._destroyHtmlBridge(); } this.element.removeData("jPlayer"); // Remove jPlayer data this.element.unbind(".jPlayer"); // Remove all event handlers created by the jPlayer constructor this.element.empty(); // Remove the inserted child elements delete this.instances[this.internal.instance]; // Clear the instance on the static instance object }, enable: function() { // Plan to implement // options.disabled = false }, disable: function () { // Plan to implement // options.disabled = true }, _testCanPlayType: function(elem) { // IE9 on Win Server 2008 did not implement canPlayType(), but it has the property. try { elem.canPlayType(this.format.mp3.codec); // The type is irrelevant. return true; } catch(err) { return false; } }, _testPlaybackRate: function(type) { // type: String 'audio' or 'video' var el, rate = 0.5; type = typeof type === 'string' ? type : 'audio'; el = document.createElement(type); // Wrapping in a try/catch, just in case older HTML5 browsers throw and error. try { if('playbackRate' in el) { el.playbackRate = rate; return el.playbackRate === rate; } else { return false; } } catch(err) { return false; } }, _uaBlocklist: function(list) { // list : object with properties that are all regular expressions. Property names are irrelevant. // Returns true if the user agent is matched in list. var ua = navigator.userAgent.toLowerCase(), block = false; $.each(list, function(p, re) { if(re && re.test(ua)) { block = true; return false; // exit $.each. } }); return block; }, _restrictNativeVideoControls: function() { // Fallback to noFullWindow when nativeVideoControls is true and audio media is being used. Affects when both media types are used. if(this.require.audio) { if(this.status.nativeVideoControls) { this.status.nativeVideoControls = false; this.status.noFullWindow = true; } } }, _updateNativeVideoControls: function() { if(this.html.video.available && this.html.used) { // Turn the HTML Video controls on/off this.htmlElement.video.controls = this.status.nativeVideoControls; // Show/hide the jPlayer GUI. this._updateAutohide(); // For when option changed. The poster image is not updated, as it is dealt with in setMedia(). Acceptable degradation since seriously doubt these options will change on the fly. Can again review later. if(this.status.nativeVideoControls && this.require.video) { this.internal.poster.jq.hide(); this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else if(this.status.waitForPlay && this.status.video) { this.internal.poster.jq.show(); this.internal.video.jq.css({'width': '0px', 'height': '0px'}); } } }, _addHtmlEventListeners: function(mediaElement, entity) { var self = this; mediaElement.preload = this.options.preload; mediaElement.muted = this.options.muted; mediaElement.volume = this.options.volume; if(this.status.playbackRateEnabled) { mediaElement.defaultPlaybackRate = this.options.defaultPlaybackRate; mediaElement.playbackRate = this.options.playbackRate; } // Create the event listeners // Only want the active entity to affect jPlayer and bubble events. // Using entity.gate so that object is referenced and gate property always current mediaElement.addEventListener("progress", function() { if(entity.gate) { if(self.internal.cmdsIgnored && this.readyState > 0) { // Detect iOS executed the command self.internal.cmdsIgnored = false; } self.androidFix.setMedia = false; // Disable the fix after the first progress event. if(self.androidFix.play) { // Play Android audio - performing the fix. self.androidFix.play = false; self.play(self.androidFix.time); } if(self.androidFix.pause) { // Pause Android audio at time - performing the fix. self.androidFix.pause = false; self.pause(self.androidFix.time); } self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.progress); } }, false); mediaElement.addEventListener("timeupdate", function() { if(entity.gate) { self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.timeupdate); } }, false); mediaElement.addEventListener("durationchange", function() { if(entity.gate) { self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.durationchange); } }, false); mediaElement.addEventListener("play", function() { if(entity.gate) { self._updateButtons(true); self._html_checkWaitForPlay(); // So the native controls update this variable and puts the hidden interface in the correct state. Affects toggling native controls. self._trigger($.jPlayer.event.play); } }, false); mediaElement.addEventListener("playing", function() { if(entity.gate) { self._updateButtons(true); self._seeked(); self._trigger($.jPlayer.event.playing); } }, false); mediaElement.addEventListener("pause", function() { if(entity.gate) { self._updateButtons(false); self._trigger($.jPlayer.event.pause); } }, false); mediaElement.addEventListener("waiting", function() { if(entity.gate) { self._seeking(); self._trigger($.jPlayer.event.waiting); } }, false); mediaElement.addEventListener("seeking", function() { if(entity.gate) { self._seeking(); self._trigger($.jPlayer.event.seeking); } }, false); mediaElement.addEventListener("seeked", function() { if(entity.gate) { self._seeked(); self._trigger($.jPlayer.event.seeked); } }, false); mediaElement.addEventListener("volumechange", function() { if(entity.gate) { // Read the values back from the element as the Blackberry PlayBook shares the volume with the physical buttons master volume control. // However, when tested 6th July 2011, those buttons do not generate an event. The physical play/pause button does though. self.options.volume = mediaElement.volume; self.options.muted = mediaElement.muted; self._updateMute(); self._updateVolume(); self._trigger($.jPlayer.event.volumechange); } }, false); mediaElement.addEventListener("ratechange", function() { if(entity.gate) { self.options.defaultPlaybackRate = mediaElement.defaultPlaybackRate; self.options.playbackRate = mediaElement.playbackRate; self._updatePlaybackRate(); self._trigger($.jPlayer.event.ratechange); } }, false); mediaElement.addEventListener("suspend", function() { // Seems to be the only way of capturing that the iOS4 browser did not actually play the media from the page code. ie., It needs a user gesture. if(entity.gate) { self._seeked(); self._trigger($.jPlayer.event.suspend); } }, false); mediaElement.addEventListener("ended", function() { if(entity.gate) { // Order of the next few commands are important. Change the time and then pause. // Solves a bug in Firefox, where issuing pause 1st causes the media to play from the start. ie., The pause is ignored. if(!$.jPlayer.browser.webkit) { // Chrome crashes if you do this in conjunction with a setMedia command in an ended event handler. ie., The playlist demo. self.htmlElement.media.currentTime = 0; // Safari does not care about this command. ie., It works with or without this line. (Both Safari and Chrome are Webkit.) } self.htmlElement.media.pause(); // Pause otherwise a click on the progress bar will play from that point, when it shouldn't, since it stopped playback. self._updateButtons(false); self._getHtmlStatus(mediaElement, true); // With override true. Otherwise Chrome leaves progress at full. self._updateInterface(); self._trigger($.jPlayer.event.ended); } }, false); mediaElement.addEventListener("error", function() { if(entity.gate) { self._updateButtons(false); self._seeked(); if(self.status.srcSet) { // Deals with case of clearMedia() causing an error event. clearTimeout(self.internal.htmlDlyCmdId); // Clears any delayed commands used in the HTML solution. self.status.waitForLoad = true; // Allows the load operation to try again. self.status.waitForPlay = true; // Reset since a play was captured. if(self.status.video && !self.status.nativeVideoControls) { self.internal.video.jq.css({'width':'0px', 'height':'0px'}); } if(self._validString(self.status.media.poster) && !self.status.nativeVideoControls) { self.internal.poster.jq.show(); } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.show(); } self._error( { type: $.jPlayer.error.URL, context: self.status.src, // this.src shows absolute urls. Want context to show the url given. message: $.jPlayer.errorMsg.URL, hint: $.jPlayer.errorHint.URL }); } } }, false); // Create all the other event listeners that bubble up to a jPlayer event from html, without being used by jPlayer. $.each($.jPlayer.htmlEvent, function(i, eventType) { mediaElement.addEventListener(this, function() { if(entity.gate) { self._trigger($.jPlayer.event[eventType]); } }, false); }); }, _getHtmlStatus: function(media, override) { var ct = 0, cpa = 0, sp = 0, cpr = 0; // Fixes the duration bug in iOS, where the durationchange event occurs when media.duration is not always correct. // Fixes the initial duration bug in BB OS7, where the media.duration is infinity and displays as NaN:NaN due to Date() using inifity. if(isFinite(media.duration)) { this.status.duration = media.duration; } ct = media.currentTime; cpa = (this.status.duration > 0) ? 100 * ct / this.status.duration : 0; if((typeof media.seekable === "object") && (media.seekable.length > 0)) { sp = (this.status.duration > 0) ? 100 * media.seekable.end(media.seekable.length-1) / this.status.duration : 100; cpr = (this.status.duration > 0) ? 100 * media.currentTime / media.seekable.end(media.seekable.length-1) : 0; // Duration conditional for iOS duration bug. ie., seekable.end is a NaN in that case. } else { sp = 100; cpr = cpa; } if(override) { ct = 0; cpr = 0; cpa = 0; } this.status.seekPercent = sp; this.status.currentPercentRelative = cpr; this.status.currentPercentAbsolute = cpa; this.status.currentTime = ct; this.status.remaining = this.status.duration - this.status.currentTime; this.status.videoWidth = media.videoWidth; this.status.videoHeight = media.videoHeight; this.status.readyState = media.readyState; this.status.networkState = media.networkState; this.status.playbackRate = media.playbackRate; this.status.ended = media.ended; }, _resetStatus: function() { this.status = $.extend({}, this.status, $.jPlayer.prototype.status); // Maintains the status properties that persist through a reset. }, _trigger: function(eventType, error, warning) { // eventType always valid as called using $.jPlayer.event.eventType var event = $.Event(eventType); event.jPlayer = {}; event.jPlayer.version = $.extend({}, this.version); event.jPlayer.options = $.extend(true, {}, this.options); // Deep copy event.jPlayer.status = $.extend(true, {}, this.status); // Deep copy event.jPlayer.html = $.extend(true, {}, this.html); // Deep copy event.jPlayer.flash = $.extend(true, {}, this.flash); // Deep copy if(error) { event.jPlayer.error = $.extend({}, error); } if(warning) { event.jPlayer.warning = $.extend({}, warning); } this.element.trigger(event); }, jPlayerFlashEvent: function(eventType, status) { // Called from Flash if(eventType === $.jPlayer.event.ready) { if(!this.internal.ready) { this.internal.ready = true; this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); // Once Flash generates the ready event, minimise to zero as it is not affected by wmode anymore. this.version.flash = status.version; if(this.version.needFlash !== this.version.flash) { this._error( { type: $.jPlayer.error.VERSION, context: this.version.flash, message: $.jPlayer.errorMsg.VERSION + this.version.flash, hint: $.jPlayer.errorHint.VERSION }); } this._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option. this._trigger(eventType); } else { // This condition occurs if the Flash is hidden and then shown again. // Firefox also reloads the Flash if the CSS position changes. position:fixed is used for full screen. // Only do this if the Flash is the solution being used at the moment. Affects Media players where both solution may be being used. if(this.flash.gate) { // Send the current status to the Flash now that it is ready (available) again. if(this.status.srcSet) { // Need to read original status before issuing the setMedia command. var currentTime = this.status.currentTime, paused = this.status.paused; this.setMedia(this.status.media); this.volumeWorker(this.options.volume); if(currentTime > 0) { if(paused) { this.pause(currentTime); } else { this.play(currentTime); } } } this._trigger($.jPlayer.event.flashreset); } } } if(this.flash.gate) { switch(eventType) { case $.jPlayer.event.progress: this._getFlashStatus(status); this._updateInterface(); this._trigger(eventType); break; case $.jPlayer.event.timeupdate: this._getFlashStatus(status); this._updateInterface(); this._trigger(eventType); break; case $.jPlayer.event.play: this._seeked(); this._updateButtons(true); this._trigger(eventType); break; case $.jPlayer.event.pause: this._updateButtons(false); this._trigger(eventType); break; case $.jPlayer.event.ended: this._updateButtons(false); this._trigger(eventType); break; case $.jPlayer.event.click: this._trigger(eventType); // This could be dealt with by the default break; case $.jPlayer.event.error: this.status.waitForLoad = true; // Allows the load operation to try again. this.status.waitForPlay = true; // Reset since a play was captured. if(this.status.video) { this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); } if(this._validString(this.status.media.poster)) { this.internal.poster.jq.show(); } if(this.css.jq.videoPlay.length && this.status.video) { this.css.jq.videoPlay.show(); } if(this.status.video) { // Set up for another try. Execute before error event. this._flash_setVideo(this.status.media); } else { this._flash_setAudio(this.status.media); } this._updateButtons(false); this._error( { type: $.jPlayer.error.URL, context:status.src, message: $.jPlayer.errorMsg.URL, hint: $.jPlayer.errorHint.URL }); break; case $.jPlayer.event.seeking: this._seeking(); this._trigger(eventType); break; case $.jPlayer.event.seeked: this._seeked(); this._trigger(eventType); break; case $.jPlayer.event.ready: // The ready event is handled outside the switch statement. // Captured here otherwise 2 ready events would be generated if the ready event handler used setMedia. break; default: this._trigger(eventType); } } return false; }, _getFlashStatus: function(status) { this.status.seekPercent = status.seekPercent; this.status.currentPercentRelative = status.currentPercentRelative; this.status.currentPercentAbsolute = status.currentPercentAbsolute; this.status.currentTime = status.currentTime; this.status.duration = status.duration; this.status.remaining = status.duration - status.currentTime; this.status.videoWidth = status.videoWidth; this.status.videoHeight = status.videoHeight; // The Flash does not generate this information in this release this.status.readyState = 4; // status.readyState; this.status.networkState = 0; // status.networkState; this.status.playbackRate = 1; // status.playbackRate; this.status.ended = false; // status.ended; }, _updateButtons: function(playing) { if(playing === undefined) { playing = !this.status.paused; } else { this.status.paused = !playing; } if(this.css.jq.play.length && this.css.jq.pause.length) { if(playing) { this.css.jq.play.hide(); this.css.jq.pause.show(); } else { this.css.jq.play.show(); this.css.jq.pause.hide(); } } if(this.css.jq.restoreScreen.length && this.css.jq.fullScreen.length) { if(this.status.noFullWindow) { this.css.jq.fullScreen.hide(); this.css.jq.restoreScreen.hide(); } else if(this.options.fullWindow) { this.css.jq.fullScreen.hide(); this.css.jq.restoreScreen.show(); } else { this.css.jq.fullScreen.show(); this.css.jq.restoreScreen.hide(); } } if(this.css.jq.repeat.length && this.css.jq.repeatOff.length) { if(this.options.loop) { this.css.jq.repeat.hide(); this.css.jq.repeatOff.show(); } else { this.css.jq.repeat.show(); this.css.jq.repeatOff.hide(); } } }, _updateInterface: function() { if(this.css.jq.seekBar.length) { this.css.jq.seekBar.width(this.status.seekPercent+"%"); } if(this.css.jq.playBar.length) { if(this.options.smoothPlayBar) { this.css.jq.playBar.stop().animate({ width: this.status.currentPercentAbsolute+"%" }, 250, "linear"); } else { this.css.jq.playBar.width(this.status.currentPercentRelative+"%"); } } var currentTimeText = ''; if(this.css.jq.currentTime.length) { currentTimeText = this._convertTime(this.status.currentTime); if(currentTimeText !== this.css.jq.currentTime.text()) { this.css.jq.currentTime.text(this._convertTime(this.status.currentTime)); } } var durationText = '', duration = this.status.duration, remaining = this.status.remaining; if(this.css.jq.duration.length) { if(typeof this.status.media.duration === 'string') { durationText = this.status.media.duration; } else { if(typeof this.status.media.duration === 'number') { duration = this.status.media.duration; remaining = duration - this.status.currentTime; } if(this.options.remainingDuration) { durationText = (remaining > 0 ? '-' : '') + this._convertTime(remaining); } else { durationText = this._convertTime(duration); } } if(durationText !== this.css.jq.duration.text()) { this.css.jq.duration.text(durationText); } } }, _convertTime: ConvertTime.prototype.time, _seeking: function() { if(this.css.jq.seekBar.length) { this.css.jq.seekBar.addClass("jp-seeking-bg"); } }, _seeked: function() { if(this.css.jq.seekBar.length) { this.css.jq.seekBar.removeClass("jp-seeking-bg"); } }, _resetGate: function() { this.html.audio.gate = false; this.html.video.gate = false; this.flash.gate = false; }, _resetActive: function() { this.html.active = false; this.flash.active = false; }, _escapeHtml: function(s) { return s.split('&').join('&').split('<').join('<').split('>').join('>').split('"').join('"'); }, _qualifyURL: function(url) { var el = document.createElement('div'); el.innerHTML= '<a href="' + this._escapeHtml(url) + '">x</a>'; return el.firstChild.href; }, _absoluteMediaUrls: function(media) { var self = this; $.each(media, function(type, url) { if(url && self.format[type]) { media[type] = self._qualifyURL(url); } }); return media; }, setMedia: function(media) { /* media[format] = String: URL of format. Must contain all of the supplied option's video or audio formats. * media.poster = String: Video poster URL. * media.track = Array: Of objects defining the track element: kind, src, srclang, label, def. * media.stream = Boolean: * NOT IMPLEMENTED * Designating actual media streams. ie., "false/undefined" for files. Plan to refresh the flash every so often. */ var self = this, supported = false, posterChanged = this.status.media.poster !== media.poster; // Compare before reset. Important for OSX Safari as this.htmlElement.poster.src is absolute, even if original poster URL was relative. this._resetMedia(); this._resetGate(); this._resetActive(); // Clear the Android Fix. this.androidFix.setMedia = false; this.androidFix.play = false; this.androidFix.pause = false; // Convert all media URLs to absolute URLs. media = this._absoluteMediaUrls(media); $.each(this.formats, function(formatPriority, format) { var isVideo = self.format[format].media === 'video'; $.each(self.solutions, function(solutionPriority, solution) { if(self[solution].support[format] && self._validString(media[format])) { // Format supported in solution and url given for format. var isHtml = solution === 'html'; if(isVideo) { if(isHtml) { self.html.video.gate = true; self._html_setVideo(media); self.html.active = true; } else { self.flash.gate = true; self._flash_setVideo(media); self.flash.active = true; } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.show(); } self.status.video = true; } else { if(isHtml) { self.html.audio.gate = true; self._html_setAudio(media); self.html.active = true; // Setup the Android Fix - Only for HTML audio. if($.jPlayer.platform.android) { self.androidFix.setMedia = true; } } else { self.flash.gate = true; self._flash_setAudio(media); self.flash.active = true; } if(self.css.jq.videoPlay.length) { self.css.jq.videoPlay.hide(); } self.status.video = false; } supported = true; return false; // Exit $.each } }); if(supported) { return false; // Exit $.each } }); if(supported) { if(!(this.status.nativeVideoControls && this.html.video.gate)) { // Set poster IMG if native video controls are not being used // Note: With IE the IMG onload event occurs immediately when cached. // Note: Poster hidden by default in _resetMedia() if(this._validString(media.poster)) { if(posterChanged) { // Since some browsers do not generate img onload event. this.htmlElement.poster.src = media.poster; } else { this.internal.poster.jq.show(); } } } if(this.css.jq.title.length) { if(typeof media.title === 'string') { this.css.jq.title.html(media.title); if(this.htmlElement.audio) { this.htmlElement.audio.setAttribute('title', media.title); } if(this.htmlElement.video) { this.htmlElement.video.setAttribute('title', media.title); } } } this.status.srcSet = true; this.status.media = $.extend({}, media); this._updateButtons(false); this._updateInterface(); this._trigger($.jPlayer.event.setmedia); } else { // jPlayer cannot support any formats provided in this browser // Send an error event this._error( { type: $.jPlayer.error.NO_SUPPORT, context: "{supplied:'" + this.options.supplied + "'}", message: $.jPlayer.errorMsg.NO_SUPPORT, hint: $.jPlayer.errorHint.NO_SUPPORT }); } }, _resetMedia: function() { this._resetStatus(); this._updateButtons(false); this._updateInterface(); this._seeked(); this.internal.poster.jq.hide(); clearTimeout(this.internal.htmlDlyCmdId); if(this.html.active) { this._html_resetMedia(); } else if(this.flash.active) { this._flash_resetMedia(); } }, clearMedia: function() { this._resetMedia(); if(this.html.active) { this._html_clearMedia(); } else if(this.flash.active) { this._flash_clearMedia(); } this._resetGate(); this._resetActive(); }, load: function() { if(this.status.srcSet) { if(this.html.active) { this._html_load(); } else if(this.flash.active) { this._flash_load(); } } else { this._urlNotSetError("load"); } }, focus: function() { if(this.options.keyEnabled) { $.jPlayer.focus = this; } }, play: function(time) { time = (typeof time === "number") ? time : NaN; // Remove jQuery event from click handler if(this.status.srcSet) { this.focus(); if(this.html.active) { this._html_play(time); } else if(this.flash.active) { this._flash_play(time); } } else { this._urlNotSetError("play"); } }, videoPlay: function() { // Handles clicks on the play button over the video poster this.play(); }, pause: function(time) { time = (typeof time === "number") ? time : NaN; // Remove jQuery event from click handler if(this.status.srcSet) { if(this.html.active) { this._html_pause(time); } else if(this.flash.active) { this._flash_pause(time); } } else { this._urlNotSetError("pause"); } }, tellOthers: function(command, conditions) { var self = this, hasConditions = typeof conditions === 'function', args = Array.prototype.slice.call(arguments); // Convert arguments to an Array. if(typeof command !== 'string') { // Ignore, since no command. return; // Return undefined to maintain chaining. } if(hasConditions) { args.splice(1, 1); // Remove the conditions from the arguments } $.each(this.instances, function() { // Remember that "this" is the instance's "element" in the $.each() loop. if(self.element !== this) { // Do not tell my instance. if(!hasConditions || conditions.call(this.data("jPlayer"), self)) { this.jPlayer.apply(this, args); } } }); }, pauseOthers: function(time) { this.tellOthers("pause", function() { // In the conditions function, the "this" context is the other instance's jPlayer object. return this.status.srcSet; }, time); }, stop: function() { if(this.status.srcSet) { if(this.html.active) { this._html_pause(0); } else if(this.flash.active) { this._flash_pause(0); } } else { this._urlNotSetError("stop"); } }, playHead: function(p) { p = this._limitValue(p, 0, 100); if(this.status.srcSet) { if(this.html.active) { this._html_playHead(p); } else if(this.flash.active) { this._flash_playHead(p); } } else { this._urlNotSetError("playHead"); } }, _muted: function(muted) { this.mutedWorker(muted); if(this.options.globalVolume) { this.tellOthers("mutedWorker", function() { // Check the other instance has global volume enabled. return this.options.globalVolume; }, muted); } }, mutedWorker: function(muted) { this.options.muted = muted; if(this.html.used) { this._html_setProperty('muted', muted); } if(this.flash.used) { this._flash_mute(muted); } // The HTML solution generates this event from the media element itself. if(!this.html.video.gate && !this.html.audio.gate) { this._updateMute(muted); this._updateVolume(this.options.volume); this._trigger($.jPlayer.event.volumechange); } }, mute: function(mute) { // mute is either: undefined (true), an event object (true) or a boolean (muted). mute = mute === undefined ? true : !!mute; this._muted(mute); }, unmute: function(unmute) { // unmute is either: undefined (true), an event object (true) or a boolean (!muted). unmute = unmute === undefined ? true : !!unmute; this._muted(!unmute); }, _updateMute: function(mute) { if(mute === undefined) { mute = this.options.muted; } if(this.css.jq.mute.length && this.css.jq.unmute.length) { if(this.status.noVolume) { this.css.jq.mute.hide(); this.css.jq.unmute.hide(); } else if(mute) { this.css.jq.mute.hide(); this.css.jq.unmute.show(); } else { this.css.jq.mute.show(); this.css.jq.unmute.hide(); } } }, volume: function(v) { this.volumeWorker(v); if(this.options.globalVolume) { this.tellOthers("volumeWorker", function() { // Check the other instance has global volume enabled. return this.options.globalVolume; }, v); } }, volumeWorker: function(v) { v = this._limitValue(v, 0, 1); this.options.volume = v; if(this.html.used) { this._html_setProperty('volume', v); } if(this.flash.used) { this._flash_volume(v); } // The HTML solution generates this event from the media element itself. if(!this.html.video.gate && !this.html.audio.gate) { this._updateVolume(v); this._trigger($.jPlayer.event.volumechange); } }, volumeBar: function(e) { // Handles clicks on the volumeBar if(this.css.jq.volumeBar.length) { // Using $(e.currentTarget) to enable multiple volume bars var $bar = $(e.currentTarget), offset = $bar.offset(), x = e.pageX - offset.left, w = $bar.width(), y = $bar.height() - e.pageY + offset.top, h = $bar.height(); if(this.options.verticalVolume) { this.volume(y/h); } else { this.volume(x/w); } } if(this.options.muted) { this._muted(false); } }, _updateVolume: function(v) { if(v === undefined) { v = this.options.volume; } v = this.options.muted ? 0 : v; if(this.status.noVolume) { if(this.css.jq.volumeBar.length) { this.css.jq.volumeBar.hide(); } if(this.css.jq.volumeBarValue.length) { this.css.jq.volumeBarValue.hide(); } if(this.css.jq.volumeMax.length) { this.css.jq.volumeMax.hide(); } } else { if(this.css.jq.volumeBar.length) { this.css.jq.volumeBar.show(); } if(this.css.jq.volumeBarValue.length) { this.css.jq.volumeBarValue.show(); this.css.jq.volumeBarValue[this.options.verticalVolume ? "height" : "width"]((v*100)+"%"); } if(this.css.jq.volumeMax.length) { this.css.jq.volumeMax.show(); } } }, volumeMax: function() { // Handles clicks on the volume max this.volume(1); if(this.options.muted) { this._muted(false); } }, _cssSelectorAncestor: function(ancestor) { var self = this; this.options.cssSelectorAncestor = ancestor; this._removeUiClass(); this.ancestorJq = ancestor ? $(ancestor) : []; // Would use $() instead of [], but it is only 1.4+ if(ancestor && this.ancestorJq.length !== 1) { // So empty strings do not generate the warning. this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_COUNT, context: ancestor, message: $.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.ancestorJq.length + " found for cssSelectorAncestor.", hint: $.jPlayer.warningHint.CSS_SELECTOR_COUNT }); } this._addUiClass(); $.each(this.options.cssSelector, function(fn, cssSel) { self._cssSelector(fn, cssSel); }); // Set the GUI to the current state. this._updateInterface(); this._updateButtons(); this._updateAutohide(); this._updateVolume(); this._updateMute(); }, _cssSelector: function(fn, cssSel) { var self = this; if(typeof cssSel === 'string') { if($.jPlayer.prototype.options.cssSelector[fn]) { if(this.css.jq[fn] && this.css.jq[fn].length) { this.css.jq[fn].unbind(".jPlayer"); } this.options.cssSelector[fn] = cssSel; this.css.cs[fn] = this.options.cssSelectorAncestor + " " + cssSel; if(cssSel) { // Checks for empty string this.css.jq[fn] = $(this.css.cs[fn]); } else { this.css.jq[fn] = []; // To comply with the css.jq[fn].length check before its use. As of jQuery 1.4 could have used $() for an empty set. } if(this.css.jq[fn].length && this[fn]) { var handler = function(e) { e.preventDefault(); self[fn](e); $(this).blur(); }; this.css.jq[fn].bind("click.jPlayer", handler); // Using jPlayer namespace } if(cssSel && this.css.jq[fn].length !== 1) { // So empty strings do not generate the warning. ie., they just remove the old one. this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_COUNT, context: this.css.cs[fn], message: $.jPlayer.warningMsg.CSS_SELECTOR_COUNT + this.css.jq[fn].length + " found for " + fn + " method.", hint: $.jPlayer.warningHint.CSS_SELECTOR_COUNT }); } } else { this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_METHOD, context: fn, message: $.jPlayer.warningMsg.CSS_SELECTOR_METHOD, hint: $.jPlayer.warningHint.CSS_SELECTOR_METHOD }); } } else { this._warning( { type: $.jPlayer.warning.CSS_SELECTOR_STRING, context: cssSel, message: $.jPlayer.warningMsg.CSS_SELECTOR_STRING, hint: $.jPlayer.warningHint.CSS_SELECTOR_STRING }); } }, duration: function(e) { if(this.options.toggleDuration) { if(this.options.captureDuration) { e.stopPropagation(); } this._setOption("remainingDuration", !this.options.remainingDuration); } }, seekBar: function(e) { // Handles clicks on the seekBar if(this.css.jq.seekBar.length) { // Using $(e.currentTarget) to enable multiple seek bars var $bar = $(e.currentTarget), offset = $bar.offset(), x = e.pageX - offset.left, w = $bar.width(), p = 100 * x / w; this.playHead(p); } }, playbackRate: function(pbr) { this._setOption("playbackRate", pbr); }, playbackRateBar: function(e) { // Handles clicks on the playbackRateBar if(this.css.jq.playbackRateBar.length) { // Using $(e.currentTarget) to enable multiple playbackRate bars var $bar = $(e.currentTarget), offset = $bar.offset(), x = e.pageX - offset.left, w = $bar.width(), y = $bar.height() - e.pageY + offset.top, h = $bar.height(), ratio, pbr; if(this.options.verticalPlaybackRate) { ratio = y/h; } else { ratio = x/w; } pbr = ratio * (this.options.maxPlaybackRate - this.options.minPlaybackRate) + this.options.minPlaybackRate; this.playbackRate(pbr); } }, _updatePlaybackRate: function() { var pbr = this.options.playbackRate, ratio = (pbr - this.options.minPlaybackRate) / (this.options.maxPlaybackRate - this.options.minPlaybackRate); if(this.status.playbackRateEnabled) { if(this.css.jq.playbackRateBar.length) { this.css.jq.playbackRateBar.show(); } if(this.css.jq.playbackRateBarValue.length) { this.css.jq.playbackRateBarValue.show(); this.css.jq.playbackRateBarValue[this.options.verticalPlaybackRate ? "height" : "width"]((ratio*100)+"%"); } } else { if(this.css.jq.playbackRateBar.length) { this.css.jq.playbackRateBar.hide(); } if(this.css.jq.playbackRateBarValue.length) { this.css.jq.playbackRateBarValue.hide(); } } }, repeat: function() { // Handle clicks on the repeat button this._loop(true); }, repeatOff: function() { // Handle clicks on the repeatOff button this._loop(false); }, _loop: function(loop) { if(this.options.loop !== loop) { this.options.loop = loop; this._updateButtons(); this._trigger($.jPlayer.event.repeat); } }, // Options code adapted from ui.widget.js (1.8.7). Made changes so the key can use dot notation. To match previous getData solution in jPlayer 1. option: function(key, value) { var options = key; // Enables use: options(). Returns a copy of options object if ( arguments.length === 0 ) { return $.extend( true, {}, this.options ); } if(typeof key === "string") { var keys = key.split("."); // Enables use: options("someOption") Returns a copy of the option. Supports dot notation. if(value === undefined) { var opt = $.extend(true, {}, this.options); for(var i = 0; i < keys.length; i++) { if(opt[keys[i]] !== undefined) { opt = opt[keys[i]]; } else { this._warning( { type: $.jPlayer.warning.OPTION_KEY, context: key, message: $.jPlayer.warningMsg.OPTION_KEY, hint: $.jPlayer.warningHint.OPTION_KEY }); return undefined; } } return opt; } // Enables use: options("someOptionObject", someObject}). Creates: {someOptionObject:someObject} // Enables use: options("someOption", someValue). Creates: {someOption:someValue} // Enables use: options("someOptionObject.someOption", someValue). Creates: {someOptionObject:{someOption:someValue}} options = {}; var opts = options; for(var j = 0; j < keys.length; j++) { if(j < keys.length - 1) { opts[keys[j]] = {}; opts = opts[keys[j]]; } else { opts[keys[j]] = value; } } } // Otherwise enables use: options(optionObject). Uses original object (the key) this._setOptions(options); return this; }, _setOptions: function(options) { var self = this; $.each(options, function(key, value) { // This supports the 2 level depth that the options of jPlayer has. Would review if we ever need more depth. self._setOption(key, value); }); return this; }, _setOption: function(key, value) { var self = this; // The ability to set options is limited at this time. switch(key) { case "volume" : this.volume(value); break; case "muted" : this._muted(value); break; case "globalVolume" : this.options[key] = value; break; case "cssSelectorAncestor" : this._cssSelectorAncestor(value); // Set and refresh all associations for the new ancestor. break; case "cssSelector" : $.each(value, function(fn, cssSel) { self._cssSelector(fn, cssSel); // NB: The option is set inside this function, after further validity checks. }); break; case "playbackRate" : this.options[key] = value = this._limitValue(value, this.options.minPlaybackRate, this.options.maxPlaybackRate); if(this.html.used) { this._html_setProperty('playbackRate', value); } this._updatePlaybackRate(); break; case "defaultPlaybackRate" : this.options[key] = value = this._limitValue(value, this.options.minPlaybackRate, this.options.maxPlaybackRate); if(this.html.used) { this._html_setProperty('defaultPlaybackRate', value); } this._updatePlaybackRate(); break; case "minPlaybackRate" : this.options[key] = value = this._limitValue(value, 0.1, this.options.maxPlaybackRate - 0.1); this._updatePlaybackRate(); break; case "maxPlaybackRate" : this.options[key] = value = this._limitValue(value, this.options.minPlaybackRate + 0.1, 16); this._updatePlaybackRate(); break; case "fullScreen" : if(this.options[key] !== value) { // if changed var wkv = $.jPlayer.nativeFeatures.fullscreen.used.webkitVideo; if(!wkv || wkv && !this.status.waitForPlay) { if(!wkv) { // No sensible way to unset option on these devices. this.options[key] = value; } if(value) { this._requestFullscreen(); } else { this._exitFullscreen(); } if(!wkv) { this._setOption("fullWindow", value); } } } break; case "fullWindow" : if(this.options[key] !== value) { // if changed this._removeUiClass(); this.options[key] = value; this._refreshSize(); } break; case "size" : if(!this.options.fullWindow && this.options[key].cssClass !== value.cssClass) { this._removeUiClass(); } this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this._refreshSize(); break; case "sizeFull" : if(this.options.fullWindow && this.options[key].cssClass !== value.cssClass) { this._removeUiClass(); } this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this._refreshSize(); break; case "autohide" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this._updateAutohide(); break; case "loop" : this._loop(value); break; case "remainingDuration" : this.options[key] = value; this._updateInterface(); break; case "toggleDuration" : this.options[key] = value; break; case "nativeVideoControls" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); this._restrictNativeVideoControls(); this._updateNativeVideoControls(); break; case "noFullWindow" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); // Need to check again as noFullWindow can depend on this flag and the restrict() can override it. this.status.noFullWindow = this._uaBlocklist(this.options.noFullWindow); this._restrictNativeVideoControls(); this._updateButtons(); break; case "noVolume" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. this.status.noVolume = this._uaBlocklist(this.options.noVolume); this._updateVolume(); this._updateMute(); break; case "emulateHtml" : if(this.options[key] !== value) { // To avoid multiple event handlers being created, if true already. this.options[key] = value; if(value) { this._emulateHtmlBridge(); } else { this._destroyHtmlBridge(); } } break; case "timeFormat" : this.options[key] = $.extend({}, this.options[key], value); // store a merged copy of it, incase not all properties changed. break; case "keyEnabled" : this.options[key] = value; if(!value && this === $.jPlayer.focus) { $.jPlayer.focus = null; } break; case "keyBindings" : this.options[key] = $.extend(true, {}, this.options[key], value); // store a merged DEEP copy of it, incase not all properties changed. break; case "audioFullScreen" : this.options[key] = value; break; } return this; }, // End of: (Options code adapted from ui.widget.js) _refreshSize: function() { this._setSize(); // update status and jPlayer element size this._addUiClass(); // update the ui class this._updateSize(); // update internal sizes this._updateButtons(); this._updateAutohide(); this._trigger($.jPlayer.event.resize); }, _setSize: function() { // Determine the current size from the options if(this.options.fullWindow) { this.status.width = this.options.sizeFull.width; this.status.height = this.options.sizeFull.height; this.status.cssClass = this.options.sizeFull.cssClass; } else { this.status.width = this.options.size.width; this.status.height = this.options.size.height; this.status.cssClass = this.options.size.cssClass; } // Set the size of the jPlayer area. this.element.css({'width': this.status.width, 'height': this.status.height}); }, _addUiClass: function() { if(this.ancestorJq.length) { this.ancestorJq.addClass(this.status.cssClass); } }, _removeUiClass: function() { if(this.ancestorJq.length) { this.ancestorJq.removeClass(this.status.cssClass); } }, _updateSize: function() { // The poster uses show/hide so can simply resize it. this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height}); // Video html or flash resized if necessary at this time, or if native video controls being used. if(!this.status.waitForPlay && this.html.active && this.status.video || this.html.video.available && this.html.used && this.status.nativeVideoControls) { this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else if(!this.status.waitForPlay && this.flash.active && this.status.video) { this.internal.flash.jq.css({'width': this.status.width, 'height': this.status.height}); } }, _updateAutohide: function() { var self = this, event = "mousemove.jPlayer", namespace = ".jPlayerAutohide", eventType = event + namespace, handler = function() { self.css.jq.gui.fadeIn(self.options.autohide.fadeIn, function() { clearTimeout(self.internal.autohideId); self.internal.autohideId = setTimeout( function() { self.css.jq.gui.fadeOut(self.options.autohide.fadeOut); }, self.options.autohide.hold); }); }; if(this.css.jq.gui.length) { // End animations first so that its callback is executed now. // Otherwise an in progress fadeIn animation still has the callback to fadeOut again. this.css.jq.gui.stop(true, true); // Removes the fadeOut operation from the fadeIn callback. clearTimeout(this.internal.autohideId); this.element.unbind(namespace); this.css.jq.gui.unbind(namespace); if(!this.status.nativeVideoControls) { if(this.options.fullWindow && this.options.autohide.full || !this.options.fullWindow && this.options.autohide.restored) { this.element.bind(eventType, handler); this.css.jq.gui.bind(eventType, handler); this.css.jq.gui.hide(); } else { this.css.jq.gui.show(); } } else { this.css.jq.gui.hide(); } } }, fullScreen: function() { this._setOption("fullScreen", true); }, restoreScreen: function() { this._setOption("fullScreen", false); }, _fullscreenAddEventListeners: function() { var self = this, fs = $.jPlayer.nativeFeatures.fullscreen; if(fs.api.fullscreenEnabled) { if(fs.event.fullscreenchange) { // Create the event handler function and store it for removal. if(typeof this.internal.fullscreenchangeHandler !== 'function') { this.internal.fullscreenchangeHandler = function() { self._fullscreenchange(); }; } document.addEventListener(fs.event.fullscreenchange, this.internal.fullscreenchangeHandler, false); } // No point creating handler for fullscreenerror. // Either logic avoids fullscreen occurring (w3c/moz), or their is no event on the browser (webkit). } }, _fullscreenRemoveEventListeners: function() { var fs = $.jPlayer.nativeFeatures.fullscreen; if(this.internal.fullscreenchangeHandler) { document.removeEventListener(fs.event.fullscreenchange, this.internal.fullscreenchangeHandler, false); } }, _fullscreenchange: function() { // If nothing is fullscreen, then we cannot be in fullscreen mode. if(this.options.fullScreen && !$.jPlayer.nativeFeatures.fullscreen.api.fullscreenElement()) { this._setOption("fullScreen", false); } }, _requestFullscreen: function() { // Either the container or the jPlayer div var e = this.ancestorJq.length ? this.ancestorJq[0] : this.element[0], fs = $.jPlayer.nativeFeatures.fullscreen; // This method needs the video element. For iOS and Android. if(fs.used.webkitVideo) { e = this.htmlElement.video; } if(fs.api.fullscreenEnabled) { fs.api.requestFullscreen(e); } }, _exitFullscreen: function() { var fs = $.jPlayer.nativeFeatures.fullscreen, e; // This method needs the video element. For iOS and Android. if(fs.used.webkitVideo) { e = this.htmlElement.video; } if(fs.api.fullscreenEnabled) { fs.api.exitFullscreen(e); } }, _html_initMedia: function(media) { // Remove any existing track elements var $media = $(this.htmlElement.media).empty(); // Create any track elements given with the media, as an Array of track Objects. $.each(media.track || [], function(i,v) { var track = document.createElement('track'); track.setAttribute("kind", v.kind ? v.kind : ""); track.setAttribute("src", v.src ? v.src : ""); track.setAttribute("srclang", v.srclang ? v.srclang : ""); track.setAttribute("label", v.label ? v.label : ""); if(v.def) { track.setAttribute("default", v.def); } $media.append(track); }); this.htmlElement.media.src = this.status.src; if(this.options.preload !== 'none') { this._html_load(); // See function for comments } this._trigger($.jPlayer.event.timeupdate); // The flash generates this event for its solution. }, _html_setFormat: function(media) { var self = this; // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.html.support[format] && media[format]) { self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); }, _html_setAudio: function(media) { this._html_setFormat(media); this.htmlElement.media = this.htmlElement.audio; this._html_initMedia(media); }, _html_setVideo: function(media) { this._html_setFormat(media); if(this.status.nativeVideoControls) { this.htmlElement.video.poster = this._validString(media.poster) ? media.poster : ""; } this.htmlElement.media = this.htmlElement.video; this._html_initMedia(media); }, _html_resetMedia: function() { if(this.htmlElement.media) { if(this.htmlElement.media.id === this.internal.video.id && !this.status.nativeVideoControls) { this.internal.video.jq.css({'width':'0px', 'height':'0px'}); } this.htmlElement.media.pause(); } }, _html_clearMedia: function() { if(this.htmlElement.media) { this.htmlElement.media.src = "about:blank"; // The following load() is only required for Firefox 3.6 (PowerMacs). // Recent HTMl5 browsers only require the src change. Due to changes in W3C spec and load() effect. this.htmlElement.media.load(); // Stops an old, "in progress" download from continuing the download. Triggers the loadstart, error and emptied events, due to the empty src. Also an abort event if a download was in progress. } }, _html_load: function() { // This function remains to allow the early HTML5 browsers to work, such as Firefox 3.6 // A change in the W3C spec for the media.load() command means that this is no longer necessary. // This command should be removed and actually causes minor undesirable effects on some browsers. Such as loading the whole file and not only the metadata. if(this.status.waitForLoad) { this.status.waitForLoad = false; this.htmlElement.media.load(); } clearTimeout(this.internal.htmlDlyCmdId); }, _html_play: function(time) { var self = this, media = this.htmlElement.media; this.androidFix.pause = false; // Cancel the pause fix. this._html_load(); // Loads if required and clears any delayed commands. // Setup the Android Fix. if(this.androidFix.setMedia) { this.androidFix.play = true; this.androidFix.time = time; } else if(!isNaN(time)) { // Attempt to play it, since iOS has been ignoring commands if(this.internal.cmdsIgnored) { media.play(); } try { // !media.seekable is for old HTML5 browsers, like Firefox 3.6. // Checking seekable.length is important for iOS6 to work with setMedia().play(time) if(!media.seekable || typeof media.seekable === "object" && media.seekable.length > 0) { media.currentTime = time; media.play(); } else { throw 1; } } catch(err) { this.internal.htmlDlyCmdId = setTimeout(function() { self.play(time); }, 250); return; // Cancel execution and wait for the delayed command. } } else { media.play(); } this._html_checkWaitForPlay(); }, _html_pause: function(time) { var self = this, media = this.htmlElement.media; this.androidFix.play = false; // Cancel the play fix. if(time > 0) { // We do not want the stop() command, which does pause(0), causing a load operation. this._html_load(); // Loads if required and clears any delayed commands. } else { clearTimeout(this.internal.htmlDlyCmdId); } // Order of these commands is important for Safari (Win) and IE9. Pause then change currentTime. media.pause(); // Setup the Android Fix. if(this.androidFix.setMedia) { this.androidFix.pause = true; this.androidFix.time = time; } else if(!isNaN(time)) { try { if(!media.seekable || typeof media.seekable === "object" && media.seekable.length > 0) { media.currentTime = time; } else { throw 1; } } catch(err) { this.internal.htmlDlyCmdId = setTimeout(function() { self.pause(time); }, 250); return; // Cancel execution and wait for the delayed command. } } if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button. this._html_checkWaitForPlay(); } }, _html_playHead: function(percent) { var self = this, media = this.htmlElement.media; this._html_load(); // Loads if required and clears any delayed commands. // This playHead() method needs a refactor to apply the android fix. try { if(typeof media.seekable === "object" && media.seekable.length > 0) { media.currentTime = percent * media.seekable.end(media.seekable.length-1) / 100; } else if(media.duration > 0 && !isNaN(media.duration)) { media.currentTime = percent * media.duration / 100; } else { throw "e"; } } catch(err) { this.internal.htmlDlyCmdId = setTimeout(function() { self.playHead(percent); }, 250); return; // Cancel execution and wait for the delayed command. } if(!this.status.waitForLoad) { this._html_checkWaitForPlay(); } }, _html_checkWaitForPlay: function() { if(this.status.waitForPlay) { this.status.waitForPlay = false; if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } if(this.status.video) { this.internal.poster.jq.hide(); this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } } }, _html_setProperty: function(property, value) { if(this.html.audio.available) { this.htmlElement.audio[property] = value; } if(this.html.video.available) { this.htmlElement.video[property] = value; } }, _flash_setAudio: function(media) { var self = this; try { // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.flash.support[format] && media[format]) { switch (format) { case "m4a" : case "fla" : self._getMovie().fl_setAudio_m4a(media[format]); break; case "mp3" : self._getMovie().fl_setAudio_mp3(media[format]); break; case "rtmpa": self._getMovie().fl_setAudio_rtmp(media[format]); break; } self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); if(this.options.preload === 'auto') { this._flash_load(); this.status.waitForLoad = false; } } catch(err) { this._flashError(err); } }, _flash_setVideo: function(media) { var self = this; try { // Always finds a format due to checks in setMedia() $.each(this.formats, function(priority, format) { if(self.flash.support[format] && media[format]) { switch (format) { case "m4v" : case "flv" : self._getMovie().fl_setVideo_m4v(media[format]); break; case "rtmpv": self._getMovie().fl_setVideo_rtmp(media[format]); break; } self.status.src = media[format]; self.status.format[format] = true; self.status.formatType = format; return false; } }); if(this.options.preload === 'auto') { this._flash_load(); this.status.waitForLoad = false; } } catch(err) { this._flashError(err); } }, _flash_resetMedia: function() { this.internal.flash.jq.css({'width':'0px', 'height':'0px'}); // Must do via CSS as setting attr() to zero causes a jQuery error in IE. this._flash_pause(NaN); }, _flash_clearMedia: function() { try { this._getMovie().fl_clearMedia(); } catch(err) { this._flashError(err); } }, _flash_load: function() { try { this._getMovie().fl_load(); } catch(err) { this._flashError(err); } this.status.waitForLoad = false; }, _flash_play: function(time) { try { this._getMovie().fl_play(time); } catch(err) { this._flashError(err); } this.status.waitForLoad = false; this._flash_checkWaitForPlay(); }, _flash_pause: function(time) { try { this._getMovie().fl_pause(time); } catch(err) { this._flashError(err); } if(time > 0) { // Avoids a setMedia() followed by stop() or pause(0) hiding the video play button. this.status.waitForLoad = false; this._flash_checkWaitForPlay(); } }, _flash_playHead: function(p) { try { this._getMovie().fl_play_head(p); } catch(err) { this._flashError(err); } if(!this.status.waitForLoad) { this._flash_checkWaitForPlay(); } }, _flash_checkWaitForPlay: function() { if(this.status.waitForPlay) { this.status.waitForPlay = false; if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } if(this.status.video) { this.internal.poster.jq.hide(); this.internal.flash.jq.css({'width': this.status.width, 'height': this.status.height}); } } }, _flash_volume: function(v) { try { this._getMovie().fl_volume(v); } catch(err) { this._flashError(err); } }, _flash_mute: function(m) { try { this._getMovie().fl_mute(m); } catch(err) { this._flashError(err); } }, _getMovie: function() { return document[this.internal.flash.id]; }, _getFlashPluginVersion: function() { // _getFlashPluginVersion() code influenced by: // - FlashReplace 1.01: http://code.google.com/p/flashreplace/ // - SWFObject 2.2: http://code.google.com/p/swfobject/ var version = 0, flash; if(window.ActiveXObject) { try { flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); if (flash) { // flash will return null when ActiveX is disabled var v = flash.GetVariable("$version"); if(v) { v = v.split(" ")[1].split(","); version = parseInt(v[0], 10) + "." + parseInt(v[1], 10); } } } catch(e) {} } else if(navigator.plugins && navigator.mimeTypes.length > 0) { flash = navigator.plugins["Shockwave Flash"]; if(flash) { version = navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/, "$1"); } } return version * 1; // Converts to a number }, _checkForFlash: function (version) { var flashOk = false; if(this._getFlashPluginVersion() >= version) { flashOk = true; } return flashOk; }, _validString: function(url) { return (url && typeof url === "string"); // Empty strings return false }, _limitValue: function(value, min, max) { return (value < min) ? min : ((value > max) ? max : value); }, _urlNotSetError: function(context) { this._error( { type: $.jPlayer.error.URL_NOT_SET, context: context, message: $.jPlayer.errorMsg.URL_NOT_SET, hint: $.jPlayer.errorHint.URL_NOT_SET }); }, _flashError: function(error) { var errorType; if(!this.internal.ready) { errorType = "FLASH"; } else { errorType = "FLASH_DISABLED"; } this._error( { type: $.jPlayer.error[errorType], context: this.internal.flash.swf, message: $.jPlayer.errorMsg[errorType] + error.message, hint: $.jPlayer.errorHint[errorType] }); // Allow the audio player to recover if display:none and then shown again, or with position:fixed on Firefox. // This really only affects audio in a media player, as an audio player could easily move the jPlayer element away from such issues. this.internal.flash.jq.css({'width':'1px', 'height':'1px'}); }, _error: function(error) { this._trigger($.jPlayer.event.error, error); if(this.options.errorAlerts) { this._alert("Error!" + (error.message ? "\n" + error.message : "") + (error.hint ? "\n" + error.hint : "") + "\nContext: " + error.context); } }, _warning: function(warning) { this._trigger($.jPlayer.event.warning, undefined, warning); if(this.options.warningAlerts) { this._alert("Warning!" + (warning.message ? "\n" + warning.message : "") + (warning.hint ? "\n" + warning.hint : "") + "\nContext: " + warning.context); } }, _alert: function(message) { var msg = "jPlayer " + this.version.script + " : id='" + this.internal.self.id +"' : " + message; if(!this.options.consoleAlerts) { alert(msg); } else if(window.console && window.console.log) { window.console.log(msg); } }, _emulateHtmlBridge: function() { var self = this; // Emulate methods on jPlayer's DOM element. $.each( $.jPlayer.emulateMethods.split(/\s+/g), function(i, name) { self.internal.domNode[name] = function(arg) { self[name](arg); }; }); // Bubble jPlayer events to its DOM element. $.each($.jPlayer.event, function(eventName,eventType) { var nativeEvent = true; $.each( $.jPlayer.reservedEvent.split(/\s+/g), function(i, name) { if(name === eventName) { nativeEvent = false; return false; } }); if(nativeEvent) { self.element.bind(eventType + ".jPlayer.jPlayerHtml", function() { // With .jPlayer & .jPlayerHtml namespaces. self._emulateHtmlUpdate(); var domEvent = document.createEvent("Event"); domEvent.initEvent(eventName, false, true); self.internal.domNode.dispatchEvent(domEvent); }); } // The error event would require a special case }); // IE9 has a readyState property on all elements. The document should have it, but all (except media) elements inherit it in IE9. This conflicts with Popcorn, which polls the readyState. }, _emulateHtmlUpdate: function() { var self = this; $.each( $.jPlayer.emulateStatus.split(/\s+/g), function(i, name) { self.internal.domNode[name] = self.status[name]; }); $.each( $.jPlayer.emulateOptions.split(/\s+/g), function(i, name) { self.internal.domNode[name] = self.options[name]; }); }, _destroyHtmlBridge: function() { var self = this; // Bridge event handlers are also removed by destroy() through .jPlayer namespace. this.element.unbind(".jPlayerHtml"); // Remove all event handlers created by the jPlayer bridge. So you can change the emulateHtml option. // Remove the methods and properties var emulated = $.jPlayer.emulateMethods + " " + $.jPlayer.emulateStatus + " " + $.jPlayer.emulateOptions; $.each( emulated.split(/\s+/g), function(i, name) { delete self.internal.domNode[name]; }); } }; $.jPlayer.error = { FLASH: "e_flash", FLASH_DISABLED: "e_flash_disabled", NO_SOLUTION: "e_no_solution", NO_SUPPORT: "e_no_support", URL: "e_url", URL_NOT_SET: "e_url_not_set", VERSION: "e_version" }; $.jPlayer.errorMsg = { FLASH: "jPlayer's Flash fallback is not configured correctly, or a command was issued before the jPlayer Ready event. Details: ", // Used in: _flashError() FLASH_DISABLED: "jPlayer's Flash fallback has been disabled by the browser due to the CSS rules you have used. Details: ", // Used in: _flashError() NO_SOLUTION: "No solution can be found by jPlayer in this browser. Neither HTML nor Flash can be used.", // Used in: _init() NO_SUPPORT: "It is not possible to play any media format provided in setMedia() on this browser using your current options.", // Used in: setMedia() URL: "Media URL could not be loaded.", // Used in: jPlayerFlashEvent() and _addHtmlEventListeners() URL_NOT_SET: "Attempt to issue media playback commands, while no media url is set.", // Used in: load(), play(), pause(), stop() and playHead() VERSION: "jPlayer " + $.jPlayer.prototype.version.script + " needs Jplayer.swf version " + $.jPlayer.prototype.version.needFlash + " but found " // Used in: jPlayerReady() }; $.jPlayer.errorHint = { FLASH: "Check your swfPath option and that Jplayer.swf is there.", FLASH_DISABLED: "Check that you have not display:none; the jPlayer entity or any ancestor.", NO_SOLUTION: "Review the jPlayer options: support and supplied.", NO_SUPPORT: "Video or audio formats defined in the supplied option are missing.", URL: "Check media URL is valid.", URL_NOT_SET: "Use setMedia() to set the media URL.", VERSION: "Update jPlayer files." }; $.jPlayer.warning = { CSS_SELECTOR_COUNT: "e_css_selector_count", CSS_SELECTOR_METHOD: "e_css_selector_method", CSS_SELECTOR_STRING: "e_css_selector_string", OPTION_KEY: "e_option_key" }; $.jPlayer.warningMsg = { CSS_SELECTOR_COUNT: "The number of css selectors found did not equal one: ", CSS_SELECTOR_METHOD: "The methodName given in jPlayer('cssSelector') is not a valid jPlayer method.", CSS_SELECTOR_STRING: "The methodCssSelector given in jPlayer('cssSelector') is not a String or is empty.", OPTION_KEY: "The option requested in jPlayer('option') is undefined." }; $.jPlayer.warningHint = { CSS_SELECTOR_COUNT: "Check your css selector and the ancestor.", CSS_SELECTOR_METHOD: "Check your method name.", CSS_SELECTOR_STRING: "Check your css selector is a string.", OPTION_KEY: "Check your option name." }; })); /* * jQuery Hotkeys Plugin * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * * Based upon the plugin by Tzury Bar Yochay: * http://github.com/tzuryby/hotkeys * * Original idea by: * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/ */ (function(jQuery){ jQuery.hotkeys = { version: "0.8", specialKeys: { 8: "backspace", 9: "tab", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 191: "/", 224: "meta" }, shiftNums: { "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<", ".": ">", "/": "?", "\\": "|" } }; function keyHandler( handleObj ) { // Only care when a possible input has been specified if ( typeof handleObj.data !== "string" ) { return; } var origHandler = handleObj.handler, keys = handleObj.data.toLowerCase().split(" "); handleObj.handler = function( event ) { // Don't fire in text-accepting inputs that we didn't directly bind to if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) || event.target.type === "text") ) { return; } // Keypress represents characters, not special keys var special = event.type !== "keypress" && jQuery.hotkeys.specialKeys[ event.which ], character = String.fromCharCode( event.which ).toLowerCase(), key, modif = "", possible = {}; // check combinations (alt|ctrl|shift+anything) if ( event.altKey && special !== "alt" ) { modif += "alt+"; } if ( event.ctrlKey && special !== "ctrl" ) { modif += "ctrl+"; } // TODO: Need to make sure this works consistently across platforms if ( event.metaKey && !event.ctrlKey && special !== "meta" ) { modif += "meta+"; } if ( event.shiftKey && special !== "shift" ) { modif += "shift+"; } if ( special ) { possible[ modif + special ] = true; } else { possible[ modif + character ] = true; possible[ modif + jQuery.hotkeys.shiftNums[ character ] ] = true; // "$" can be triggered as "Shift+4" or "Shift+$" or just "$" if ( modif === "shift+" ) { possible[ jQuery.hotkeys.shiftNums[ character ] ] = true; } } for ( var i = 0, l = keys.length; i < l; i++ ) { if ( possible[ keys[i] ] ) { return origHandler.apply( this, arguments ); } } }; } jQuery.each([ "keydown", "keyup", "keypress" ], function() { jQuery.event.special[ this ] = { add: keyHandler }; }); })( jQuery ); !function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b():a.way=b()}(this,function(){"use strict";var a,b,c="way",d=function(){this._watchers={},this._watchersAll={}};d.prototype.constructor=d,d.prototype.watchAll=function(a){this._watchersAll=this._watchersAll||[],m.contains(this._watchersAll,a)||this._watchersAll.push(a)},d.prototype.watch=function(a,b){this._watchers||(this._watchers={}),this._watchers[a]=this._watchers[a]||[],this._watchers[a].push(b)},d.prototype.findWatcherDeps=function(a){var b=[],c=m.keys(this._watchers);return c.forEach(function(c){f(a,c)&&b.push(c)}),b},d.prototype.emitChange=function(a){this._watchers||(this._watchers={});var b=this,c=b.findWatcherDeps(a);c.forEach(function(a){this._watchers[a]&&this._watchers[a].forEach(function(c){c.apply(b,[b.get(a)])})}),b._watchersAll&&m.isArray(b._watchersAll)&&b._watchersAll.forEach(function(c){m.isFunction(c)&&c.apply(b,[a,b.get(a)])})};var e=function(){this.data={},this._bindings={},this.options={persistent:!0,timeoutInput:50,timeoutDOM:500}};e.prototype=Object.create(d.prototype),e.constructor=e,e.prototype.dom=function(a){return this._element=b.dom(a).get(0),this},e.prototype.toStorage=function(a,b){var c=this,b=b||c._element,a=a||c.dom(b).getOptions(),d=c.dom(b).toJSON(a),e=c.dom(b).scope(),f=e?e+"."+a.data:a.data;return a.readonly?!1:void c.set(f,d,a)},e.prototype.toJSON=function(a,b){var c=this,b=b||c._element,d=c.dom(b).getValue(),a=a||c.dom(b).getOptions();return m.isArray(a.pick)&&(d=j(d,a.pick,!0)),m.isArray(a.omit)&&(d=j(d,a.omit,!1)),d},e.prototype.fromStorage=function(a,b){var c=this,b=b||c._element,a=a||c.dom(b).getOptions();if(a.writeonly)return!1;var d=c.dom(b).scope(),e=d?d+"."+a.data:a.data,f=c.get(e);c.dom(b).fromJSON(f,a)},e.prototype.fromJSON=function(a,b,c){var d=this,c=c||d._element,b=b||d.dom(c).getOptions();if(b.writeonly)return!1;if(m.isObject(a)){m.isArray(b.pick)&&(a=j(a,b.pick,!0)),m.isArray(b.omit)&&(a=j(a,b.omit,!1));var e=m.isObject(d.dom(c).toJSON())?d.dom(c).toJSON():{};a=m.extend(e,a)}b.json&&(a=z.isStringified(a)?a:z.prettyprint(a)),d.dom(c).setValue(a,b)},e.prototype.getValue=function(a){var c=this,a=a||c._element,d={SELECT:function(){return b.dom(a).val()},INPUT:function(){var c=b.dom(a).type();return m.contains(["text","password"],c)?b.dom(a).val():m.contains(["checkbox","radio"],c)?b.dom(a).prop("checked")?b.dom(a).val():null:void 0},TEXTAREA:function(){return b.dom(a).val()}},e=function(){b.dom(a).html()},f=b.dom(a).get(0).tagName,g=d[f]||e;return g()},e.prototype._transforms={uppercase:function(a){return m.isString(a)?a.toUpperCase():a},lowercase:function(a){return m.isString(a)?a.toLowerCase():a},reverse:function(a){return a&&a.split&&m.isFunction(a.split)?a.split("").reverse().join(""):a}},e.prototype.registerTransform=function(a,b){var c=this;m.isFunction(b)&&(c._transforms[a]=b)},e.prototype.setValue=function(a,c,d){var e=this,d=d||e._element,c=c||e.dom(d).getOptions();c.transform=c.transform||[],c.transform.forEach(function(b){var c=e._transforms[b]||function(a){return a};a=c(a)});var f={SELECT:function(a){b.dom(d).val(a)},INPUT:function(a){m.isString(a)||(a=JSON.stringify(a));var c=b.dom(d).get(0).type;m.contains(["text","password"],c)&&b.dom(d).val(a||""),m.contains(["checkbox","radio"],c)&&(a===b.dom(d).val()?b.dom(d).prop("checked",!0):b.dom(d).prop("checked",!1))},TEXTAREA:function(a){m.isString(a)||(a=JSON.stringify(a)),b.dom(d).val(a||"")},PRE:function(a){c.html?b.dom(d).html(a):b.dom(d).text(a)},IMG:function(a){if(!a)return a=c.default||"",b.dom(d).attr("src",a),!1;var e=function(a,c){b.dom(d).addClass("way-loading"),b.dom("img",{src:a,onerror:function(){c(!1)},onload:function(){c(!0)}})};e(a,function(e){b.dom(d).removeClass("way-loading"),e?b.dom(d).removeClass("way-error").addClass("way-success"):(a?b.dom(d).addClass("way-error"):b.dom(d).removeClass("way-error").removeClass("way-success"),a=c.default||""),b.dom(d).attr("src",a)})}},g=function(a){c.html?b.dom(d).html(a):b.dom(d).text(a)},h=b.dom(d).get(0).tagName,i=f[h]||g;i(a)},e.prototype.setDefault=function(a,b,c){var d=this,c=c||d._element,a=a||!1,b=b?m.extend(d.dom(c).getOptions(),b):d.dom(c).getOptions();return b.default?void(a?d.set(b.data,b.default,b):d.dom(c).setValue(b.default,b)):!1},e.prototype.setDefaults=function(){var a=this,d="["+c+"-default]",e=b.dom(d).get();for(var f in e){var g=e[f],h=a.dom(g).getOptions(),i=h.data||null,j=i?a.get(i):null;j||a.dom(g).setDefault()}},e.prototype.registerBindings=function(){var a=this,d="["+c+"-data]";a._bindings={};var e=b.dom(d).get();for(var f in e){var g=e[f],h=a.dom(g).getOptions(),i=a.dom(g).scope(),d=i?i+"."+h.data:h.data;a._bindings[d]=a._bindings[d]||[],m.contains(a._bindings[d],b.dom(g).get(0))||a._bindings[d].push(b.dom(g).get(0))}},e.prototype.updateBindings=function(a){var c=this;c._bindings=c._bindings||{};var d=k(c._bindings,a);d.forEach(function(a){var d=b.dom(a).get(0)===b.dom(":focus").get(0)?!0:!1;d||c.dom(a).fromStorage()}),c._bindings.__all__&&c._bindings.__all__.forEach(function(a){c.dom(a).fromJSON(c.data)})},e.prototype.registerRepeats=function(){var a=this,d="["+c+"-repeat]";a._repeats=a._repeats||{},a._repeatsCount=a._repeatsCount||0;var e=b.dom(d).get();for(var f in e){var g=e[f],h=a.dom(g).getOptions();a._repeats[h.repeat]=a._repeats[h.repeat]||[];var i=c+'-repeat-wrapper="'+a._repeatsCount+'"',j=b.dom(g).parent("["+i+"]");if(!j.length){a._repeats[h.repeat].push({id:a._repeatsCount,element:b.dom(g).clone(!0).removeAttr(c+"-repeat").removeAttr(c+"-filter").get(0),selector:h.repeat,filter:h.filter});var k=document.createElement("div");b.dom(k).attr(c+"-repeat-wrapper",a._repeatsCount),b.dom(k).attr(c+"-scope",h.repeat),h.filter&&b.dom(k).attr(c+"-filter",h.filter),b.dom(g).replaceWith(k),a.updateRepeats(h.repeat),a._repeatsCount++}}},e.prototype.updateRepeats=function(a){var d=this;d._repeats=d._repeats||{};var e=k(d._repeats,a);e.forEach(function(a){var e="["+c+'-repeat-wrapper="'+a.id+'"]',f=d.get(a.selector),g=[];a.filter=a.filter||[],b.dom(e).empty();for(var h in f){b.dom(a.element).attr(c+"-scope",h);var i=b.dom(a.element).get(0).outerHTML;i=i.replace(/\$\$key/gi,h),g.push(i)}b.dom(e).html(g),d.registerBindings(),d.updateBindings()})},e.prototype.updateForms=function(){var a=this,d="form["+c+"-data]",e=b.dom(d).get();for(var f in e){var h=e[f],i=a.dom(h).getOptions(),j=i.data;b.dom(h).removeAttr(c+"-data");var k=b.dom(h).find("[name]").reverse().get();for(var f in k){var l=k[f],m=b.dom(l).attr("name");if(g(m,"[]")){var n=m.split("[]")[0],o="[name^='"+n+"']",p=b.dom(h).find(o).get().length;m=n+"."+p}var d=j+"."+m;i.data=d,a.dom(l).setOptions(i),b.dom(l).removeAttr("name")}}},e.prototype.registerDependencies=function(){this.registerBindings(),this.registerRepeats()},e.prototype.updateDependencies=function(a){this.updateBindings(a),this.updateRepeats(a),this.updateForms(a)},e.prototype.setOptions=function(a,d){var e=this,d=e._element||d;for(var f in a){var g=c+"-"+f,h=a[f];b.dom(d).attr(g,h)}},e.prototype.getOptions=function(a){var b=this,a=a||b._element,d={data:null,html:!1,readonly:!1,writeonly:!1,persistent:!1};return m.extend(d,b.dom(a).getAttrs(c))},e.prototype.getAttrs=function(a,c){var d=this,c=c||d._element,e=function(a,b){var c={pick:"array",omit:"array",readonly:"boolean",writeonly:"boolean",json:"boolean",html:"boolean",persistent:"boolean"},d={array:function(a){return a.split(",")},"boolean":function(a){return"true"===a?!0:"false"===a?!1:!0}},e=function(){return b},f=c[a]||null,g=d[f]||e;return g(b)},g={},h=[].slice.call(b.dom(c).get(0).attributes);return h.forEach(function(b){var c=a&&f(b.name,a+"-")?!0:!1;if(c){var d=a?b.name.slice(a.length+1,b.name.length):b.name,h=e(d,b.value);m.contains(["transform","filter"],d)&&(h=h.split("|")),g[d]=h}}),g},e.prototype.scope=function(a,d){var e=this,d=d||e._element,f=c+"-scope",g=c+"-scope-break",h=[],i="",j="["+g+"], ["+f+"]",k=b.dom(d).parents(j).get();for(var l in k){var n=k[l];if(b.dom(n).attr(g))break;var o=b.dom(n).attr(f);h.unshift(o)}return b.dom(d).attr(f)&&h.push(b.dom(d).attr(f)),b.dom(d).attr(g)&&(h=[]),i=m.compact(h).join(".")},e.prototype.get=function(a){var b=this;return void 0===a||m.isString(a)?b.data?a?z.get(b.data,a):b.data:{}:!1},e.prototype.set=function(a,b,c){if(!a)return!1;if("this"===a.split(".")[0])return console.log('Sorry, "this" is a reserved word in way.js'),!1;var d=this;if(c=c||{},a){if(!m.isString(a))return!1;d.data=d.data||{},d.data=a?z.set(d.data,a,b):{},d.updateDependencies(a),d.emitChange(a,b),c.persistent&&d.backup(a)}},e.prototype.push=function(a,b,c){if(!a)return!1;var d=this;c=c||{},a&&(d.data=a?z.push(d.data,a,b,!0):{}),d.updateDependencies(a),d.emitChange(a,null),c.persistent&&d.backup(a)},e.prototype.remove=function(a,b){var c=this;b=b||{},c.data=a?z.remove(c.data,a):{},c.updateDependencies(a),c.emitChange(a,null),b.persistent&&c.backup(a)},e.prototype.clear=function(){this.remove(null,{persistent:!0})},e.prototype.backup=function(){var a=this;if(a.options.persistent)try{var b=a.data||{};localStorage.setItem(c,JSON.stringify(b))}catch(d){console.log("Your browser does not support localStorage.")}},e.prototype.restore=function(){var a=this;if(a.options.persistent)try{var b=localStorage.getItem(c);try{b=JSON.parse(b);for(var d in b)a.set(d,b[d])}catch(e){}}catch(e){console.log("Your browser does not support localStorage.")}};var f=function(a,b){return""===b?!0:null===a||null===b?!1:(a=String(a),b=String(b),a.length>=b.length&&a.slice(0,b.length)===b)},g=function(a,b){return""===b?!0:null===a||null===b?!1:(a=String(a),b=String(b),a.length>=b.length&&a.slice(a.length-b.length,a.length)===b)},h=function(a){return m.pick(a,m.compact(m.keys(a)))},i=function(a,b,c){var d=m.keys(a);return d.forEach(function(d){c?f(d,b)||delete a[d]:f(d,b)&&delete a[d]}),a},j=function(a,b,c){var d=z.flatten(a);for(var e in b)d=i(d,b[e],c);var f=z.unflatten(d);return h(f)},k=function(a,b){var c=[];if(b){var d=b.split("."),e=d[d.length-1],g=!isNaN(e);if(g){d.pop();var h=d.join(".");c=a[h]?m.union(c,a[h]):c}for(var h in a)f(h,b)&&(c=m.union(c,a[h]))}else for(var h in a)c=m.union(c,a[h]);return c},l=function(a){return a?a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"):a},m={},n=Array.prototype,o=Object.prototype,p=Function.prototype,q=(Array.isArray,Object.keys),r=(p.bind,n.push),s=n.slice,t=n.concat,u=o.toString,v=o.hasOwnProperty,w=function(a,b,c,d){if(b&&m.every(a,m.isArray))return t.apply(d,a);for(var e=0,f=a.length;f>e;e++){var g=a[e];m.isArray(g)||m.isArguments(g)?b?r.apply(d,g):w(g,b,c,d):c||d.push(g)}return d},x=function(a,b,c){if(void 0===b)return a;switch(null==c?3:c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)};case 4:return function(c,d,e,f){return a.call(b,c,d,e,f)}}return function(){return a.apply(b,arguments)}};m.compact=function(a){return m.filter(a,m.identity)},m.filter=function(a,b,c){var d=[];return null==a?d:(b=m.iteratee(b,c),m.each(a,function(a,c,e){b(a,c,e)&&d.push(a)}),d)},m.identity=function(a){return a},m.every=function(a,b,c){if(null==a)return!0;b=m.iteratee(b,c);var d,e,f=a.length!==+a.length&&m.keys(a),g=(f||a).length;for(d=0;g>d;d++)if(e=f?f[d]:d,!b(a[e],e,a))return!1;return!0},m.union=function(){return m.uniq(w(arguments,!0,!0,[]))},m.uniq=function(a,b,c,d){if(null==a)return[];m.isBoolean(b)||(d=c,c=b,b=!1),null!=c&&(c=m.iteratee(c,d));for(var e=[],f=[],g=0,h=a.length;h>g;g++){var i=a[g];if(b)g&&f===i||e.push(i),f=i;else if(c){var j=c(i,g,a);m.indexOf(f,j)<0&&(f.push(j),e.push(i))}else m.indexOf(e,i)<0&&e.push(i)}return e},m.pick=function(a,b,c){var d,e={};if(null==a)return e;if(m.isFunction(b)){b=x(b,c);for(d in a){var f=a[d];b(f,d,a)&&(e[d]=f)}}else{var g=t.apply([],s.call(arguments,1));a=new Object(a);for(var h=0,i=g.length;i>h;h++)d=g[h],d in a&&(e[d]=a[d])}return e},m.has=function(a,b){return null!=a&&v.call(a,b)},m.keys=function(a){if(!m.isObject(a))return[];if(q)return q(a);var b=[];for(var c in a)m.has(a,c)&&b.push(c);return b},m.contains=function(a,b){return null==a?!1:(a.length!==+a.length&&(a=m.values(a)),m.indexOf(a,b)>=0)},m.sortedIndex=function(a,b,c,d){c=m.iteratee(c,d,1);for(var e=c(b),f=0,g=a.length;g>f;){var h=f+g>>>1;c(a[h])<e?f=h+1:g=h}return f},m.property=function(a){return function(b){return b[a]}},m.iteratee=function(a,b,c){return null==a?m.identity:m.isFunction(a)?x(a,b,c):m.isObject(a)?m.matches(a):m.property(a)},m.pairs=function(a){for(var b=m.keys(a),c=b.length,d=Array(c),e=0;c>e;e++)d[e]=[b[e],a[b[e]]];return d},m.matches=function(a){var b=m.pairs(a),c=b.length;return function(a){if(null==a)return!c;a=new Object(a);for(var d=0;c>d;d++){var e=b[d],f=e[0];if(e[1]!==a[f]||!(f in a))return!1}return!0}},m.indexOf=function(a,b,c){if(null==a)return-1;var d=0,e=a.length;if(c){if("number"!=typeof c)return d=m.sortedIndex(a,b),a[d]===b?d:-1;d=0>c?Math.max(0,e+c):c}for(;e>d;d++)if(a[d]===b)return d;return-1},m.values=function(a){for(var b=m.keys(a),c=b.length,d=Array(c),e=0;c>e;e++)d[e]=a[b[e]];return d},m.extend=function(a){if(!m.isObject(a))return a;for(var b,c,d=1,e=arguments.length;e>d;d++){b=arguments[d];for(c in b)v.call(b,c)&&(a[c]=b[c])}return a},m.isArray=function(a){return"[object Array]"===u.call(a)},m.isBoolean=function(a){return a===!0||a===!1||"[object Boolean]"===u.call(a)},m.isUndefined=function(a){return void 0===a},m.isObject=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},m.each=function(a,b,c){if(null==a)return a;b=x(b,c);var d,e=a.length;if(e===+e)for(d=0;e>d;d++)b(a[d],d,a);else{var f=m.keys(a);for(d=0,e=f.length;e>d;d++)b(a[f[d]],f[d],a)}return a},m.each(["Arguments","Function","String","Number","Date","RegExp"],function(a){m["is"+a]=function(b){return u.call(b)==="[object "+a+"]"}});var y=function(a,b,c,d){var e,f=b.replace(/\[(["']?)([^\1]+?)\1?\]/g,".$2").replace(/^\./,"").split("."),g=0,h=f.length;if(arguments.length>2){for(e=a,h--;h>g;)b=f[g++],a=a[b]=m.isObject(a[b])?a[b]:{};d?m.isArray(a)?a.splice(f[g],1):delete a[f[g]]:a[f[g]]=c,c=e}else{for(;null!=(a=a[f[g++]])&&h>g;);c=h>g?void 0:a}return c},z={};z.VERSION="0.1.0",z.debug=!0,z.exit=function(a,b,c,d){if(z.debug){var e={};e.noJSON="Not a JSON",e.noString="Not a String",e.noArray="Not an Array",e.missing="Missing argument";var f={source:a,data:c,value:d};f.message=e[b]?e[b]:"No particular reason",console.log("Error",f)}},z.is=function(a){return"[object Object]"==u.call(a)},z.isStringified=function(a){var b=!1;try{b=/^[\],:{}\s]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))}catch(c){}return b},z.get=function(a,b){return void 0==a?z.exit("get","missing","json",a):void 0==b?z.exit("get","missing","selector",b):m.isString(b)?y(a,b):z.exit("get","noString","selector",b)},z.set=function(a,b,c){return void 0==a?z.exit("set","missing","json",a):void 0==b?z.exit("set","missing","selector",b):m.isString(b)?c?y(a,b,c):z.remove(a,b):z.exit("set","noString","selector",b)},z.remove=function(a,b){return void 0==a?z.exit("remove","missing","json",a):void 0==b?z.exit("remove","missing","selector",b):m.isString(b)?y(a,b,null,!0):z.exit("remove","noString","selector",b)},z.push=function(a,b,c,d){if(void 0==a)return z.exit("push","missing","json",a);if(void 0==b)return z.exit("push","missing","selector",b);var e=z.get(a,b);if(!m.isArray(e)){if(!d)return z.exit("push","noArray","array",e);e=[]}return e.push(c),z.set(a,b,e)},z.unshift=function(a,b,c){if(void 0==a)return z.exit("unshift","missing","json",a);if(void 0==b)return z.exit("unshift","missing","selector",b);if(void 0==c)return z.exit("unshift","missing","value",c);var d=z.get(a,b);return m.isArray(d)?(d.unshift(c),z.set(a,b,d)):z.exit("unshift","noArray","array",d)},z.flatten=function(a){function b(a,d){if(Object(a)!==a)c[d]=a;else if(Array.isArray(a))for(var e=0,f=a.length;f>e;e++)b(a[e],d?d+"."+e:""+e),0==f&&(c[d]=[]);else{var g=!0;for(var h in a)g=!1,b(a[h],d?d+"."+h:h);g&&(c[d]={})}}if("Object"!=a.constructor.name)return z.exit("flatten","noJSON","json",a);var c={};return b(a,""),c},z.unflatten=function(a){if(Object(a)!==a||Array.isArray(a))return a;var b,c,d,e,f,g={};for(var h in a){b=g,c="",e=0;do d=h.indexOf(".",e),f=h.substring(e,-1!==d?d:void 0),b=b[c]||(b[c]=isNaN(parseInt(f))?{}:[]),c=f,e=d+1;while(d>=0);b[c]=a[h]}return g[""]},z.prettyprint=function(a){return JSON.stringify(a,void 0,2)};var A=function(){};A.constructor=A,A.prototype.dom=function(a,b){var c=this,d=[];if(!b)return m.isString(a)?d=[].slice.call(document.querySelectorAll(a)):m.isObject(a)&&a.attributes&&(d=[a]),c._elements=d,c.length=d.length,c;var e=document.createElement(a);for(var f in b)e[f]=b[f]},A.prototype.on=function(a,b){var c=this,d=c._elements;a=a.split(" ");for(var e=0,f=d.length;f>e;e++)for(var g=d[e],h=0,i=a.length;i>h;h++)g.addEventListener&&g.addEventListener(a[h],b,!1)},A.prototype.find=function(a){var b=this,c=b.get(0),d=[];return m.isString(a)&&(d=[].slice.call(c.querySelectorAll(a))),b._elements=d,b},A.prototype.get=function(a,b){var c=this,d=c._elements||[],e=d[a]||{};return b?(c._element=e,c):m.isNumber(a)?e:d},A.prototype.reverse=function(){return this._elements=this._elements.reverse(),this},A.prototype.val=function(a){return this.prop("value",a)},A.prototype.type=function(a){return this.prop("type",a)},A.prototype.html=function(a){return this.prop("innerHTML",a)},A.prototype.text=function(a){return this.prop("innerHTML",l(a))},A.prototype.prop=function(a,b){var c=this,d=c._elements;for(var e in d){if(m.isUndefined(b))return d[e][a];d[e][a]=b}},A.prototype.attr=function(a,b){var c=this,d=c._elements;for(var e in d){if(void 0===b)return d[e].getAttribute(a);d[e].setAttribute(a,b)}return c},A.prototype.removeAttr=function(a){var b=this;for(var c in b._elements)b._elements[c].removeAttribute(a);return b},A.prototype.addClass=function(a){var b=this;for(var c in b._elements)b._elements[c].classList.add(a);return b},A.prototype.removeClass=function(a){var b=this;for(var c in b._elements)b._elements[c].classList.remove(a);return b},A.prototype.parents=function(a){for(var b=this,c=b.get(0),d=c.parentNode,e=[];null!==d;){var f=d,g=m.isFunction(f.matches)?f.matches(a):!1,h=void 0===f.doctype?!0:!1;a||(g=!0),g&&h&&e.push(f),d=f.parentNode}return b._elements=e,b},A.prototype.parent=function(a){var b=this,c=b.get(0),d=c.parentNode,e=m.isFunction(d.matches)?d.matches(a):!1;return a||(e=!0),e?d:{}},A.prototype.clone=function(a){var b=this,c=b.get(0),d=c.cloneNode(!0);return b._elements=[d],a?b:d},A.prototype.empty=function(a){var b=this,c=b.get(0);if(!c||!c.hasChildNodes)return a?b:c;for(;c.hasChildNodes();)c.removeChild(c.lastChild);return a?b:c},A.prototype.replaceWith=function(a){var b=this,c=b.get(0),d=c.parentNode;d.replaceChild(a,c)},A.prototype.ready=function(a){document&&m.isFunction(document.addEventListener)?document.addEventListener("DOMContentLoaded",a,!1):window&&m.isFunction(window.addEventListener)?window.addEventListener("load",a,!1):document.onreadystatechange=function(){"complete"===document.readyState&&a()}},a=new e;var B=null,C=function(c){B&&clearTimeout(B),B=setTimeout(function(){var d=b.dom(c.target).get(0);a.dom(d).toStorage()},a.options.timeout)},D=function(b){b.preventDefault();var c=a.dom(this).getOptions();a.remove(c.data,c)},E=function(b){b.preventDefault();var c=a.dom(this).getOptions();if(!c||!c["action-push"])return!1;var d=c["action-push"].split(":"),e=d[0]||null,f=d[1]||null;a.push(e,f,c)},F=function(b){b.preventDefault();var c=a.dom(this).getOptions();return c&&c["action-remove"]?void a.remove(c["action-remove"],c):!1},G=null,H=function(){G&&clearTimeout(G),G=setTimeout(function(){a.registerDependencies(),I()},a.options.timeoutDOM)};b=new A,a.w=b;var I=function(){b.dom("body").on("DOMSubtreeModified",H),b.dom("["+c+"-data]").on("input change",C),b.dom("["+c+"-clear]").on("click",D),b.dom("["+c+"-action-remove]").on("click",F),b.dom("["+c+"-action-push]").on("click",E)},J=function(){I(),a.restore(),a.setDefaults(),a.registerDependencies(),a.updateDependencies()};return b.ready(J),a}); /* * jQuery UI Touch Punch 0.2.2 * * Copyright 2011, Dave Furfero * Dual licensed under the MIT or GPL Version 2 licenses. * * Depends: * jquery.ui.widget.js * jquery.ui.mouse.js */ (function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery); //! moment.js //! version : 2.8.4 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = '2.8.4', // the global-scope this is NOT the global object in Node.js globalScope = typeof global !== 'undefined' ? global : this, oldGlobalMoment, round = Math.round, hasOwnProperty = Object.prototype.hasOwnProperty, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for locale config files locales = {}, // extra moment internal properties (plugins register props here) momentProperties = [], // check for nodeJS hasModule = (typeof module !== 'undefined' && module && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Q|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenOffsetMs = /[\+\-]?\d+/, // 1234567890123 parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d+/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker '+10:00' > ['10', '00'] or '-1530' > ['-15', '30'] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', Q : 'quarter', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // default relative time thresholds relativeTimeThresholds = { s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month M: 11 // months to year }, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.localeData().monthsShort(this, format); }, MMMM : function (format) { return this.localeData().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.localeData().weekdaysMin(this, format); }, ddd : function (format) { return this.localeData().weekdaysShort(this, format); }, dddd : function (format) { return this.localeData().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.localeData().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.localeData().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + ':' + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = '+'; if (a < 0) { a = -a; b = '-'; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, x : function () { return this.valueOf(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, deprecations = {}, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; // Pick the first defined of two or three arguments. dfl comes from // default. function dfl(a, b, c) { switch (arguments.length) { case 2: return a != null ? a : b; case 3: return a != null ? a : b != null ? b : c; default: throw new Error('Implement me'); } } function hasOwnProp(a, b) { return hasOwnProperty.call(a, b); } function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function printMsg(msg) { if (moment.suppressDeprecationWarnings === false && typeof console !== 'undefined' && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (firstTime) { printMsg(msg); firstTime = false; } return fn.apply(this, arguments); }, fn); } function deprecateSimple(name, msg) { if (!deprecations[name]) { printMsg(msg); deprecations[name] = true; } } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.localeData().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Locale() { } // Moment prototype object function Moment(config, skipOverflow) { if (skipOverflow !== false) { checkOverflow(config); } copyConfig(this, config); this._d = new Date(+config._d); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + quarters * 3 + years * 12; this._data = {}; this._locale = moment.localeData(); this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (hasOwnProp(b, i)) { a[i] = b[i]; } } if (hasOwnProp(b, 'toString')) { a.toString = b.toString; } if (hasOwnProp(b, 'valueOf')) { a.valueOf = b.valueOf; } return a; } function copyConfig(to, from) { var i, prop, val; if (typeof from._isAMomentObject !== 'undefined') { to._isAMomentObject = from._isAMomentObject; } if (typeof from._i !== 'undefined') { to._i = from._i; } if (typeof from._f !== 'undefined') { to._f = from._f; } if (typeof from._l !== 'undefined') { to._l = from._l; } if (typeof from._strict !== 'undefined') { to._strict = from._strict; } if (typeof from._tzm !== 'undefined') { to._tzm = from._tzm; } if (typeof from._isUTC !== 'undefined') { to._isUTC = from._isUTC; } if (typeof from._offset !== 'undefined') { to._offset = from._offset; } if (typeof from._pf !== 'undefined') { to._pf = from._pf; } if (typeof from._locale !== 'undefined') { to._locale = from._locale; } if (momentProperties.length > 0) { for (i in momentProperties) { prop = momentProperties[i]; val = from[prop]; if (typeof val !== 'undefined') { to[prop] = val; } } } return to; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } function positiveMomentsDifference(base, other) { var res = {milliseconds: 0, months: 0}; res.months = other.month() - base.month() + (other.year() - base.year()) * 12; if (base.clone().add(res.months, 'M').isAfter(other)) { --res.months; } res.milliseconds = +other - +(base.clone().add(res.months, 'M')); return res; } function momentsDifference(base, other) { var res; other = makeAs(other, base); if (base.isBefore(other)) { res = positiveMomentsDifference(base, other); } else { res = positiveMomentsDifference(other, base); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } // TODO: remove 'name' arg after deprecation is removed function createAdder(direction, name) { return function (val, period) { var dur, tmp; //invert the arguments, but complain about it if (period !== null && !isNaN(+period)) { deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + '(number, period).'); tmp = val; val = period; period = tmp; } val = typeof val === 'string' ? +val : val; dur = moment.duration(val, period); addOrSubtractDurationFromMoment(this, dur, direction); return this; }; } function addOrSubtractDurationFromMoment(mom, duration, isAdding, updateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months; updateOffset = updateOffset == null ? true : updateOffset; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } if (days) { rawSetter(mom, 'Date', rawGetter(mom, 'Date') + days * isAdding); } if (months) { rawMonthSetter(mom, rawGetter(mom, 'Month') + months * isAdding); } if (updateOffset) { moment.updateOffset(mom, days || months); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment._locale[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment._locale, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function weeksInYear(year, dow, doy) { return weekOfYear(moment([year, 11, 31 + dow - doy]), dow, doy).week; } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 24 || (m._a[HOUR] === 24 && (m._a[MINUTE] !== 0 || m._a[SECOND] !== 0 || m._a[MILLISECOND] !== 0)) ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0 && m._pf.bigHour === undefined; } } return m._isValid; } function normalizeLocale(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // pick the locale from the array // try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each // substring from most specific to least, but move to the next array item if it's a more specific variant than the current root function chooseLocale(names) { var i = 0, j, next, locale, split; while (i < names.length) { split = normalizeLocale(names[i]).split('-'); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split('-') : null; while (j > 0) { locale = loadLocale(split.slice(0, j).join('-')); if (locale) { return locale; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return null; } function loadLocale(name) { var oldLocale = null; if (!locales[name] && hasModule) { try { oldLocale = moment.locale(); require('./locale/' + name); // because defineLocale currently also sets the global locale, we want to undo that for lazy loaded locales moment.locale(oldLocale); } catch (e) { } } return locales[name]; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { var res, diff; if (model._isUTC) { res = model.clone(); diff = (moment.isMoment(input) || isDate(input) ? +input : +moment(input)) - (+res); // Use low-level api, because this fn is low-level api. res._d.setTime(+res._d + diff); moment.updateOffset(res, false); return res; } else { return moment(input).local(); } } /************************************ Locale ************************************/ extend(Locale.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } // Lenient ordinal parsing accepts just a number in addition to // number + (possibly) stuff coming from _ordinalParseLenient. this._ordinalParseLenient = new RegExp(this._ordinalParse.source + '|' + /\d{1,2}/.source); }, _months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), months : function (m) { return this._months[m.month()]; }, _monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName, format, strict) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already mom = moment.utc([2000, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'); this._shortMonthsParse[i] = new RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i'); } if (!strict && !this._monthsParse[i]) { regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (strict && format === 'MMMM' && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format === 'MMM' && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LTS : 'h:mm:ss A', LT : 'h:mm A', L : 'MM/DD/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY LT', LLLL : 'dddd, MMMM D, YYYY LT' }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom, now) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom, [now]) : output; }, _relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace('%d', number); }, _ordinal : '%d', _ordinalParse : /\d{1,2}/, preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ''); } return input.replace(/\\/g, ''); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ''; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.localeData().invalidDate(); } format = expandFormat(format, m.localeData()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, locale) { var i = 5; function replaceLongDateFormatTokens(input) { return locale.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'Q': return parseTokenOneDigit; case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return config._locale._meridiemParse; case 'x': return parseTokenOffsetMs; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; case 'Do': return strict ? config._locale._ordinalParse : config._locale._ordinalParseLenient; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), 'i')); return a; } } function timezoneMinutesFromString(string) { string = string || ''; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // QUARTER case 'Q': if (input != null) { datePartArray[MONTH] = (toInt(input) - 1) * 3; } break; // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = config._locale.monthsParse(input, token, config._strict); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; case 'Do' : if (input != null) { datePartArray[DATE] = toInt(parseInt( input.match(/\d{1,2}/)[0], 10)); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = moment.parseTwoDigitYear(input); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = config._locale.isPM(input); break; // HOUR case 'h' : // fall through to hh case 'hh' : config._pf.bigHour = true; /* falls through */ case 'H' : // fall through to HH case 'HH' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX OFFSET (MILLISECONDS) case 'x': config._d = new Date(toInt(input)); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; // WEEKDAY - human case 'dd': case 'ddd': case 'dddd': a = config._locale.weekdaysParse(input); // if we didn't get a weekday name, mark the date as invalid if (a != null) { config._w = config._w || {}; config._w['d'] = a; } else { config._pf.invalidWeekday = input; } break; // WEEK, WEEK DAY - numeric case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gggg': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = toInt(input); } break; case 'gg': case 'GG': config._w = config._w || {}; config._w[token] = moment.parseTwoDigitYear(input); } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; // TODO: We need to take the current isoWeekYear, but that depends on // how we interpret now (local, utc, fixed offset). So create // a now version of current config (take local/utc/offset flags, and // create now). weekYear = dfl(w.GG, config._a[YEAR], weekOfYear(moment(), 1, 4).year); week = dfl(w.W, 1); weekday = dfl(w.E, 1); } else { dow = config._locale._week.dow; doy = config._locale._week.doy; weekYear = dfl(w.gg, config._a[YEAR], weekOfYear(moment(), dow, doy).year); week = dfl(w.w, 1); if (w.d != null) { // weekday -- low day numbers are considered next week weekday = w.d; if (weekday < dow) { ++week; } } else if (w.e != null) { // local weekday -- counting starts from begining of week weekday = w.e + dow; } else { // default to begining of week weekday = dow; } } temp = dayOfYearFromWeeks(weekYear, week, weekday, doy, dow); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = dfl(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // Check for 24:00:00.000 if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); // Apply timezone offset from input. The actual zone can be changed // with parseZone. if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() + config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day || normalizedInput.date, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { if (config._f === moment.ISO_8601) { parseISO(config); return; } config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, config._locale).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // clear _12h flag if hour is <= 12 if (config._pf.bigHour === true && config._a[HOUR] <= 12) { config._pf.bigHour = undefined; } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function parseISO(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be 'T' or undefined config._f = isoDates[i][0] + (match[6] || ' '); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += 'Z'; } makeDateFromStringAndFormat(config); } else { config._isValid = false; } } // date from iso format or fallback function makeDateFromString(config) { parseISO(config); if (config._isValid === false) { delete config._isValid; moment.createFromInputFallback(config); } } function map(arr, fn) { var res = [], i; for (i = 0; i < arr.length; ++i) { res.push(fn(arr[i], i)); } return res; } function makeDateFromInput(config) { var input = config._i, matched; if (input === undefined) { config._d = new Date(); } else if (isDate(input)) { config._d = new Date(+input); } else if ((matched = aspNetJsonRegex.exec(input)) !== null) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = map(input.slice(0), function (obj) { return parseInt(obj, 10); }); dateFromConfig(config); } else if (typeof(input) === 'object') { dateFromObject(config); } else if (typeof(input) === 'number') { // from milliseconds config._d = new Date(input); } else { moment.createFromInputFallback(config); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, locale) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = locale.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) { return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(posNegDuration, withoutSuffix, locale) { var duration = moment.duration(posNegDuration).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), years = round(duration.as('y')), args = seconds < relativeTimeThresholds.s && ['s', seconds] || minutes === 1 && ['m'] || minutes < relativeTimeThresholds.m && ['mm', minutes] || hours === 1 && ['h'] || hours < relativeTimeThresholds.h && ['hh', hours] || days === 1 && ['d'] || days < relativeTimeThresholds.d && ['dd', days] || months === 1 && ['M'] || months < relativeTimeThresholds.M && ['MM', months] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = +posNegDuration > 0; args[4] = locale; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add(daysToDayOfWeek, 'd'); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; d = d === 0 ? 7 : d; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f, res; config._locale = config._locale || moment.localeData(config._l); if (input === null || (format === undefined && input === '')) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = config._locale.preparse(input); } if (moment.isMoment(input)) { return new Moment(input, true); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } res = new Moment(config); if (res._nextDay) { // Adding is smart enough around DST res.add(1, 'd'); res._nextDay = undefined; } return res; } moment = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = locale; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; moment.suppressDeprecationWarnings = false; moment.createFromInputFallback = deprecate( 'moment construction falls back to js Date. This is ' + 'discouraged and will be removed in upcoming major ' + 'release. Please refer to ' + 'https://github.com/moment/moment/issues/1407 for more info.', function (config) { config._d = new Date(config._i + (config._useUTC ? ' UTC' : '')); } ); // Pick a moment m from moments so that m[fn](other) is true for all // other. This relies on the function fn to be transitive. // // moments should either be an array of moment objects or an array, whose // first element is an array of moment objects. function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray(moments[0])) { moments = moments[0]; } if (!moments.length) { return moment(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (moments[i][fn](res)) { res = moments[i]; } } return res; } moment.min = function () { var args = [].slice.call(arguments, 0); return pickBy('isBefore', args); }; moment.max = function () { var args = [].slice.call(arguments, 0); return pickBy('isAfter', args); }; // creating with utc moment.utc = function (input, format, locale, strict) { var c; if (typeof(locale) === 'boolean') { strict = locale; locale = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = locale; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso, diffRes; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === '-') ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } else if (typeof duration === 'object' && ('from' in duration || 'to' in duration)) { diffRes = momentsDifference(moment(duration.from), moment(duration.to)); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (moment.isDuration(input) && hasOwnProp(input, '_locale')) { ret._locale = input._locale; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // constant that refers to the ISO standard moment.ISO_8601 = function () {}; // Plugins that add properties should also add the key here (null value), // so we can properly clone ourselves. moment.momentProperties = momentProperties; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function allows you to set a threshold for relative time strings moment.relativeTimeThreshold = function (threshold, limit) { if (relativeTimeThresholds[threshold] === undefined) { return false; } if (limit === undefined) { return relativeTimeThresholds[threshold]; } relativeTimeThresholds[threshold] = limit; return true; }; moment.lang = deprecate( 'moment.lang is deprecated. Use moment.locale instead.', function (key, value) { return moment.locale(key, value); } ); // This function will load locale and then set the global locale. If // no arguments are passed in, it will simply return the current global // locale key. moment.locale = function (key, values) { var data; if (key) { if (typeof(values) !== 'undefined') { data = moment.defineLocale(key, values); } else { data = moment.localeData(key); } if (data) { moment.duration._locale = moment._locale = data; } } return moment._locale._abbr; }; moment.defineLocale = function (name, values) { if (values !== null) { values.abbr = name; if (!locales[name]) { locales[name] = new Locale(); } locales[name].set(values); // backwards compat for now: also set the locale moment.locale(name); return locales[name]; } else { // useful for testing delete locales[name]; return null; } }; moment.langData = deprecate( 'moment.langData is deprecated. Use moment.localeData instead.', function (key) { return moment.localeData(key); } ); // returns locale data moment.localeData = function (key) { var locale; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return moment._locale; } if (!isArray(key)) { //short-circuit everything else locale = loadLocale(key); if (locale) { return locale; } key = [key]; } return chooseLocale(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && hasOwnProp(obj, '_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function () { return moment.apply(null, arguments).parseZone(); }; moment.parseTwoDigitYear = function (input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2000); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ'); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { if ('function' === typeof Date.prototype.toISOString) { // native implementation is ~50x faster, use it when we can return this.toDate().toISOString(); } else { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function (keepLocalTime) { return this.zone(0, keepLocalTime); }, local : function (keepLocalTime) { if (this._isUTC) { this.zone(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.add(this._dateTzOffset(), 'm'); } } return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.localeData().postformat(output); }, add : createAdder(1, 'add'), subtract : createAdder(-1, 'subtract'), diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output, daysAdjust; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. daysAdjust = (this - moment(this).startOf('month')) - (that - moment(that).startOf('month')); // same as above but with zones, to negate all dst daysAdjust -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4; output += daysAdjust / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration({to: this, from: time}).locale(this.locale()).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function (time) { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var now = time || moment(), sod = makeAs(now, this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.localeData().calendar(format, this, moment(now))); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, 'd'); } else { return day; } }, month : makeAccessor('Month', true), startOf : function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'quarter': case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } // quarters are also special if (units === 'quarter') { this.month(Math.floor(this.month() / 3) * 3); } return this; }, endOf: function (units) { units = normalizeUnits(units); if (units === undefined || units === 'millisecond') { return this; } return this.startOf(units).add(1, (units === 'isoWeek' ? 'week' : units)).subtract(1, 'ms'); }, isAfter: function (input, units) { var inputMs; units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this > +input; } else { inputMs = moment.isMoment(input) ? +input : +moment(input); return inputMs < +this.clone().startOf(units); } }, isBefore: function (input, units) { var inputMs; units = normalizeUnits(typeof units !== 'undefined' ? units : 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this < +input; } else { inputMs = moment.isMoment(input) ? +input : +moment(input); return +this.clone().endOf(units) < inputMs; } }, isSame: function (input, units) { var inputMs; units = normalizeUnits(units || 'millisecond'); if (units === 'millisecond') { input = moment.isMoment(input) ? input : moment(input); return +this === +input; } else { inputMs = +moment(input); return +(this.clone().startOf(units)) <= inputMs && inputMs <= +(this.clone().endOf(units)); } }, min: deprecate( 'moment().min is deprecated, use moment.min instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other < this ? this : other; } ), max: deprecate( 'moment().max is deprecated, use moment.max instead. https://github.com/moment/moment/issues/1548', function (other) { other = moment.apply(null, arguments); return other > this ? this : other; } ), // keepLocalTime = true means only change the timezone, without // affecting the local hour. So 5:31:26 +0300 --[zone(2, true)]--> // 5:31:26 +0200 It is possible that 5:31:26 doesn't exist int zone // +0200, so we adjust the time as needed, to be valid. // // Keeping the time actually adds/subtracts (one hour) // from the actual represented time. That is why we call updateOffset // a second time. In case it wants us to change the offset again // _changeInProgress == true case, then we have to adjust, because // there is no such time in the given timezone. zone : function (input, keepLocalTime) { var offset = this._offset || 0, localAdjust; if (input != null) { if (typeof input === 'string') { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = this._dateTzOffset(); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.subtract(localAdjust, 'm'); } if (offset !== input) { if (!keepLocalTime || this._changeInProgress) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, false); } else if (!this._changeInProgress) { this._changeInProgress = true; moment.updateOffset(this, true); this._changeInProgress = null; } } } else { return this._isUTC ? offset : this._dateTzOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? 'UTC' : ''; }, zoneName : function () { return this._isUTC ? 'Coordinated Universal Time' : ''; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add((input - dayOfYear), 'd'); }, quarter : function (input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); }, weekYear : function (input) { var year = weekOfYear(this, this.localeData()._week.dow, this.localeData()._week.doy).year; return input == null ? year : this.add((input - year), 'y'); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add((input - year), 'y'); }, week : function (input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, 'd'); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, 'd'); }, weekday : function (input) { var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, 'd'); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, isoWeeksInYear : function () { return weeksInYear(this.year(), 1, 4); }, weeksInYear : function () { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a locale key, it will set the locale for this // instance. Otherwise, it will return the locale configuration // variables for this instance. locale : function (key) { var newLocaleData; if (key === undefined) { return this._locale._abbr; } else { newLocaleData = moment.localeData(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } }, lang : deprecate( 'moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function (key) { if (key === undefined) { return this.localeData(); } else { return this.locale(key); } } ), localeData : function () { return this._locale; }, _dateTzOffset : function () { // On Firefox.24 Date#getTimezoneOffset returns a floating point. // https://github.com/moment/moment/pull/1871 return Math.round(this._d.getTimezoneOffset() / 15) * 15; } }); function rawMonthSetter(mom, value) { var dayOfMonth; // TODO: Move this out of here! if (typeof value === 'string') { value = mom.localeData().monthsParse(value); // TODO: Another silent failure? if (typeof value !== 'number') { return mom; } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth); return mom; } function rawGetter(mom, unit) { return mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit](); } function rawSetter(mom, unit, value) { if (unit === 'Month') { return rawMonthSetter(mom, value); } else { return mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value); } } function makeAccessor(unit, keepTime) { return function (value) { if (value != null) { rawSetter(this, unit, value); moment.updateOffset(this, keepTime); return this; } else { return rawGetter(this, unit); } }; } moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false); moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false); moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false); // Setting the hour should keep the time, because the user explicitly // specified which hour he wants. So trying to maintain the same hour (in // a new timezone) makes sense. Adding/subtracting hours does not follow // this rule. moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true); // moment.fn.month is defined separately moment.fn.date = makeAccessor('Date', true); moment.fn.dates = deprecate('dates accessor is deprecated. Use date instead.', makeAccessor('Date', true)); moment.fn.year = makeAccessor('FullYear', true); moment.fn.years = deprecate('years accessor is deprecated. Use year instead.', makeAccessor('FullYear', true)); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; moment.fn.quarters = moment.fn.quarter; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ function daysToYears (days) { // 400 years have 146097 days (taking into account leap year rules) return days * 400 / 146097; } function yearsToDays (years) { // years * 365 + absRound(years / 4) - // absRound(years / 100) + absRound(years / 400); return years * 146097 / 400; } extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years = 0; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); // Accurately convert days to years, assume start from year 0. years = absRound(daysToYears(days)); days -= absRound(yearsToDays(years)); // 30 days to a month // TODO (iskren): Use anchor date (like 1st Jan) to compute this. months += absRound(days / 30); days %= 30; // 12 months -> 1 year years += absRound(months / 12); months %= 12; data.days = days; data.months = months; data.years = years; }, abs : function () { this._milliseconds = Math.abs(this._milliseconds); this._days = Math.abs(this._days); this._months = Math.abs(this._months); this._data.milliseconds = Math.abs(this._data.milliseconds); this._data.seconds = Math.abs(this._data.seconds); this._data.minutes = Math.abs(this._data.minutes); this._data.hours = Math.abs(this._data.hours); this._data.months = Math.abs(this._data.months); this._data.years = Math.abs(this._data.years); return this; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var output = relativeTime(this, !withSuffix, this.localeData()); if (withSuffix) { output = this.localeData().pastFuture(+this, output); } return this.localeData().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { var days, months; units = normalizeUnits(units); if (units === 'month' || units === 'year') { days = this._days + this._milliseconds / 864e5; months = this._months + daysToYears(days) * 12; return units === 'month' ? months : months / 12; } else { // handle milliseconds separately because of floating point math errors (issue #1867) days = this._days + Math.round(yearsToDays(this._months / 12)); switch (units) { case 'week': return days / 7 + this._milliseconds / 6048e5; case 'day': return days + this._milliseconds / 864e5; case 'hour': return days * 24 + this._milliseconds / 36e5; case 'minute': return days * 24 * 60 + this._milliseconds / 6e4; case 'second': return days * 24 * 60 * 60 + this._milliseconds / 1000; // Math.floor prevents floating point math errors here case 'millisecond': return Math.floor(days * 24 * 60 * 60 * 1000) + this._milliseconds; default: throw new Error('Unknown unit ' + units); } } }, lang : moment.fn.lang, locale : moment.fn.locale, toIsoString : deprecate( 'toIsoString() is deprecated. Please use toISOString() instead ' + '(notice the capitals)', function () { return this.toISOString(); } ), toISOString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); }, localeData : function () { return this._locale; } }); moment.duration.fn.toString = moment.duration.fn.toISOString; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } for (i in unitMillisecondFactors) { if (hasOwnProp(unitMillisecondFactors, i)) { makeDurationGetter(i.toLowerCase()); } } moment.duration.fn.asMilliseconds = function () { return this.as('ms'); }; moment.duration.fn.asSeconds = function () { return this.as('s'); }; moment.duration.fn.asMinutes = function () { return this.as('m'); }; moment.duration.fn.asHours = function () { return this.as('h'); }; moment.duration.fn.asDays = function () { return this.as('d'); }; moment.duration.fn.asWeeks = function () { return this.as('weeks'); }; moment.duration.fn.asMonths = function () { return this.as('M'); }; moment.duration.fn.asYears = function () { return this.as('y'); }; /************************************ Default Locale ************************************/ // Set default locale, other locale will inherit from English. moment.locale('en', { ordinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /* EMBED_LOCALES */ /************************************ Exposing Moment ************************************/ function makeGlobal(shouldDeprecate) { /*global ender:false */ if (typeof ender !== 'undefined') { return; } oldGlobalMoment = globalScope.moment; if (shouldDeprecate) { globalScope.moment = deprecate( 'Accessing Moment through the global scope is ' + 'deprecated, and will be removed in an upcoming ' + 'release.', moment); } else { globalScope.moment = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; } else if (typeof define === 'function' && define.amd) { define('moment', function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal === true) { // release the global variable globalScope.moment = oldGlobalMoment; } return moment; }); makeGlobal(true); } else { makeGlobal(); } }).call(this); // Underscore.js 1.7.0 // http://underscorejs.org // (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, concat = ArrayProto.concat, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.7.0'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var createCallback = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result ?? either // identity, an arbitrary callback, a property matcher, or a property accessor. _.iteratee = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return createCallback(value, context, argCount); if (_.isObject(value)) return _.matches(value); return _.property(value); }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { if (obj == null) return obj; iteratee = createCallback(iteratee, context); var i, length = obj.length; if (length === +length) { for (i = 0; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { if (obj == null) return []; iteratee = _.iteratee(iteratee, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, results = Array(length), currentKey; for (var index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; var reduceError = 'Reduce of empty array with no initial value'; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index = 0, currentKey; if (arguments.length < 3) { if (!length) throw new TypeError(reduceError); memo = obj[keys ? keys[index++] : index++]; } for (; index < length; index++) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = function(obj, iteratee, memo, context) { if (obj == null) obj = []; iteratee = createCallback(iteratee, context, 4); var keys = obj.length !== + obj.length && _.keys(obj), index = (keys || obj).length, currentKey; if (arguments.length < 3) { if (!index) throw new TypeError(reduceError); memo = obj[keys ? keys[--index] : --index]; } while (index--) { currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var result; predicate = _.iteratee(predicate, context); _.some(obj, function(value, index, list) { if (predicate(value, index, list)) { result = value; return true; } }); return result; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; if (obj == null) return results; predicate = _.iteratee(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(_.iteratee(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { if (obj == null) return true; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { if (obj == null) return false; predicate = _.iteratee(predicate, context); var keys = obj.length !== +obj.length && _.keys(obj), length = (keys || obj).length, index, currentKey; for (index = 0; index < length; index++) { currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given value (using `===`). // Aliased as `include`. _.contains = _.include = function(obj, target) { if (obj == null) return false; if (obj.length !== +obj.length) obj = _.values(obj); return _.indexOf(obj, target) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { return (isFunc ? method : value[method]).apply(value, args); }); }; // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matches(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matches(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = obj.length === +obj.length ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher??ates_shuffle). _.shuffle = function(obj) { var set = obj && obj.length === +obj.length ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (obj.length !== +obj.length) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = _.iteratee(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = _.iteratee(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = _.iteratee(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = array.length; while (low < high) { var mid = low + high >>> 1; if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (obj.length === +obj.length) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return obj.length === +obj.length ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { predicate = _.iteratee(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; if (n < 0) return []; return slice.call(array, 0, n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. The **guard** check allows it to work with // `_.map`. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. The **guard** check allows it to work with `_.map`. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return slice.call(array, Math.max(array.length - n, 0)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. The **guard** // check allows it to work with `_.map`. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { if (shallow && _.every(input, _.isArray)) { return concat.apply(output, input); } for (var i = 0, length = input.length; i < length; i++) { var value = input[i]; if (!_.isArray(value) && !_.isArguments(value)) { if (!strict) output.push(value); } else if (shallow) { push.apply(output, value); } else { flatten(value, shallow, strict, output); } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false, []); }; // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (array == null) return []; if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = _.iteratee(iteratee, context); var result = []; var seen = []; for (var i = 0, length = array.length; i < length; i++) { var value = array[i]; if (isSorted) { if (!i || seen !== value) result.push(value); seen = value; } else if (iteratee) { var computed = iteratee(value, i, array); if (_.indexOf(seen, computed) < 0) { seen.push(computed); result.push(value); } } else if (_.indexOf(result, value) < 0) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true, [])); }; // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { if (array == null) return []; var result = []; var argsLength = arguments.length; for (var i = 0, length = array.length; i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { var rest = flatten(slice.call(arguments, 1), true, true, []); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function(array) { if (array == null) return []; var length = _.max(arguments, 'length').length; var results = Array(length); for (var i = 0; i < length; i++) { results[i] = _.pluck(arguments, i); } return results; }; // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { if (list == null) return {}; var result = {}; for (var i = 0, length = list.length; i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = function(array, item, isSorted) { if (array == null) return -1; var i = 0, length = array.length; if (isSorted) { if (typeof isSorted == 'number') { i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted; } else { i = _.sortedIndex(array, item); return array[i] === item ? i : -1; } } for (; i < length; i++) if (array[i] === item) return i; return -1; }; _.lastIndexOf = function(array, item, from) { if (array == null) return -1; var idx = array.length; if (typeof from == 'number') { idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1); } while (--idx >= 0) if (array[idx] === item) return idx; return -1; }; // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (arguments.length <= 1) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Function (ahem) Functions // ------------------ // Reusable constructor function for prototype setting. var Ctor = function(){}; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = function(func, context) { var args, bound; if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); args = slice.call(arguments, 2); bound = function() { if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); Ctor.prototype = func.prototype; var self = new Ctor; Ctor.prototype = null; var result = func.apply(self, args.concat(slice.call(arguments))); if (_.isObject(result)) return result; return self; }; return bound; }; // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. _.partial = function(func) { var boundArgs = slice.call(arguments, 1); return function() { var position = 0; var args = boundArgs.slice(); for (var i = 0, length = args.length; i < length; i++) { if (args[i] === _) args[i] = arguments[position++]; } while (position < arguments.length) args.push(arguments[position++]); return func.apply(this, args); }; }; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = hasher ? hasher.apply(this, arguments) : key; if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = function(func) { return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); }; // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { clearTimeout(timeout); timeout = null; previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed after being called N times. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed before being called N times. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } else { func = null; } return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); // Object Functions // ---------------- // Retrieve the names of an object's properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // Extend a given object with all the properties in passed-in object(s). _.extend = function(obj) { if (!_.isObject(obj)) return obj; var source, prop; for (var i = 1, length = arguments.length; i < length; i++) { source = arguments[i]; for (prop in source) { if (hasOwnProperty.call(source, prop)) { obj[prop] = source[prop]; } } } return obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = function(obj, iteratee, context) { var result = {}, key; if (obj == null) return result; if (_.isFunction(iteratee)) { iteratee = createCallback(iteratee, context); for (key in obj) { var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } } else { var keys = concat.apply([], slice.call(arguments, 1)); obj = new Object(obj); for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (key in obj) result[key] = obj[key]; } } return result; }; // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(concat.apply([], slice.call(arguments, 1)), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; // Fill in a given object with default properties. _.defaults = function(obj) { if (!_.isObject(obj)) return obj; for (var i = 1, length = arguments.length; i < length; i++) { var source = arguments[i]; for (var prop in source) { if (obj[prop] === void 0) obj[prop] = source[prop]; } } return obj; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } if (typeof a != 'object' || typeof b != 'object') return false; // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Objects with different constructors are not equivalent, but `Object`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if ( aCtor !== bCtor && // Handle Object.create(x) cases 'constructor' in a && 'constructor' in b && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) ) { return false; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); var size, result; // Recursively compare objects and arrays. if (className === '[object Array]') { // Compare array lengths to determine if a deep comparison is necessary. size = a.length; result = size === b.length; if (result) { // Deep compare the contents, ignoring non-numeric properties. while (size--) { if (!(result = eq(a[size], b[size], aStack, bStack))) break; } } } else { // Deep compare objects. var keys = _.keys(a), key; size = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. result = _.keys(b).length === size; if (result) { while (size--) { // Deep compare each member key = keys[size]; if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; } } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return result; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b, [], []); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0; for (var key in obj) if (_.has(obj, key)) return false; return true; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around an IE 11 bug. if (typeof /./ !== 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = function(key) { return function(obj) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of `key:value` pairs. _.matches = function(attrs) { var pairs = _.pairs(attrs), length = pairs.length; return function(obj) { if (obj == null) return !length; obj = new Object(obj); for (var i = 0; i < length; i++) { var pair = pairs[i], key = pair[0]; if (pair[1] !== obj[key] || !(key in obj)) return false; } return true; }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = createCallback(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', '`': '`' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property) { if (object == null) return void 0; var value = object[property]; return _.isFunction(value) ? object[property]() : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var result = function(obj) { return this._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result.call(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result.call(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result.call(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define === 'function' && define.amd) { define('underscore', [], function() { return _; }); } }.call(this)); ;(function(win){ var store = {}, doc = win.document, localStorageName = 'localStorage', scriptTag = 'script', storage store.disabled = false store.version = '1.3.17' store.set = function(key, value) {} store.get = function(key, defaultVal) {} store.has = function(key) { return store.get(key) !== undefined } store.remove = function(key) {} store.clear = function() {} store.transact = function(key, defaultVal, transactionFn) { if (transactionFn == null) { transactionFn = defaultVal defaultVal = null } if (defaultVal == null) { defaultVal = {} } var val = store.get(key, defaultVal) transactionFn(val) store.set(key, val) } store.getAll = function() {} store.forEach = function() {} store.serialize = function(value) { return JSON.stringify(value) } store.deserialize = function(value) { if (typeof value != 'string') { return undefined } try { return JSON.parse(value) } catch(e) { return value || undefined } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] store.set = function(key, val) { if (val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)) return val } store.get = function(key, defaultVal) { var val = store.deserialize(storage.getItem(key)) return (val === undefined ? defaultVal : val) } store.remove = function(key) { storage.removeItem(key) } store.clear = function() { storage.clear() } store.getAll = function() { var ret = {} store.forEach(function(key, val) { ret[key] = val }) return ret } store.forEach = function(callback) { for (var i=0; i<storage.length; i++) { var key = storage.key(i) callback(key, store.get(key)) } } } else if (doc.documentElement.addBehavior) { var storageOwner, storageContainer // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. try { storageContainer = new ActiveXObject('htmlfile') storageContainer.open() storageContainer.write('<'+scriptTag+'>document.w=window</'+scriptTag+'><iframe src="/favicon.ico"></iframe>') storageContainer.close() storageOwner = storageContainer.w.frames[0].document storage = storageOwner.createElement('div') } catch(e) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } var withIEStorage = function(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys cannot start with a digit or contain certain chars. // See https://github.com/marcuswestin/store.js/issues/40 // See https://github.com/marcuswestin/store.js/issues/83 var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g") function ieKeyFix(key) { return key.replace(/^d/, '___$&').replace(forbiddenCharsRegex, '___') } store.set = withIEStorage(function(storage, key, val) { key = ieKeyFix(key) if (val === undefined) { return store.remove(key) } storage.setAttribute(key, store.serialize(val)) storage.save(localStorageName) return val }) store.get = withIEStorage(function(storage, key, defaultVal) { key = ieKeyFix(key) var val = store.deserialize(storage.getAttribute(key)) return (val === undefined ? defaultVal : val) }) store.remove = withIEStorage(function(storage, key) { key = ieKeyFix(key) storage.removeAttribute(key) storage.save(localStorageName) }) store.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr=attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) store.getAll = function(storage) { var ret = {} store.forEach(function(key, val) { ret[key] = val }) return ret } store.forEach = withIEStorage(function(storage, callback) { var attributes = storage.XMLDocument.documentElement.attributes for (var i=0, attr; attr=attributes[i]; ++i) { callback(attr.name, store.deserialize(storage.getAttribute(attr.name))) } }) } try { var testKey = '__storejs__' store.set(testKey, testKey) if (store.get(testKey) != testKey) { store.disabled = true } store.remove(testKey) } catch(e) { store.disabled = true } store.enabled = !store.disabled if (typeof module != 'undefined' && module.exports && this.module !== module) { module.exports = store } else if (typeof define === 'function' && define.amd) { define(store) } else { win.store = store } })(Function('return this')()); /* jQuery Tags Input Plugin 1.3.2 Copyright (c) 2011 XOXCO, Inc Documentation for this plugin lives here: http://xoxco.com/clickable/jquery-tags-input Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php ben@xoxco.com */ (function($) { var delimiter = new Array(); var tags_callbacks = new Array(); $.fn.doAutosize = function(o){ var minWidth = $(this).data('minwidth'), maxWidth = $(this).data('maxwidth'), val = '', input = $(this), testSubject = $('#'+$(this).data('tester_id')); if (val === (val = input.val())) {return;} // Enter new content into testSubject var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>'); testSubject.html(escaped); // Calculate new width + whether to change var testerWidth = testSubject.width(), newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth, currentWidth = input.width(), isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth) || (newWidth > minWidth && newWidth < maxWidth); // Animate width if (isValidWidthChange) { input.width(newWidth); } }; $.fn.resetAutosize = function(options){ // alert(JSON.stringify(options)); var minWidth = $(this).data('minwidth') || options.minInputWidth || $(this).width(), maxWidth = $(this).data('maxwidth') || options.maxInputWidth || ($(this).closest('.tagsinput').width() - options.inputPadding), val = '', input = $(this), testSubject = $('<tester/>').css({ position: 'absolute', top: -9999, left: -9999, width: 'auto', fontSize: input.css('fontSize'), fontFamily: input.css('fontFamily'), fontWeight: input.css('fontWeight'), letterSpacing: input.css('letterSpacing'), whiteSpace: 'nowrap' }), testerId = $(this).attr('id')+'_autosize_tester'; if(! $('#'+testerId).length > 0){ testSubject.attr('id', testerId); testSubject.appendTo('body'); } input.data('minwidth', minWidth); input.data('maxwidth', maxWidth); input.data('tester_id', testerId); input.css('width', minWidth); }; $.fn.addTag = function(value,options) { options = jQuery.extend({focus:false,callback:true},options); this.each(function() { var id = $(this).attr('id'); var tagslist = $(this).val().split(delimiter[id]); if (tagslist[0] == '') { tagslist = new Array(); } value = jQuery.trim(value); if (options.unique) { var skipTag = $(tagslist).tagExist(value); if(skipTag == true) { //Marks fake input as not_valid to let styling it $('#'+id+'_tag').addClass('not_valid'); } } else { var skipTag = false; } if (value !='' && skipTag != true) { $('<span>').addClass('tag').append( $('<span>').text(value).append(' '), $('<a>', { href : '#', title : 'Removing tag', text : 'x' }).click(function () { return $('#' + id).removeTag(escape(value)); }) ).insertBefore('#' + id + '_addTag'); tagslist.push(value); $('#'+id+'_tag').val(''); if (options.focus) { $('#'+id+'_tag').focus(); } else { $('#'+id+'_tag').blur(); } $.fn.tagsInput.updateTagsField(this,tagslist); if (options.callback && tags_callbacks[id] && tags_callbacks[id]['onAddTag']) { var f = tags_callbacks[id]['onAddTag']; f.call(this, value); } if(tags_callbacks[id] && tags_callbacks[id]['onChange']) { var i = tagslist.length; var f = tags_callbacks[id]['onChange']; f.call(this, $(this), tagslist[i-1]); } } }); return false; }; $.fn.removeTag = function(value) { value = unescape(value); this.each(function() { var id = $(this).attr('id'); var old = $(this).val().split(delimiter[id]); $('#'+id+'_tagsinput .tag').remove(); str = ''; for (i=0; i< old.length; i++) { if (old[i]!=value) { str = str + delimiter[id] +old[i]; } } $.fn.tagsInput.importTags(this,str); if (tags_callbacks[id] && tags_callbacks[id]['onRemoveTag']) { var f = tags_callbacks[id]['onRemoveTag']; f.call(this, value); } }); return false; }; $.fn.tagExist = function(val) { return (jQuery.inArray(val, $(this)) >= 0); //true when tag exists, false when not }; // clear all existing tags and import new ones from a string $.fn.importTags = function(str) { id = $(this).attr('id'); $('#'+id+'_tagsinput .tag').remove(); $.fn.tagsInput.importTags(this,str); } $.fn.tagsInput = function(options) { var settings = jQuery.extend({ interactive:true, defaultText:'add a tag', minChars:0, width:'300px', height:'100px', autocomplete: {selectFirst: false }, 'hide':true, 'delimiter':',', 'unique':true, removeWithBackspace:true, placeholderColor:'#666666', autosize: true, comfortZone: 20, inputPadding: 6*2, },options); this.each(function() { if (settings.hide) { $(this).hide(); } var id = $(this).attr('id') var data = jQuery.extend({ pid:id, real_input: '#'+id, holder: '#'+id+'_tagsinput', input_wrapper: '#'+id+'_addTag', fake_input: '#'+id+'_tag' },settings); delimiter[id] = data.delimiter; if (settings.onAddTag || settings.onRemoveTag || settings.onChange) { tags_callbacks[id] = new Array(); tags_callbacks[id]['onAddTag'] = settings.onAddTag; tags_callbacks[id]['onRemoveTag'] = settings.onRemoveTag; tags_callbacks[id]['onChange'] = settings.onChange; } var markup = '<div id="'+id+'_tagsinput" class="tagsinput"><div id="'+id+'_addTag">'; if (settings.interactive) { markup = markup + '<input id="'+id+'_tag" value="" data-default="'+settings.defaultText+'" />'; } markup = markup + '</div><div class="tags_clear"></div></div>'; $(markup).insertAfter(this); $(data.holder).css('width',settings.width); $(data.holder).css('height',settings.height); if ($(data.real_input).val()!='') { $.fn.tagsInput.importTags($(data.real_input),$(data.real_input).val()); } if (settings.interactive) { $(data.fake_input).val($(data.fake_input).attr('data-default')); $(data.fake_input).css('color',settings.placeholderColor); $(data.fake_input).resetAutosize(settings); $(data.holder).bind('click',data,function(event) { $(event.data.fake_input).focus(); }); $(data.fake_input).bind('focus',data,function(event) { if ($(event.data.fake_input).val()==$(event.data.fake_input).attr('data-default')) { $(event.data.fake_input).val(''); } $(event.data.fake_input).css('color','#000000'); }); if (settings.autocomplete_url != undefined) { autocomplete_options = {source: settings.autocomplete_url}; for (attrname in settings.autocomplete) { autocomplete_options[attrname] = settings.autocomplete[attrname]; } if (jQuery.Autocompleter !== undefined) { $(data.fake_input).autocomplete(settings.autocomplete_url, settings.autocomplete); $(data.fake_input).bind('result',data,function(event,data,formatted) { if (data) { $('#'+id).addTag(data[0] + "",{focus:true,unique:(settings.unique)}); } }); } else if (jQuery.ui.autocomplete !== undefined) { $(data.fake_input).autocomplete(autocomplete_options); $(data.fake_input).bind('autocompleteselect',data,function(event,ui) { $(event.data.real_input).addTag(ui.item.value,{focus:true,unique:(settings.unique)}); return false; }); } } else { // if a user tabs out of the field, create a new tag // this is only available if autocomplete is not used. $(data.fake_input).bind('blur',data,function(event) { var d = $(this).attr('data-default'); if ($(event.data.fake_input).val()!='' && $(event.data.fake_input).val()!=d) { if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) ) $(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)}); } else { $(event.data.fake_input).val($(event.data.fake_input).attr('data-default')); $(event.data.fake_input).css('color',settings.placeholderColor); } return false; }); } // if user types a comma, create a new tag $(data.fake_input).bind('keypress',data,function(event) { if (event.which==event.data.delimiter.charCodeAt(0) || event.which==13 ) { event.preventDefault(); if( (event.data.minChars <= $(event.data.fake_input).val().length) && (!event.data.maxChars || (event.data.maxChars >= $(event.data.fake_input).val().length)) ) $(event.data.real_input).addTag($(event.data.fake_input).val(),{focus:true,unique:(settings.unique)}); $(event.data.fake_input).resetAutosize(settings); return false; } else if (event.data.autosize) { $(event.data.fake_input).doAutosize(settings); } }); //Delete last tag on backspace data.removeWithBackspace && $(data.fake_input).bind('keydown', function(event) { if(event.keyCode == 8 && $(this).val() == '') { event.preventDefault(); var last_tag = $(this).closest('.tagsinput').find('.tag:last').text(); var id = $(this).attr('id').replace(/_tag$/, ''); last_tag = last_tag.replace(/[\s]+x$/, ''); $('#' + id).removeTag(escape(last_tag)); $(this).trigger('focus'); } }); $(data.fake_input).blur(); //Removes the not_valid class when user changes the value of the fake input if(data.unique) { $(data.fake_input).keydown(function(event){ if(event.keyCode == 8 || String.fromCharCode(event.which).match(/\w+|[????????????,/]+/)) { $(this).removeClass('not_valid'); } }); } } // if settings.interactive return false; }); return this; }; $.fn.tagsInput.updateTagsField = function(obj,tagslist) { var id = $(obj).attr('id'); $(obj).val(tagslist.join(delimiter[id])); }; $.fn.tagsInput.importTags = function(obj,val) { $(obj).val(''); var id = $(obj).attr('id'); var tags = val.split(delimiter[id]); for (i=0; i<tags.length; i++) { $(obj).addTag(tags[i],{focus:false,callback:false}); } if(tags_callbacks[id] && tags_callbacks[id]['onChange']) { var f = tags_callbacks[id]['onChange']; f.call(obj, obj, tags[i]); } }; })(jQuery); /*! Holder - 2.3.2 - client side image placeholders (c) 2012-2014 Ivan Malopinsky / http://imsky.co Provided under the MIT License. Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var system_config = { use_svg: false, use_canvas: false, use_fallback: false }; var instance_config = {}; var preempted = false; canvas = document.createElement('canvas'); var dpr = 1, bsr = 1; var resizable_images = []; if (!canvas.getContext) { system_config.use_fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI system_config.use_fallback = true; } else { var ctx = canvas.getContext("2d"); } } if(!!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect){ system_config.use_svg = true; system_config.use_canvas = false; } if(!system_config.use_fallback){ dpr = window.devicePixelRatio || 1, bsr = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; } var ratio = dpr / bsr; var settings = { domain: "holder.js", images: "img", bgnodes: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 }, "sky": { background: "#0D8FDB", foreground: "#fff", size: 12 }, "vine": { background: "#39DBAC", foreground: "#1E292C", size: 12 }, "lava": { background: "#F8591A", foreground: "#1C2846", size: 12 } }, stylesheet: "" }; app.flags = { dimensions: { regex: /^(\d+)x(\d+)$/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /^([0-9%]+)x([0-9%]+)$/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } }, font: { regex: /font\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } }, auto: { regex: /^auto$/ }, textmode: { regex: /textmode\:(.*)/, output: function(val){ return this.regex.exec(val)[1]; } } } function text_size(width, height, template) { height = parseInt(height, 10); width = parseInt(width, 10); var bigSide = Math.max(height, width) var smallSide = Math.min(height, width) var scale = 1 / 12; var newHeight = Math.min(smallSide * 0.75, 0.75 * bigSide * scale); return { height: Math.round(Math.max(template.size, newHeight)) } } var svg_el = (function(){ //Prevent IE <9 from initializing SVG renderer if(!window.XMLSerializer) return; var serializer = new XMLSerializer(); var svg_ns = "http://www.w3.org/2000/svg" var svg = document.createElementNS(svg_ns, "svg"); //IE throws an exception if this is set and Chrome requires it to be set if(svg.webkitMatchesSelector){ svg.setAttribute("xmlns", "http://www.w3.org/2000/svg") } var bg_el = document.createElementNS(svg_ns, "rect") var text_el = document.createElementNS(svg_ns, "text") var textnode_el = document.createTextNode(null) text_el.setAttribute("text-anchor", "middle") text_el.appendChild(textnode_el) svg.appendChild(bg_el) svg.appendChild(text_el) return function(props){ svg.setAttribute("width",props.width); svg.setAttribute("height", props.height); bg_el.setAttribute("width", props.width); bg_el.setAttribute("height", props.height); bg_el.setAttribute("fill", props.template.background); text_el.setAttribute("x", props.width/2) text_el.setAttribute("y", props.height/2) textnode_el.nodeValue=props.text text_el.setAttribute("style", css_properties({ "fill": props.template.foreground, "font-weight": "bold", "font-size": props.text_height+"px", "font-family":props.font, "dominant-baseline":"central" })) return serializer.serializeToString(svg) } })() function css_properties(props){ var ret = []; for(p in props){ if(props.hasOwnProperty(p)){ ret.push(p+":"+props[p]) } } return ret.join(";") } function draw_canvas(args) { var ctx = args.ctx, dimensions = args.dimensions, template = args.template, ratio = args.ratio, holder = args.holder, literal = holder.textmode == "literal", exact = holder.textmode == "exact"; var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; var font = template.font ? template.font : "Arial,Helvetica,sans-serif"; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px " + font; var text = template.text ? template.text : (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height)); if (literal) { var dimensions = holder.dimensions; text = dimensions.width + "x" + dimensions.height; } else if(exact && holder.exact_dimensions){ var dimensions = holder.exact_dimensions; text = (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height)); } var text_width = ctx.measureText(text).width; if (text_width / width >= 0.75) { text_height = Math.floor(text_height * 0.75 * (width / text_width)); } //Resetting font size if necessary ctx.font = "bold " + (text_height * ratio) + "px " + font; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function draw_svg(args){ var dimensions = args.dimensions, template = args.template, holder = args.holder, literal = holder.textmode == "literal", exact = holder.textmode == "exact"; var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width, height = dimensions.height; var font = template.font ? template.font : "Arial,Helvetica,sans-serif"; var text = template.text ? template.text : (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height)); if (literal) { var dimensions = holder.dimensions; text = dimensions.width + "x" + dimensions.height; } else if(exact && holder.exact_dimensions){ var dimensions = holder.exact_dimensions; text = (Math.floor(dimensions.width) + "x" + Math.floor(dimensions.height)); } var string = svg_el({ text: text, width:width, height:height, text_height:text_height, font:font, template:template }) return "data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(string))); } function draw(args) { if(instance_config.use_canvas && !instance_config.use_svg){ return draw_canvas(args); } else{ return draw_svg(args); } } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text ? decodeURIComponent(holder.text) : holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); theme = (holder.font ? extend(theme, { font: holder.font }) : theme); el.setAttribute("data-src", src); holder.theme = theme; el.holder_data = holder; if (mode == "image") { el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); if (instance_config.use_fallback || !holder.auto) { el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; } if (instance_config.use_fallback) { el.style.backgroundColor = theme.background; } else { el.setAttribute("src", draw({ctx: ctx, dimensions: dimensions, template: theme, ratio:ratio, holder: holder})); if(holder.textmode && holder.textmode == "exact"){ resizable_images.push(el); resizable_update(el); } } } else if (mode == "background") { if (!instance_config.use_fallback) { el.style.backgroundImage = "url(" + draw({ctx:ctx, dimensions: dimensions, template: theme, ratio: ratio, holder: holder}) + ")"; el.style.backgroundSize = dimensions.width + "px " + dimensions.height + "px"; } } else if (mode == "fluid") { el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); if (dimensions.height.slice(-1) == "%") { el.style.height = dimensions.height } else if(holder.auto == null || !holder.auto){ el.style.height = dimensions.height + "px" } if (dimensions.width.slice(-1) == "%") { el.style.width = dimensions.width } else if(holder.auto == null || !holder.auto){ el.style.width = dimensions.width + "px" } if (el.style.display == "inline" || el.style.display === "" || el.style.display == "none") { el.style.display = "block"; } set_initial_dimensions(el) if (instance_config.use_fallback) { el.style.backgroundColor = theme.background; } else { resizable_images.push(el); resizable_update(el); } } } function dimension_check(el, callback) { var dimensions = { height: el.clientHeight, width: el.clientWidth }; if (!dimensions.height && !dimensions.width) { el.setAttribute("data-holder-invisible", true) callback.call(this, el) } else{ el.removeAttribute("data-holder-invisible") return dimensions; } } function set_initial_dimensions(el){ if(el.holder_data){ var dimensions = dimension_check(el, app.invisible_error_fn( set_initial_dimensions)) if(dimensions){ var holder = el.holder_data; holder.initial_dimensions = dimensions; holder.fluid_data = { fluid_height: holder.dimensions.height.slice(-1) == "%", fluid_width: holder.dimensions.width.slice(-1) == "%", mode: null } if(holder.fluid_data.fluid_width && !holder.fluid_data.fluid_height){ holder.fluid_data.mode = "width" holder.fluid_data.ratio = holder.initial_dimensions.width / parseFloat(holder.dimensions.height) } else if(!holder.fluid_data.fluid_width && holder.fluid_data.fluid_height){ holder.fluid_data.mode = "height"; holder.fluid_data.ratio = parseFloat(holder.dimensions.width) / holder.initial_dimensions.height } } } } function resizable_update(element) { var images; if (element.nodeType == null) { images = resizable_images; } else { images = [element] } for (var i in images) { if (!images.hasOwnProperty(i)) { continue; } var el = images[i] if (el.holder_data) { var holder = el.holder_data; var dimensions = dimension_check(el, app.invisible_error_fn( resizable_update)) if(dimensions){ if(holder.fluid){ if(holder.auto){ switch(holder.fluid_data.mode){ case "width": dimensions.height = dimensions.width / holder.fluid_data.ratio; break; case "height": dimensions.width = dimensions.height * holder.fluid_data.ratio; break; } } el.setAttribute("src", draw({ ctx: ctx, dimensions: dimensions, template: holder.theme, ratio: ratio, holder: holder })) } if(holder.textmode && holder.textmode == "exact"){ holder.exact_dimensions = dimensions; el.setAttribute("src", draw({ ctx: ctx, dimensions: holder.dimensions, template: holder.theme, ratio: ratio, holder: holder })) } } } } } function parse_flags(flags, options) { var ret = { theme: extend(settings.themes.gray, {}) }; var render = false; for (var fl = flags.length, j = 0; j < fl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.textmode.match(flag)) { ret.textmode = app.flags.textmode.output(flag) } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors if(options.themes.hasOwnProperty(flag)){ ret.theme = extend(options.themes[flag], {}); } } else if (app.flags.font.match(flag)) { ret.font = app.flags.font.output(flag); } else if (app.flags.auto.match(flag)) { ret.auto = true; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } } return render ? ret : false; } for (var flag in app.flags) { if (!app.flags.hasOwnProperty(flag)) continue; app.flags[flag].match = function (val) { return val.match(this.regex) } } app.invisible_error_fn = function(fn){ return function(el){ if(el.hasAttribute("data-holder-invisible")){ throw new Error("Holder: invisible placeholder") } } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { instance_config = extend({}, system_config) preempted = true; var options = extend(settings, o), images = [], imageNodes = [], bgnodes = []; if(options.use_canvas != null && options.use_canvas){ instance_config.use_canvas = true; instance_config.use_svg = false; } if (typeof (options.images) == "string") { imageNodes = selector(options.images); } else if (window.NodeList && options.images instanceof window.NodeList) { imageNodes = options.images; } else if (window.Node && options.images instanceof window.Node) { imageNodes = [options.images]; } else if(window.HTMLCollection && options.images instanceof window.HTMLCollection){ imageNodes = options.images } if (typeof (options.bgnodes) == "string") { bgnodes = selector(options.bgnodes); } else if (window.NodeList && options.elements instanceof window.NodeList) { bgnodes = options.bgnodes; } else if (window.Node && options.bgnodes instanceof window.Node) { bgnodes = [options.bgnodes]; } for (i = 0, l = imageNodes.length; i < l; i++) images.push(imageNodes[i]); var holdercss = document.getElementById("holderjs-style"); if (!holdercss) { holdercss = document.createElement("style"); holdercss.setAttribute("id", "holderjs-style"); holdercss.type = "text/css"; document.getElementsByTagName("head")[0].appendChild(holdercss); } if (!options.nocss) { if (holdercss.styleSheet) { holdercss.styleSheet.cssText += options.stylesheet; } else { if(options.stylesheet.length){ holdercss.appendChild(document.createTextNode(options.stylesheet)); } } } var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = bgnodes.length, i = 0; i < l; i++) { var src = window.getComputedStyle(bgnodes[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); var bgsrc = bgnodes[i].getAttribute("data-background-src"); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", bgnodes[i], holder, src); } } else if (bgsrc != null) { var holder = parse_flags(bgsrc.substr(bgsrc.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { render("background", bgnodes[i], holder, src); } } } for (l = images.length, i = 0; i < l; i++) { var attr_data_src, attr_src; attr_src = attr_data_src = src = null; try { attr_src = images[i].getAttribute("src"); attr_datasrc = images[i].getAttribute("data-src"); } catch (e) {} if (attr_datasrc == null && !! attr_src && attr_src.indexOf(options.domain) >= 0) { src = attr_src; } else if ( !! attr_datasrc && attr_datasrc.indexOf(options.domain) >= 0) { src = attr_datasrc; } if (src) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1).split("/"), options); if (holder) { if (holder.fluid) { render("fluid", images[i], holder, src) } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", resizable_update, false); window.addEventListener("orientationchange", resizable_update, false); } else { window.attachEvent("onresize", resizable_update) } preempted || app.run({}); if (typeof window.Turbolinks === "object") { document.addEventListener("page:change", function() { app.run({}) }) } }); if (typeof define === "function" && define.amd) { define([], function () { return app; }); } //github.com/davidchambers/Base64.js (function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})(); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}} //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a,b){var a=a.match(/^(\W)?(.*)/),b=b||document,c=b["getElement"+(a[1]?"#"==a[1]?"ById":"sByClassName":"sByTagName")],d=c.call(b,a[2]),e=[];return null!==d&&(e=d.length||0===d.length?d:[d]),e} //shallow object property extend function extend(a,b){ var c={}; for(var i in a){ if(a.hasOwnProperty(i)){ c[i]=a[i]; } } for(var i in b){ if(b.hasOwnProperty(i)){ c[i]=b[i]; } } return c } //hasOwnProperty polyfill if (!Object.prototype.hasOwnProperty) /*jshint -W001, -W103 */ Object.prototype.hasOwnProperty = function(prop) { var proto = this.__proto__ || this.constructor.prototype; return (prop in this) && (!(prop in proto) || proto[prop] !== this[prop]); } /*jshint +W001, +W103 */ })(Holder, window); /* =================================================== * bootstrap-transition.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* CSS TRANSITION SUPPORT (http://www.modernizr.com/) * ======================================================= */ $(function () { $.support.transition = (function () { var transitionEnd = (function () { var el = document.createElement('bootstrap') , transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd' , 'MozTransition' : 'transitionend' , 'OTransition' : 'oTransitionEnd otransitionend' , 'transition' : 'transitionend' } , name for (name in transEndEventNames){ if (el.style[name] !== undefined) { return transEndEventNames[name] } } }()) return transitionEnd && { end: transitionEnd } })() }) }(window.jQuery); /* ========================================================== * bootstrap-affix.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* AFFIX CLASS DEFINITION * ====================== */ var Affix = function (element, options) { this.options = $.extend({}, $.fn.affix.defaults, options) this.$window = $(window) .on('scroll.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.affix.data-api', $.proxy(function () { setTimeout($.proxy(this.checkPosition, this), 1) }, this)) this.$element = $(element) this.checkPosition() } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() , scrollTop = this.$window.scrollTop() , position = this.$element.offset() , offset = this.options.offset , offsetBottom = offset.bottom , offsetTop = offset.top , reset = 'affix affix-top affix-bottom' , affix if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top() if (typeof offsetBottom == 'function') offsetBottom = offset.bottom() 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 this.affixed = affix this.unpin = affix == 'bottom' ? position.top - scrollTop : null this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : '')) } /* AFFIX PLUGIN DEFINITION * ======================= */ var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('affix') , options = typeof option == 'object' && option if (!data) $this.data('affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix $.fn.affix.defaults = { offset: 0 } /* 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) , data = $spy.data() data.offset = data.offset || {} data.offsetBottom && (data.offset.bottom = data.offsetBottom) data.offsetTop && (data.offset.top = data.offsetTop) $spy.affix(data) }) }) }(window.jQuery); /* ========================================================== * bootstrap-alert.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* ALERT CLASS DEFINITION * ====================== */ var dismiss = '[data-dismiss="alert"]' , Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) , selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = $(selector) e && e.preventDefault() $parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent()) $parent.trigger(e = $.Event('close')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent .trigger('closed') .remove() } $.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement() } /* ALERT PLUGIN DEFINITION * ======================= */ var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('alert') if (!data) $this.data('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.alert.data-api', dismiss, Alert.prototype.close) }(window.jQuery); /* ============================================================ * bootstrap-button.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* BUTTON PUBLIC CLASS DEFINITION * ============================== */ var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.button.defaults, options) } Button.prototype.setState = function (state) { var d = 'disabled' , $el = this.$element , data = $el.data() , val = $el.is('input') ? 'val' : 'html' state = state + 'Text' 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-radio"]') $parent && $parent .find('.active') .removeClass('active') this.$element.toggleClass('active') } /* BUTTON PLUGIN DEFINITION * ======================== */ var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('button') , options = typeof option == 'object' && option if (!data) $this.data('button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.defaults = { loadingText: 'loading...' } $.fn.button.Constructor = Button /* BUTTON NO CONFLICT * ================== */ $.fn.button.noConflict = function () { $.fn.button = old return this } /* BUTTON DATA-API * =============== */ $(document).on('click.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') }) }(window.jQuery); /* ========================================================== * bootstrap-carousel.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* CAROUSEL CLASS DEFINITION * ========================= */ var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.prototype = { cycle: function (e) { if (!e) this.paused = false if (this.interval) clearInterval(this.interval); this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } , getActiveIndex: function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } , to: function (pos) { var activeIndex = this.getActiveIndex() , that = this if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) { return this.$element.one('slid', function () { that.to(pos) }) } if (activeIndex == pos) { return this.pause().cycle() } return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } , pause: function (e) { if (!e) this.paused = true if (this.$element.find('.next, .prev').length && $.support.transition.end) { this.$element.trigger($.support.transition.end) this.cycle(true) } clearInterval(this.interval) this.interval = null return this } , next: function () { if (this.sliding) return return this.slide('next') } , prev: function () { if (this.sliding) return return this.slide('prev') } , slide: function (type, next) { var $active = this.$element.find('.item.active') , $next = next || $active[type]() , isCycling = this.interval , direction = type == 'next' ? 'left' : 'right' , fallback = type == 'next' ? 'first' : 'last' , that = this , e this.sliding = true isCycling && this.pause() $next = $next.length ? $next : this.$element.find('.item')[fallback]() e = $.Event('slide', { relatedTarget: $next[0] , direction: direction }) if ($next.hasClass('active')) return if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid', 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) this.$element.one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid') }, 0) }) } else { this.$element.trigger(e) if (e.isDefaultPrevented()) return $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid') } isCycling && this.cycle() return this } } /* CAROUSEL PLUGIN DEFINITION * ========================== */ var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('carousel') , options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option) , action = typeof option == 'string' ? option : options.slide if (!data) $this.data('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.defaults = { interval: 5000 , pause: 'hover' } $.fn.carousel.Constructor = Carousel /* CAROUSEL NO CONFLICT * ==================== */ $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } /* CAROUSEL DATA-API * ================= */ $(document).on('click.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href , $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 , options = $.extend({}, $target.data(), $this.data()) , slideIndex $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('carousel').pause().to(slideIndex).cycle() } e.preventDefault() }) }(window.jQuery); /* ============================================================= * bootstrap-collapse.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* COLLAPSE PUBLIC CLASS DEFINITION * ================================ */ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, $.fn.collapse.defaults, options) if (this.options.parent) { this.$parent = $(this.options.parent) } this.options.toggle && this.toggle() } Collapse.prototype = { constructor: Collapse , dimension: function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } , show: function () { var dimension , scroll , actives , hasData if (this.transitioning || this.$element.hasClass('in')) return dimension = this.dimension() scroll = $.camelCase(['scroll', dimension].join('-')) actives = this.$parent && this.$parent.find('> .accordion-group > .in') if (actives && actives.length) { hasData = actives.data('collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('collapse', null) } this.$element[dimension](0) this.transition('addClass', $.Event('show'), 'shown') $.support.transition && this.$element[dimension](this.$element[0][scroll]) } , hide: function () { var dimension if (this.transitioning || !this.$element.hasClass('in')) return dimension = this.dimension() this.reset(this.$element[dimension]()) this.transition('removeClass', $.Event('hide'), 'hidden') this.$element[dimension](0) } , reset: function (size) { var dimension = this.dimension() this.$element .removeClass('collapse') [dimension](size || 'auto') [0].offsetWidth this.$element[size !== null ? 'addClass' : 'removeClass']('collapse') return this } , transition: function (method, startEvent, completeEvent) { var that = this , complete = function () { if (startEvent.type == 'show') that.reset() that.transitioning = 0 that.$element.trigger(completeEvent) } this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return this.transitioning = 1 this.$element[method]('in') $.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete() } , 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) , data = $this.data('collapse') , options = $.extend({}, $.fn.collapse.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.defaults = { toggle: true } $.fn.collapse.Constructor = Collapse /* COLLAPSE NO CONFLICT * ==================== */ $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } /* COLLAPSE DATA-API * ================= */ $(document).on('click.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href , target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 , option = $(target).data('collapse') ? 'toggle' : $this.data() $this[$(target).hasClass('in') ? 'addClass' : 'removeClass']('collapsed') $(target).collapse(option) }) }(window.jQuery); /* ============================================================ * bootstrap-dropdown.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* DROPDOWN CLASS DEFINITION * ========================= */ var toggle = '[data-toggle=dropdown]' , Dropdown = function (element) { var $el = $(element).on('click.dropdown.data-api', this.toggle) $('html').on('click.dropdown.data-api', function () { $el.parent().removeClass('open') }) } Dropdown.prototype = { constructor: Dropdown , toggle: function (e) { var $this = $(this) , $parent , isActive if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement) { // if mobile we we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertBefore($(this)).on('click', clearMenus) } $parent.toggleClass('open') } $this.focus() return false } , keydown: function (e) { var $this , $items , $active , $parent , isActive , index if (!/(38|40|27)/.test(e.keyCode)) return $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return $parent = getParent($this) isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } $items = $('[role=menu] li:not(.divider):visible a', $parent) if (!$items.length) return 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() { $('.dropdown-backdrop').remove() $(toggle).each(function () { getParent($(this)).removeClass('open') }) } function getParent($this) { var selector = $this.attr('data-target') , $parent if (!selector) { selector = $this.attr('href') selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } $parent = selector && $(selector) if (!$parent || !$parent.length) $parent = $this.parent() return $parent } /* DROPDOWN PLUGIN DEFINITION * ========================== */ var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('dropdown') if (!data) $this.data('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.dropdown.data-api', clearMenus) .on('click.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.dropdown.data-api' , toggle, Dropdown.prototype.toggle) .on('keydown.dropdown.data-api', toggle + ', [role=menu]' , Dropdown.prototype.keydown) }(window.jQuery); /* ========================================================= * bootstrap-modal.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* MODAL CLASS DEFINITION * ====================== */ var Modal = function (element, options) { this.options = options this.$element = $(element) .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) this.options.remote && this.$element.find('.modal-body').load(this.options.remote) } Modal.prototype = { constructor: Modal , toggle: function () { return this[!this.isShown ? 'show' : 'hide']() } , show: function () { var that = this , e = $.Event('show') this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() 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() transition ? that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : that.$element.focus().trigger('shown') }) } , hide: function (e) { e && e.preventDefault() var that = this e = $.Event('hide') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.modal') this.$element .removeClass('in') .attr('aria-hidden', true) $.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal() } , enforceFocus: function () { var that = this $(document).on('focusin.modal', function (e) { if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { that.$element.focus() } }) } , escape: function () { var that = this if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.modal', function ( e ) { e.which == 27 && that.hide() }) } else if (!this.isShown) { this.$element.off('keyup.dismiss.modal') } } , hideWithTransition: function () { var that = this , timeout = setTimeout(function () { that.$element.off($.support.transition.end) that.hideModal() }, 500) this.$element.one($.support.transition.end, function () { clearTimeout(timeout) that.hideModal() }) } , hideModal: function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden') }) } , removeBackdrop: function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } , backdrop: function (callback) { var that = this , 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.$backdrop.click( this.options.backdrop == 'static' ? $.proxy(this.$element[0].focus, this.$element[0]) : $.proxy(this.hide, this) ) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade')? this.$backdrop.one($.support.transition.end, callback) : callback() } else if (callback) { callback() } } } /* MODAL PLUGIN DEFINITION * ======================= */ var old = $.fn.modal $.fn.modal = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option) if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option]() else if (options.show) data.show() }) } $.fn.modal.defaults = { backdrop: true , keyboard: true , show: true } $.fn.modal.Constructor = Modal /* MODAL NO CONFLICT * ================= */ $.fn.modal.noConflict = function () { $.fn.modal = old return this } /* MODAL DATA-API * ============== */ $(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) , href = $this.attr('href') , $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 , option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data()) e.preventDefault() $target .modal(option) .one('hide', function () { $this.focus() }) }) }(window.jQuery); /* ======================================================== * bootstrap-tab.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* TAB CLASS DEFINITION * ==================== */ var Tab = function (element) { this.element = $(element) } Tab.prototype = { constructor: Tab , show: function () { var $this = this.element , $ul = $this.closest('ul:not(.dropdown-menu)') , selector = $this.attr('data-target') , previous , $target , e if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ( $this.parent('li').hasClass('active') ) return previous = $ul.find('.active:last a')[0] e = $.Event('show', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown' , relatedTarget: previous }) }) } , activate: function ( element, container, callback) { var $active = container.find('> .active') , 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) : next() $active.removeClass('in') } } /* TAB PLUGIN DEFINITION * ===================== */ var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tab') if (!data) $this.data('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.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(window.jQuery); /* =========================================================== * bootstrap-tooltip.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#tooltips * 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"; // jshint ;_; /* TOOLTIP PUBLIC CLASS DEFINITION * =============================== */ var Tooltip = function (element, options) { this.init('tooltip', element, options) } Tooltip.prototype = { constructor: Tooltip , init: function (type, element, options) { var eventIn , eventOut , triggers , trigger , i this.type = type this.$element = $(element) this.options = this.getOptions(options) this.enabled = true triggers = this.options.trigger.split(' ') for (i = triggers.length; i--;) { trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { eventIn = trigger == 'hover' ? 'mouseenter' : 'focus' 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() } , getOptions: function (options) { options = $.extend({}, $.fn[this.type].defaults, this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay , hide: options.delay } } return options } , enter: function (e) { var defaults = $.fn[this.type].defaults , options = {} , self this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }, this) self = $(e.currentTarget)[this.type](options).data(this.type) if (!self.options.delay || !self.options.delay.show) return self.show() clearTimeout(this.timeout) self.hoverState = 'in' this.timeout = setTimeout(function() { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } , leave: function (e) { var self = $(e.currentTarget)[this.type](this._options).data(this.type) if (this.timeout) clearTimeout(this.timeout) if (!self.options.delay || !self.options.delay.hide) return self.hide() self.hoverState = 'out' this.timeout = setTimeout(function() { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } , show: function () { var $tip , pos , actualWidth , actualHeight , placement , tp , e = $.Event('show') if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip = this.tip() this.setContent() if (this.options.animation) { $tip.addClass('fade') } placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement $tip .detach() .css({ top: 0, left: 0, display: 'block' }) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) pos = this.getPosition() actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight switch (placement) { case 'bottom': tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'top': tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} break case 'left': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} break case 'right': tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} break } this.applyPlacement(tp, placement) this.$element.trigger('shown') } } , applyPlacement: function(offset, placement){ var $tip = this.tip() , width = $tip[0].offsetWidth , height = $tip[0].offsetHeight , actualWidth , actualHeight , delta , replace $tip .offset(offset) .addClass(placement) .addClass('in') actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight replace = true } if (placement == 'bottom' || placement == 'top') { 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) } , replaceArrow: function(delta, dimension, position){ this .arrow() .css(position, delta ? (50 * (1 - delta / dimension) + "%") : '') } , setContent: function () { var $tip = this.tip() , title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } , hide: function () { var that = this , $tip = this.tip() , e = $.Event('hide') this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') function removeWithAnimation() { var timeout = setTimeout(function () { $tip.off($.support.transition.end).detach() }, 500) $tip.one($.support.transition.end, function () { clearTimeout(timeout) $tip.detach() }) } $.support.transition && this.$tip.hasClass('fade') ? removeWithAnimation() : $tip.detach() this.$element.trigger('hidden') return this } , 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', '') } } , hasContent: function () { return this.getTitle() } , getPosition: function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth , height: el.offsetHeight }, this.$element.offset()) } , getTitle: function () { var title , $e = this.$element , o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } , tip: function () { return this.$tip = this.$tip || $(this.options.template) } , arrow: function(){ return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") } , validate: function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } , enable: function () { this.enabled = true } , disable: function () { this.enabled = false } , toggleEnabled: function () { this.enabled = !this.enabled } , toggle: function (e) { var self = e ? $(e.currentTarget)[this.type](this._options).data(this.type) : this self.tip().hasClass('in') ? self.hide() : self.show() } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } } /* TOOLTIP PLUGIN DEFINITION * ========================= */ var old = $.fn.tooltip $.fn.tooltip = function ( option ) { return this.each(function () { var $this = $(this) , data = $this.data('tooltip') , options = typeof option == 'object' && option if (!data) $this.data('tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip $.fn.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 NO CONFLICT * =================== */ $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(window.jQuery); /* =========================================================== * bootstrap-popover.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* POPOVER PUBLIC CLASS DEFINITION * =============================== */ var Popover = function (element, options) { this.init('popover', element, options) } /* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js ========================================== */ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, { constructor: Popover , setContent: function () { var $tip = this.tip() , title = this.getTitle() , 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') } , hasContent: function () { return this.getTitle() || this.getContent() } , getContent: function () { var content , $e = this.$element , o = this.options content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) || $e.attr('data-content') return content } , tip: function () { if (!this.$tip) { this.$tip = $(this.options.template) } return this.$tip } , destroy: function () { this.hide().$element.off('.' + this.type).removeData(this.type) } }) /* POPOVER PLUGIN DEFINITION * ======================= */ var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('popover') , options = typeof option == 'object' && option if (!data) $this.data('popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover $.fn.popover.defaults = $.extend({} , $.fn.tooltip.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>' }) /* POPOVER NO CONFLICT * =================== */ $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(window.jQuery); /* ============================================================= * bootstrap-scrollspy.js v2.3.2 * http://getbootstrap.com/2.3.2/javascript.html#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"; // jshint ;_; /* SCROLLSPY CLASS DEFINITION * ========================== */ function ScrollSpy(element, options) { var process = $.proxy(this.process, this) , $element = $(element).is('body') ? $(window) : $(element) , href this.options = $.extend({}, $.fn.scrollspy.defaults, options) this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.$body = $('body') this.refresh() this.process() } ScrollSpy.prototype = { constructor: ScrollSpy , refresh: function () { var self = this , $targets this.offsets = $([]) this.targets = $([]) $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) return ( $href && $href.length && [[ $href.position().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]) }) } , process: function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset , scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight , maxScroll = scrollHeight - this.$scrollElement.height() , offsets = this.offsets , targets = this.targets , activeTarget = this.activeTarget , 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] ) } } , activate: function (target) { var active , selector this.activeTarget = target $(this.selector) .parent('.active') .removeClass('active') selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' active = $(selector) .parent('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active.closest('li.dropdown').addClass('active') } active.trigger('activate') } } /* SCROLLSPY PLUGIN DEFINITION * =========================== */ var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) , data = $this.data('scrollspy') , options = typeof option == 'object' && option if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy $.fn.scrollspy.defaults = { offset: 10 } /* 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()) }) }) }(window.jQuery); /* * Project: Twitter Bootstrap Hover Dropdown * Author: Cameron Spear * Contributors: Mattia Larentis * * Dependencies?: Twitter Bootstrap's Dropdown plugin * * A simple plugin to enable twitter bootstrap dropdowns to active on hover and provide a nice user experience. * * No license, do what you want. I'd love credit or a shoutout, though. * * http://cameronspear.com/blog/twitter-bootstrap-dropdown-on-hover-plugin/ */ ;(function($, window, undefined) { // outside the scope of the jQuery plugin to // keep track of all dropdowns var $allDropdowns = $(); // if instantlyCloseOthers is true, then it will instantly // shut other nav items when a new one is hovered over $.fn.dropdownHover = function(options) { // the element we really care about // is the dropdown-toggle's parent $allDropdowns = $allDropdowns.add(this.parent()); return this.each(function() { var $this = $(this), $parent = $this.parent(), defaults = { delay: 500, instantlyCloseOthers: true }, data = { delay: $(this).data('delay'), instantlyCloseOthers: $(this).data('close-others') }, settings = $.extend(true, {}, defaults, options, data), timeout; $parent.hover(function(event) { // so a neighbor can't open the dropdown if(!$parent.hasClass('open') && !$this.is(event.target)) { return true; } if(shouldHover) { if(settings.instantlyCloseOthers === true) $allDropdowns.removeClass('open'); window.clearTimeout(timeout); $parent.addClass('open'); } }, function() { if(shouldHover) { timeout = window.setTimeout(function() { $parent.removeClass('open'); }, settings.delay); } }); // this helps with button groups! $this.hover(function() { if(shouldHover) { if(settings.instantlyCloseOthers === true) $allDropdowns.removeClass('open'); window.clearTimeout(timeout); $parent.addClass('open'); } }); // handle submenus $parent.find('.dropdown-submenu').each(function(){ var $this = $(this); var subTimeout; $this.hover(function() { if(shouldHover) { window.clearTimeout(subTimeout); $this.children('.dropdown-menu').show(); // always close submenu siblings instantly $this.siblings().children('.dropdown-menu').hide(); } }, function() { var $submenu = $this.children('.dropdown-menu'); if(shouldHover) { subTimeout = window.setTimeout(function() { $submenu.hide(); }, settings.delay); } else { // emulate Twitter Bootstrap's default behavior $submenu.hide(); } }); }); }); }; // helper variables to guess if they are using a mouse var shouldHover = false, mouse_info = { hits: 0, x: null, y: null }; $(document).ready(function() { // apply dropdownHover to all elements with the data-hover="dropdown" attribute $('[data-hover="dropdown"]').dropdownHover(); // if the mouse movements are "smooth" or there are more than 20, they probably have a real mouse $(document).mousemove(function(e){ mouse_info.hits++; if (mouse_info.hits > 20 || (Math.abs(e.pageX - mouse_info.x) + Math.abs(e.pageY - mouse_info.y)) < 4) { $(this).unbind(e); shouldHover = true; } else { mouse_info.x = e.pageX; mouse_info.y = e.pageY; } }); }); // for the submenu to close on delay, we need to override Bootstrap's CSS in this case var css = '.dropdown-submenu:hover>.dropdown-menu{display:none}'; var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } $('head')[0].appendChild(style); })(jQuery, this); /** * Unslider by @idiot and @damirfoy * Contributors: * - @ShamoX * */ (function($, f) { var Unslider = function() { // Object clone var _ = this; // Set some options _.o = { speed: 500, // animation speed, false for no transition (integer or boolean) delay: 3000, // delay between slides, false for no autoplay (integer or boolean) init: 0, // init delay, false for no delay (integer or boolean) pause: !f, // pause on hover (boolean) loop: !f, // infinitely looping (boolean) keys: f, // keyboard shortcuts (boolean) dots: f, // display dots pagination (boolean) arrows: f, // display prev/next arrows (boolean) prev: '←', // text or html inside prev button (string) next: '→', // same as for prev option fluid: f, // is it a percentage width? (boolean) starting: f, // invoke before animation (function with argument) complete: f, // invoke after animation (function with argument) items: '>ul', // slides container selector item: '>li', // slidable items selector easing: 'swing',// easing function to use for animation autoplay: true, // enable autoplay on initialisation albums:[] }; _.init = function(el, o) { // Check whether we're passing any options in to Unslider _.o = $.extend(_.o, o); _.el = el; _.ul = el.find(_.o.items); _.max = [el.outerWidth() | 0, el.outerHeight() | 0]; _.li = _.ul.find(_.o.item).each(function(index) { var me = $(this), width = me.outerWidth(), height = me.outerHeight(); // Set the max values if (width > _.max[0]) _.max[0] = width; if (height > _.max[1]) _.max[1] = height; }); _.albums = _.o.albums; // Cached vars var o = _.o, ul = _.ul, li = _.li, len = li.length; // Current indeed _.i = 0; // Set the main element el.css({width: _.max[0], height: li.first().outerHeight(), overflow: 'hidden'}); // Set the relative widths ul.css({position: 'relative', left: 0, width: (len * 100) + '%'}); if(o.fluid) { li.css({'float': 'left', width: (100 / len) + '%'}); } else { li.css({'float': 'left', width: (_.max[0]) + 'px'}); } // Autoslide o.autoplay && setTimeout(function() { if (o.delay | 0) { _.play(); if (o.pause) { el.on('mouseover mouseout', function(e) { _.stop(); e.type == 'mouseout' && _.play(); }); }; }; }, o.init | 0); // Keypresses if (o.keys) { $(document).keydown(function(e) { var key = e.which; if (key == 37) _.prev(); // Left else if (key == 39) _.next(); // Right else if (key == 27) _.stop(); // Esc }); }; // Dot pagination o.dots && nav('dot'); // Arrows support o.arrows && nav('arrow'); // Patch for fluid-width sliders. Screw those guys. if (o.fluid) { $(window).resize(function() { _.r && clearTimeout(_.r); _.r = setTimeout(function() { var styl = {height: li.eq(_.i).outerHeight()}, width = el.outerWidth(); ul.css(styl); styl['width'] = Math.min(Math.round((width / el.parent().width()) * 100), 100) + '%'; el.css(styl); li.css({ width: width + 'px' }); }, 50); }).resize(); }; // Move support if ($.event.special['move'] || $.Event('move')) { el.on('movestart', function(e) { if ((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) { e.preventDefault(); }else{ el.data("left", _.ul.offset().left / el.width() * 100); } }).on('move', function(e) { var left = 100 * e.distX / el.width(); _.ul.css("left", el.data("left") + left + "%"); _.ul.data("left", left); }).on('moveend', function(e) { var left = _.ul.data("left"); if (Math.abs(left) > 30){ var i = left > 0 ? _.i-1 : _.i+1; if (i < 0 || i >= len) i = _.i; _.to(i); }else{ _.to(_.i); } }); }; return _; }; // Move Unslider to a slide index _.to = function(index, callback) { if (_.t) { _.stop(); _.play(); } var o = _.o, el = _.el, ul = _.ul, li = _.li, current = _.i, target = li.eq(index); $.isFunction(o.starting) && !callback && o.starting(el, li.eq(current)); // To slide or not to slide if ((!target.length || index < 0) && o.loop == f) return; // Check if it's out of bounds if (!target.length) index = 0; if (index < 0) index = li.length - 1; target = li.eq(index); var speed = callback ? 5 : o.speed | 0, easing = o.easing, obj = {height: target.outerHeight()}; if (!ul.queue('fx').length) { // Handle those pesky dots el.find('.dot').eq(index).addClass('active').siblings().removeClass('active'); if( 0 !== index ){ el.animate(obj, speed, easing) && ul.animate($.extend({left: '-' + index + '00%'}, obj), speed, easing, function(data) { _.i = index; $.isFunction(o.complete) && !callback && o.complete(el, target); }); }else{ ul.offset({left:0}); _.i = index; $.isFunction(o.complete) && !callback && o.complete(el, target); } }; }; // Autoplay functionality _.play = function() { _.t = setInterval(function() { _.to(_.i + 1); }, _.o.delay | 0); }; // Stop autoplay _.stop = function() { _.t = clearInterval(_.t); return _; }; // Move to previous/next slide _.next = function() { return _.stop().to(_.i + 1); }; _.prev = function() { return _.stop().to(_.i - 1); }; // Create dots and arrows function nav(name, html) { if (name == 'dot') { html = '<ol class="dots">'; if(_.albums.length > 0){ $.each(_.li, function(index) { html += '<li class="' + (index == _.i ? name + ' active' : name) + '">' + '<img src="'+ _.albums[index]+'" class="slider-thumb" />' + '</li>'; }); }else{ $.each(_.li, function(index) { html += '<li class="' + (index == _.i ? name + ' active' : name) + '">' +index+ '</li>'; }); } html += '</ol>'; } else { html = '<div class="'; html = html + name + 's">' + html + name + ' prev">' + _.o.prev + '</div>' + html + name + ' next">' + _.o.next + '</div></div>'; }; _.el.addClass('has-' + name + 's').append(html).find('.' + name).click(function() { var me = $(this); me.hasClass('dot') ? _.stop().to(me.index()) : me.hasClass('prev') ? _.prev() : _.next(); }); }; }; // Create a jQuery plugin $.fn.unslider = function(o) { var len = this.length; // Enable multiple-slider support return this.each(function(index) { // Cache a copy of $(this), so it var me = $(this), key = 'unslider' + (len > 1 ? '-' + ++index : ''), instance = (new Unslider).init(me, o); // Invoke an Unslider instance me.data(key, instance).data('key', key); }); }; Unslider.version = "1.0.0"; })(jQuery, false); /*global jQuery */ /*! * jQuery Scrollbox * (c) 2009-2013 Hunter Wu <hunter.wu@gmail.com> * MIT Licensed. * * http://github.com/wmh/jquery-scrollbox */ (function($) { $.fn.scrollbox = function(config) { //default config var defConfig = { linear: false, // Scroll method startDelay: 2, // Start delay (in seconds) delay: 3, // Delay after each scroll event (in seconds) step: 5, // Distance of each single step (in pixels) speed: 32, // Delay after each single step (in milliseconds) switchItems: 1, // Items to switch after each scroll event direction: 'vertical', distance: 'auto', autoPlay: true, onMouseOverPause: true, paused: false, queue: null, listElement: 'ul', listItemElement:'li' }; config = $.extend(defConfig, config); config.scrollOffset = config.direction === 'vertical' ? 'scrollTop' : 'scrollLeft'; if (config.queue) { config.queue = $('#' + config.queue); } return this.each(function() { var container = $(this), containerUL, scrollingId = null, nextScrollId = null, paused = false, backward, forward, resetClock, scrollForward, scrollBackward, forwardHover, pauseHover; if (config.onMouseOverPause) { container.bind('mouseover', function() { paused = true; }); container.bind('mouseout', function() { paused = false; }); } containerUL = container.children(config.listElement + ':first-child'); scrollForward = function() { if (paused) { return; } var curLi, i, newScrollOffset, scrollDistance, theStep; curLi = containerUL.children(config.listItemElement + ':first-child'); scrollDistance = config.distance !== 'auto' ? config.distance : config.direction === 'vertical' ? curLi.outerHeight(true) : curLi.outerWidth(true); // offset if (!config.linear) { theStep = Math.max(3, parseInt((scrollDistance - container[0][config.scrollOffset]) * 0.3, 10)); newScrollOffset = Math.min(container[0][config.scrollOffset] + theStep, scrollDistance); } else { newScrollOffset = Math.min(container[0][config.scrollOffset] + config.step, scrollDistance); } container[0][config.scrollOffset] = newScrollOffset; if (newScrollOffset >= scrollDistance) { for (i = 0; i < config.switchItems; i++) { if (config.queue && config.queue.find(config.listItemElement).length > 0) { containerUL.append(config.queue.find(config.listItemElement)[0]); containerUL.children(config.listItemElement + ':first-child').remove(); } else { containerUL.append(containerUL.children(config.listItemElement + ':first-child')); } } container[0][config.scrollOffset] = 0; clearInterval(scrollingId); if (config.autoPlay) { nextScrollId = setTimeout(forward, config.delay * 1000); } } }; // Backward // 1. If forwarding, then reverse // 2. If stoping, then backward once scrollBackward = function() { if (paused) { return; } var curLi, i, liLen, newScrollOffset, scrollDistance, theStep; // init if (container[0][config.scrollOffset] === 0) { liLen = containerUL.children(config.listItemElement).length; for (i = 0; i < config.switchItems; i++) { containerUL.children(config.listItemElement + ':last-child').insertBefore(containerUL.children(config.listItemElement+':first-child')); } curLi = containerUL.children(config.listItemElement + ':first-child'); scrollDistance = config.distance !== 'auto' ? config.distance : config.direction === 'vertical' ? curLi.height() : curLi.width(); container[0][config.scrollOffset] = scrollDistance; } // new offset if (!config.linear) { theStep = Math.max(3, parseInt(container[0][config.scrollOffset] * 0.3, 10)); newScrollOffset = Math.max(container[0][config.scrollOffset] - theStep, 0); } else { newScrollOffset = Math.max(container[0][config.scrollOffset] - config.step, 0); } container[0][config.scrollOffset] = newScrollOffset; if (newScrollOffset === 0) { clearInterval(scrollingId); if (config.autoPlay) { nextScrollId = setTimeout(forward, config.delay * 1000); } } }; forward = function() { clearInterval(scrollingId); scrollingId = setInterval(scrollForward, config.speed); }; // Implements mouseover function. forwardHover = function() { config.autoPlay = true; paused = false; clearInterval(scrollingId); scrollingId = setInterval(scrollForward, config.speed); }; pauseHover = function() { paused = true; }; backward = function() { clearInterval(scrollingId); scrollingId = setInterval(scrollBackward, config.speed); }; resetClock = function(delay) { config.delay = delay || config.delay; clearTimeout(nextScrollId); if (config.autoPlay) { nextScrollId = setTimeout(forward, config.delay * 1000); } }; if (config.autoPlay) { nextScrollId = setTimeout(forward, config.startDelay * 1000); } // bind events for container container.bind('resetClock', function(delay) { resetClock(delay); }); container.bind('forward', function() { clearTimeout(nextScrollId); forward(); }); container.bind('pauseHover', function() { pauseHover(); }); container.bind('forwardHover', function() { forwardHover(); }); container.bind('backward', function() { clearTimeout(nextScrollId); backward(); }); container.bind('speedUp', function(speed) { if (typeof speed === 'undefined') { speed = Math.max(1, parseInt(config.speed / 2, 10)); } config.speed = speed; }); container.bind('speedDown', function(speed) { if (typeof speed === 'undefined') { speed = config.speed * 2; } config.speed = speed; }); }); }; }(jQuery)); /* ### jQuery Star Rating Plugin v4.11 - 2013-03-14 ### * Home: http://www.fyneworks.com/jquery/star-rating/ * Code: http://code.google.com/p/jquery-star-rating-plugin/ * * Licensed under http://en.wikipedia.org/wiki/MIT_License ### */ /*# AVOID COLLISIONS #*/ ;if(window.jQuery) (function($){ /*# AVOID COLLISIONS #*/ // IE6 Background Image Fix if ((!$.support.opacity && !$.support.style)) try { document.execCommand("BackgroundImageCache", false, true)} catch(e) { }; // Thanks to http://www.visualjquery.com/rating/rating_redux.html // plugin initialization $.fn.rating = function(options){ if(this.length==0) return this; // quick fail // Handle API methods if(typeof arguments[0]=='string'){ // Perform API methods on individual elements if(this.length>1){ var args = arguments; return this.each(function(){ $.fn.rating.apply($(this), args); }); }; // Invoke API method handler $.fn.rating[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []); // Quick exit... return this; }; // Initialize options for this call var options = $.extend( {}/* new object */, $.fn.rating.options/* default options */, options || {} /* just-in-time options */ ); // Allow multiple controls with the same name by making each call unique $.fn.rating.calls++; // loop through each matched element this .not('.star-rating-applied') .addClass('star-rating-applied') .each(function(){ // Load control parameters / find context / etc var control, input = $(this); var eid = (this.name || 'unnamed-rating').replace(/\[|\]/g, '_').replace(/^\_+|\_+$/g,''); var context = $(this.form || document.body); // FIX: http://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=23 var raters = context.data('rating'); if(!raters || raters.call!=$.fn.rating.calls) raters = { count:0, call:$.fn.rating.calls }; var rater = raters[eid] || context.data('rating'+eid); // if rater is available, verify that the control still exists if(rater) control = rater.data('rating'); if(rater && control)//{// save a byte! // add star to control if rater is available and the same control still exists control.count++; //}// save a byte! else{ // create new control if first star or control element was removed/replaced // Initialize options for this rater control = $.extend( {}/* new object */, options || {} /* current call options */, ($.metadata? input.metadata(): ($.meta?input.data():null)) || {}, /* metadata options */ { count:0, stars: [], inputs: [] } ); // increment number of rating controls control.serial = raters.count++; // create rating element rater = $('<span class="star-rating-control"/>'); input.before(rater); // Mark element for initialization (once all stars are ready) rater.addClass('rating-to-be-drawn'); // Accept readOnly setting from 'disabled' property if(input.attr('disabled') || input.hasClass('disabled')) control.readOnly = true; // Accept required setting from class property (class='required') if(input.hasClass('required')) control.required = true; // Create 'cancel' button rater.append( control.cancel = $('<div class="rating-cancel"><a title="' + control.cancel + '">' + control.cancelValue + '</a></div>') .on('mouseover',function(){ $(this).rating('drain'); $(this).addClass('star-rating-hover'); //$(this).rating('focus'); }) .on('mouseout',function(){ $(this).rating('draw'); $(this).removeClass('star-rating-hover'); //$(this).rating('blur'); }) .on('click',function(){ $(this).rating('select'); }) .data('rating', control) ); }; // first element of group // insert rating star (thanks Jan Fanslau rev125 for blind support https://code.google.com/p/jquery-star-rating-plugin/issues/detail?id=125) var star = $('<div role="text" aria-label="'+ this.title +'" class="star-rating rater-'+ control.serial +'"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>'); rater.append(star); // inherit attributes from input element if(this.id) star.attr('id', this.id); if(this.className) star.addClass(this.className); // Half-stars? if(control.half) control.split = 2; // Prepare division control if(typeof control.split=='number' && control.split>0){ var stw = ($.fn.width ? star.width() : 0) || control.starWidth; var spi = (control.count % control.split), spw = Math.floor(stw/control.split); star // restrict star's width and hide overflow (already in CSS) .width(spw) // move the star left by using a negative margin // this is work-around to IE's stupid box model (position:relative doesn't work) .find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' }) }; // readOnly? if(control.readOnly)//{ //save a byte! // Mark star as readOnly so user can customize display star.addClass('star-rating-readonly'); //} //save a byte! else//{ //save a byte! // Enable hover css effects star.addClass('star-rating-live') // Attach mouse events .on('mouseover',function(){ $(this).rating('fill'); $(this).rating('focus'); }) .on('mouseout',function(){ $(this).rating('draw'); $(this).rating('blur'); }) .on('click',function(){ $(this).rating('select'); }) ; //}; //save a byte! // set current selection if(this.checked) control.current = star; // set current select for links if(this.nodeName=="A"){ if($(this).hasClass('selected')) control.current = star; }; // hide input element input.hide(); // backward compatibility, form element to plugin input.on('change.rating',function(event){ if(event.selfTriggered) return false; $(this).rating('select'); }); // attach reference to star to input element and vice-versa star.data('rating.input', input.data('rating.star', star)); // store control information in form (or body when form not available) control.stars[control.stars.length] = star[0]; control.inputs[control.inputs.length] = input[0]; control.rater = raters[eid] = rater; control.context = context; input.data('rating', control); rater.data('rating', control); star.data('rating', control); context.data('rating', raters); context.data('rating'+eid, rater); // required for ajax forms }); // each element // Initialize ratings (first draw) $('.rating-to-be-drawn').rating('draw').removeClass('rating-to-be-drawn'); return this; // don't break the chain... }; /*--------------------------------------------------------*/ /* ### Core functionality and API ### */ $.extend($.fn.rating, { // Used to append a unique serial number to internal control ID // each time the plugin is invoked so same name controls can co-exist calls: 0, focus: function(){ var control = this.data('rating'); if(!control) return this; if(!control.focus) return this; // quick fail if not required // find data for event var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null ); // focus handler, as requested by focusdigital.co.uk if(control.focus) control.focus.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]); }, // $.fn.rating.focus blur: function(){ var control = this.data('rating'); if(!control) return this; if(!control.blur) return this; // quick fail if not required // find data for event var input = $(this).data('rating.input') || $( this.tagName=='INPUT' ? this : null ); // blur handler, as requested by focusdigital.co.uk if(control.blur) control.blur.apply(input[0], [input.val(), $('a', input.data('rating.star'))[0]]); }, // $.fn.rating.blur fill: function(){ // fill to the current mouse position. var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // Reset all stars and highlight them up to this element this.rating('drain'); this.prevAll().addBack().filter('.rater-'+ control.serial).addClass('star-rating-hover'); },// $.fn.rating.fill drain: function() { // drain all the stars. var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // Reset all stars control.rater.children().filter('.rater-'+ control.serial).removeClass('star-rating-on').removeClass('star-rating-hover'); },// $.fn.rating.drain draw: function(){ // set value and stars to reflect current selection var control = this.data('rating'); if(!control) return this; // Clear all stars this.rating('drain'); // Set control value var current = $( control.current );//? control.current.data('rating.input') : null ); var starson = current.length ? current.prevAll().addBack().filter('.rater-'+ control.serial) : null; if(starson) starson.addClass('star-rating-on'); // Show/hide 'cancel' button control.cancel[control.readOnly || control.required?'hide':'show'](); // Add/remove read-only classes to remove hand pointer this.siblings()[control.readOnly?'addClass':'removeClass']('star-rating-readonly'); },// $.fn.rating.draw select: function(value,wantCallBack){ // select a value var control = this.data('rating'); if(!control) return this; // do not execute when control is in read-only mode if(control.readOnly) return; // clear selection control.current = null; // programmatically (based on user input) if(typeof value!='undefined' || this.length>1){ // select by index (0 based) if(typeof value=='number') return $(control.stars[value]).rating('select',undefined,wantCallBack); // select by literal value (must be passed as a string if(typeof value=='string'){ //return $.each(control.stars, function(){ //console.log($(this).data('rating.input'), $(this).data('rating.input').val(), value, $(this).data('rating.input').val()==value?'BINGO!':''); if($(this).data('rating.input').val()==value) $(this).rating('select',undefined,wantCallBack); }); // don't break the chain return this; }; } else{ control.current = this[0].tagName=='INPUT' ? this.data('rating.star') : (this.is('.rater-'+ control.serial) ? this : null); }; // Update rating control state this.data('rating', control); // Update display this.rating('draw'); // find current input and its sibblings var current = $( control.current ? control.current.data('rating.input') : null ); var lastipt = $( control.inputs ).filter(':checked'); var deadipt = $( control.inputs ).not(current); // check and uncheck elements as required deadipt.prop('checked',false);//.removeAttr('checked'); current.prop('checked',true);//.attr('checked','checked'); // trigger change on current or last selected input $(current.length? current : lastipt ).trigger({ type:'change', selfTriggered:true }); // click callback, as requested here: http://plugins.jquery.com/node/1655 if((wantCallBack || wantCallBack == undefined) && control.callback) control.callback.apply(current[0], [current.val(), $('a', control.current)[0]]);// callback event // don't break the chain return this; },// $.fn.rating.select readOnly: function(toggle, disable){ // make the control read-only (still submits value) var control = this.data('rating'); if(!control) return this; // setread-only status control.readOnly = toggle || toggle==undefined ? true : false; // enable/disable control value submission if(disable) $(control.inputs).attr("disabled", "disabled"); else $(control.inputs).removeAttr("disabled"); // Update rating control state this.data('rating', control); // Update display this.rating('draw'); },// $.fn.rating.readOnly disable: function(){ // make read-only and never submit value this.rating('readOnly', true, true); },// $.fn.rating.disable enable: function(){ // make read/write and submit value this.rating('readOnly', false, false); }// $.fn.rating.select }); /*--------------------------------------------------------*/ /* ### Default Settings ### eg.: You can override default control like this: $.fn.rating.options.cancel = 'Clear'; */ $.fn.rating.options = { //$.extend($.fn.rating, { options: { cancel: 'Cancel Rating', // advisory title for the 'cancel' link cancelValue: '', // value to submit when user click the 'cancel' link split: 0, // split the star into how many parts? // Width of star image in case the plugin can't work it out. This can happen if // the jQuery.dimensions plugin is not available OR the image is hidden at installation starWidth: 16//, //NB.: These don't need to be pre-defined (can be undefined/null) so let's save some code! //half: false, // just a shortcut to control.split = 2 //required: false, // disables the 'cancel' button so user can only select one of the specified values //readOnly: false, // disable rating plugin interaction/ values cannot be.one('change', //focus: function(){}, // executed when stars are focused //blur: function(){}, // executed when stars are focused //callback: function(){}, // executed when a star is clicked }; //} }); /*--------------------------------------------------------*/ // auto-initialize plugin $(function(){ $('input[type=radio].star').rating(); }); /*# AVOID COLLISIONS #*/ })(jQuery); /*# AVOID COLLISIONS #*/ /*! jQuery UI - v1.11.0 - 2014-08-11 * http://jqueryui.com * Includes: core.js, widget.js, mouse.js, draggable.js, droppable.js, resizable.js, selectable.js, sortable.js, effect.js, accordion.js, autocomplete.js, button.js, datepicker.js, dialog.js, effect-blind.js, effect-bounce.js, effect-clip.js, effect-drop.js, effect-explode.js, effect-fade.js, effect-fold.js, effect-highlight.js, effect-puff.js, effect-pulsate.js, effect-scale.js, effect-shake.js, effect-size.js, effect-slide.js, effect-transfer.js, menu.js, position.js, progressbar.js, selectmenu.js, slider.js, spinner.js, tabs.js, tooltip.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { // $.ui might exist from components with no dependencies, e.g., $.ui.position $.ui = $.ui || {}; $.extend( $.ui, { version: "1.11.0", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ scrollParent: function() { var position = this.css( "position" ), excludeStaticParent = position === "absolute", scrollParent = this.parents().filter( function() { var parent = $( this ); if ( excludeStaticParent && parent.css( "position" ) === "static" ) { return false; } return (/(auto|scroll)/).test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) ); }).eq( 0 ); return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent; }, uniqueId: (function() { var uuid = 0; return function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + ( ++uuid ); } }); }; })(), removeUniqueId: function() { return this.each(function() { if ( /^ui-id-\d+$/.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().addBack().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated $.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); $.fn.extend({ focus: (function( orig ) { return function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : orig.apply( this, arguments ); }; })( $.fn.focus ), disableSelection: (function() { var eventType = "onselectstart" in document.createElement( "div" ) ? "selectstart" : "mousedown"; return function() { return this.bind( eventType + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }; })(), enableSelection: function() { return this.unbind( ".ui-disableSelection" ); }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; } }); // $.ui.plugin is deprecated. Use $.widget() extensions instead. $.ui.plugin = { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args, allowDisconnected ) { var i, set = instance.plugins[ name ]; if ( !set ) { return; } if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); return $.widget; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var mouseHandled = false; $( document ).mouseup( function() { mouseHandled = false; }); return $.widget("ui.mouse", { version: "1.11.0", options: { cancel: "input,textarea,button,select,option", distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind("mousedown." + this.widgetName, function(event) { return that._mouseDown(event); }) .bind("click." + this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { $.removeData(event.target, that.widgetName + ".preventClickEvent"); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind("." + this.widgetName); if ( this._mouseMoveDelegate ) { this.document .unbind("mousemove." + this.widgetName, this._mouseMoveDelegate) .unbind("mouseup." + this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if ( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { $.removeData(event.target, this.widgetName + ".preventClickEvent"); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; this.document .bind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .bind( "mouseup." + this.widgetName, this._mouseUpDelegate ); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { return this._mouseUp(event); // Iframe mouseup check - mouseup occurred in another document } else if ( !event.which ) { return this._mouseUp( event ); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { this.document .unbind( "mousemove." + this.widgetName, this._mouseMoveDelegate ) .unbind( "mouseup." + this.widgetName, this._mouseUpDelegate ); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + ".preventClickEvent", true); } this._mouseStop(event); } mouseHandled = false; return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(/* event */) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(/* event */) {}, _mouseDrag: function(/* event */) {}, _mouseStop: function(/* event */) {}, _mouseCapture: function(/* event */) { return true; } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.widget("ui.draggable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "drag", options: { addClasses: true, appendTo: "parent", axis: false, connectToSortable: false, containment: false, cursor: "auto", cursorAt: false, grid: false, handle: false, helper: "original", iframeFix: false, opacity: false, refreshPositions: false, revert: false, revertDuration: 500, scope: "default", scroll: true, scrollSensitivity: 20, scrollSpeed: 20, snap: false, snapMode: "both", snapTolerance: 20, stack: false, zIndex: false, // callbacks drag: null, start: null, stop: null }, _create: function() { if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) { this.element[0].style.position = "relative"; } if (this.options.addClasses){ this.element.addClass("ui-draggable"); } if (this.options.disabled){ this.element.addClass("ui-draggable-disabled"); } this._setHandleClassName(); this._mouseInit(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _destroy: function() { if ( ( this.helper || this.element ).is( ".ui-draggable-dragging" ) ) { this.destroyOnClear = true; return; } this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._removeHandleClassName(); this._mouseDestroy(); }, _mouseCapture: function(event) { var document = this.document[ 0 ], o = this.options; // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { // Support: IE9+ // If the <body> is blurred, IE will switch windows, see #9520 if ( document.activeElement && document.activeElement.nodeName.toLowerCase() !== "body" ) { // Blur any element that currently has focus, see #4261 $( document.activeElement ).blur(); } } catch ( error ) {} // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) { return false; } //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) { return false; } $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>") .css({ width: this.offsetWidth + "px", height: this.offsetHeight + "px", position: "absolute", opacity: "0.001", zIndex: 1000 }) .css($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if ($.ui.ddmanager) { $.ui.ddmanager.current = this; } /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css( "position" ); this.scrollParent = this.helper.scrollParent(); this.offsetParent = this.helper.offsetParent(); this.offsetParentCssPosition = this.offsetParent.css( "position" ); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; //Reset scroll cache this.offset.scroll = false; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition( event, false ); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options this._setContainment(); //Trigger event + callbacks if (this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStart(this, event); } return true; }, _mouseDrag: function(event, noPropagation) { // reset any necessary cached properties (see #5009) if ( this.offsetParentCssPosition === "fixed" ) { this.offset.parent = this._getParentOffset(); } //Compute the helpers position this.position = this._generatePosition( event, true ); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if (this._trigger("drag", event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.position; } this.helper[ 0 ].style.left = this.position.left + "px"; this.helper[ 0 ].style.top = this.position.top + "px"; if ($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var that = this, dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) { dropped = $.ui.ddmanager.drop(this, event); } //if a drop comes from outside (a sortable) if (this.dropped) { dropped = this.dropped; this.dropped = false; } if ((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if (that._trigger("stop", event) !== false) { that._clear(); } }); } else { if (this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if ( $.ui.ddmanager ) { $.ui.ddmanager.dragStop(this, event); } // The interaction is over; whether or not the click resulted in a drag, focus the element this.element.focus(); return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if (this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { return this.options.handle ? !!$( event.target ).closest( this.element.find( this.options.handle ) ).length : true; }, _setHandleClassName: function() { this._removeHandleClassName(); $( this.options.handle || this.element ).addClass( "ui-draggable-handle" ); }, _removeHandleClassName: function() { this.element.find( ".ui-draggable-handle" ) .addBack() .removeClass( "ui-draggable-handle" ); }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[ 0 ], [ event ])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element); if (!helper.parents("body").length) { helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo)); } if (helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) { helper.css("position", "absolute"); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = { left: +obj[0], top: +obj[1] || 0 }; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _isRootNode: function( element ) { return ( /(html|body)/i ).test( element.tagName ) || element === this.document[ 0 ]; }, _getParentOffset: function() { //Get the offsetParent and cache its position var po = this.offsetParent.offset(), document = this.document[ 0 ]; // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if (this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if ( this._isRootNode( this.offsetParent[ 0 ] ) ) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if ( this.cssPosition !== "relative" ) { return { top: 0, left: 0 }; } var p = this.element.position(), scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: p.top - ( parseInt(this.helper.css( "top" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollTop() : 0 ), left: p.left - ( parseInt(this.helper.css( "left" ), 10) || 0 ) + ( !scrollIsRootNode ? this.scrollParent.scrollLeft() : 0 ) }; }, _cacheMargins: function() { this.margins = { left: (parseInt(this.element.css("marginLeft"),10) || 0), top: (parseInt(this.element.css("marginTop"),10) || 0), right: (parseInt(this.element.css("marginRight"),10) || 0), bottom: (parseInt(this.element.css("marginBottom"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var over, c, ce, o = this.options, document = this.document[ 0 ]; this.relative_container = null; if ( !o.containment ) { this.containment = null; return; } if ( o.containment === "window" ) { this.containment = [ $( window ).scrollLeft() - this.offset.relative.left - this.offset.parent.left, $( window ).scrollTop() - this.offset.relative.top - this.offset.parent.top, $( window ).scrollLeft() + $( window ).width() - this.helperProportions.width - this.margins.left, $( window ).scrollTop() + ( $( window ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment === "document") { this.containment = [ 0, 0, $( document ).width() - this.helperProportions.width - this.margins.left, ( $( document ).height() || document.body.parentNode.scrollHeight ) - this.helperProportions.height - this.margins.top ]; return; } if ( o.containment.constructor === Array ) { this.containment = o.containment; return; } if ( o.containment === "parent" ) { o.containment = this.helper[ 0 ].parentNode; } c = $( o.containment ); ce = c[ 0 ]; if ( !ce ) { return; } over = c.css( "overflow" ) !== "hidden"; this.containment = [ ( parseInt( c.css( "borderLeftWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingLeft" ), 10 ) || 0 ), ( parseInt( c.css( "borderTopWidth" ), 10 ) || 0 ) + ( parseInt( c.css( "paddingTop" ), 10 ) || 0 ), ( over ? Math.max( ce.scrollWidth, ce.offsetWidth ) : ce.offsetWidth ) - ( parseInt( c.css( "borderRightWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingRight" ), 10 ) || 0 ) - this.helperProportions.width - this.margins.left - this.margins.right, ( over ? Math.max( ce.scrollHeight, ce.offsetHeight ) : ce.offsetHeight ) - ( parseInt( c.css( "borderBottomWidth" ), 10 ) || 0 ) - ( parseInt( c.css( "paddingBottom" ), 10 ) || 0 ) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; }, _convertPositionTo: function(d, pos) { if (!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) * mod) ) }; }, _generatePosition: function( event, constrainPosition ) { var containment, co, top, left, o = this.options, scrollIsRootNode = this._isRootNode( this.scrollParent[ 0 ] ), pageX = event.pageX, pageY = event.pageY; // Cache the scroll if ( !scrollIsRootNode || !this.offset.scroll ) { this.offset.scroll = { top: this.scrollParent.scrollTop(), left: this.scrollParent.scrollLeft() }; } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ // If we are not dragging yet, we won't check for options if ( constrainPosition ) { if ( this.containment ) { if ( this.relative_container ){ co = this.relative_container.offset(); containment = [ this.containment[ 0 ] + co.left, this.containment[ 1 ] + co.top, this.containment[ 2 ] + co.left, this.containment[ 3 ] + co.top ]; } else { containment = this.containment; } if (event.pageX - this.offset.click.left < containment[0]) { pageX = containment[0] + this.offset.click.left; } if (event.pageY - this.offset.click.top < containment[1]) { pageY = containment[1] + this.offset.click.top; } if (event.pageX - this.offset.click.left > containment[2]) { pageX = containment[2] + this.offset.click.left; } if (event.pageY - this.offset.click.top > containment[3]) { pageY = containment[3] + this.offset.click.top; } } if (o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } if ( o.axis === "y" ) { pageX = this.originalPageX; } if ( o.axis === "x" ) { pageY = this.originalPageY; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.top : ( scrollIsRootNode ? 0 : this.offset.scroll.top ) ) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( this.cssPosition === "fixed" ? -this.offset.scroll.left : ( scrollIsRootNode ? 0 : this.offset.scroll.left ) ) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if (this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) { this.helper.remove(); } this.helper = null; this.cancelHelperRemoval = false; if ( this.destroyOnClear ) { this.destroy(); } }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call( this, type, [ event, ui, this ], true ); //The absolute position has to be recalculated after plugins if (type === "drag") { this.positionAbs = this._convertPositionTo("absolute"); } return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function() { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function( event, ui, inst ) { var o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $( this ).sortable( "instance" ); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function( event, ui, inst ) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var uiSortable = $.extend( {}, ui, { item: inst.element }); $.each(inst.sortables, function() { if (this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid" if (this.shouldRevert) { this.instance.options.revert = this.shouldRevert; } //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if (inst.options.helper === "original") { this.instance.currentItem.css({ top: "auto", left: "auto" }); } } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function( event, ui, inst ) { var that = this; $.each(inst.sortables, function() { var innermostIntersecting = false, thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function() { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this !== thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.contains(thisSortable.instance.element[0], this.instance.element[0]) ) { innermostIntersecting = false; } return innermostIntersecting; }); } if (innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if (!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if (this.instance.currentItem) { this.instance._mouseDrag(event); } } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if (this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger("out", event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if (this.instance.placeholder) { this.instance.placeholder.remove(); } inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } } }); } }); $.ui.plugin.add("draggable", "cursor", { start: function( event, ui, instance ) { var t = $( "body" ), o = instance.options; if (t.css("cursor")) { o._cursor = t.css("cursor"); } t.css("cursor", o.cursor); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._cursor) { $("body").css("cursor", o._cursor); } } }); $.ui.plugin.add("draggable", "opacity", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("opacity")) { o._opacity = t.css("opacity"); } t.css("opacity", o.opacity); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._opacity) { $(ui.helper).css("opacity", o._opacity); } } }); $.ui.plugin.add("draggable", "scroll", { start: function( event, ui, i ) { if ( i.scrollParent[ 0 ] !== i.document[ 0 ] && i.scrollParent[ 0 ].tagName !== "HTML" ) { i.overflowOffset = i.scrollParent.offset(); } }, drag: function( event, ui, i ) { var o = i.options, scrolled = false, document = i.document[ 0 ]; if ( i.scrollParent[ 0 ] !== document && i.scrollParent[ 0 ].tagName !== "HTML" ) { if (!o.axis || o.axis !== "x") { if ((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; } else if (event.pageY - i.overflowOffset.top < o.scrollSensitivity) { i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } } if (!o.axis || o.axis !== "y") { if ((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; } else if (event.pageX - i.overflowOffset.left < o.scrollSensitivity) { i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } } else { if (!o.axis || o.axis !== "x") { if (event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if ($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } } if (!o.axis || o.axis !== "y") { if (event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if ($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } } if (scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(i, event); } } }); $.ui.plugin.add("draggable", "snap", { start: function( event, ui, i ) { var o = i.options; i.snapElements = []; $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() { var $t = $(this), $o = $t.offset(); if (this !== i.element[0]) { i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); } }); }, drag: function( event, ui, inst ) { var ts, bs, ls, rs, l, r, t, b, i, first, o = inst.options, d = o.snapTolerance, x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (i = inst.snapElements.length - 1; i >= 0; i--){ l = inst.snapElements[i].left; r = l + inst.snapElements[i].width; t = inst.snapElements[i].top; b = t + inst.snapElements[i].height; if ( x2 < l - d || x1 > r + d || y2 < t - d || y1 > b + d || !$.contains( inst.snapElements[ i ].item.ownerDocument, inst.snapElements[ i ].item ) ) { if (inst.snapElements[i].snapping) { (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = false; continue; } if (o.snapMode !== "inner") { ts = Math.abs(t - y2) <= d; bs = Math.abs(b - y1) <= d; ls = Math.abs(l - x2) <= d; rs = Math.abs(r - x1) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } } first = (ts || bs || ls || rs); if (o.snapMode !== "outer") { ts = Math.abs(t - y1) <= d; bs = Math.abs(b - y2) <= d; ls = Math.abs(l - x1) <= d; rs = Math.abs(r - x2) <= d; if (ts) { ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; } if (bs) { ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; } if (ls) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; } if (rs) { ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } } if (!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) { (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); } inst.snapElements[i].snapping = (ts || bs || ls || rs || first); } } }); $.ui.plugin.add("draggable", "stack", { start: function( event, ui, instance ) { var min, o = instance.options, group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } min = parseInt($(group[0]).css("zIndex"), 10) || 0; $(group).each(function(i) { $(this).css("zIndex", min + i); }); this.css("zIndex", (min + group.length)); } }); $.ui.plugin.add("draggable", "zIndex", { start: function( event, ui, instance ) { var t = $( ui.helper ), o = instance.options; if (t.css("zIndex")) { o._zIndex = t.css("zIndex"); } t.css("zIndex", o.zIndex); }, stop: function( event, ui, instance ) { var o = instance.options; if (o._zIndex) { $(ui.helper).css("zIndex", o._zIndex); } } }); return $.ui.draggable; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./mouse", "./draggable" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.widget( "ui.droppable", { version: "1.11.0", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function() { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction( accept ) ? accept : function( d ) { return d.is( accept ); }; this.proportions = function( /* valueToWrite */ ) { if ( arguments.length ) { // Store the droppable's proportions proportions = arguments[ 0 ]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[ 0 ].offsetWidth, height: this.element[ 0 ].offsetHeight }; } }; this._addToManager( o.scope ); o.addClasses && this.element.addClass( "ui-droppable" ); }, _addToManager: function( scope ) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[ scope ] = $.ui.ddmanager.droppables[ scope ] || []; $.ui.ddmanager.droppables[ scope ].push( this ); }, _splice: function( drop ) { var i = 0; for ( ; i < drop.length; i++ ) { if ( drop[ i ] === this ) { drop.splice( i, 1 ); } } }, _destroy: function() { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this.element.removeClass( "ui-droppable ui-droppable-disabled" ); }, _setOption: function( key, value ) { if ( key === "accept" ) { this.accept = $.isFunction( value ) ? value : function( d ) { return d.is( value ); }; } else if ( key === "scope" ) { var drop = $.ui.ddmanager.droppables[ this.options.scope ]; this._splice( drop ); this._addToManager( value ); } this._super( key, value ); }, _activate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.addClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "activate", event, this.ui( draggable ) ); } }, _deactivate: function( event ) { var draggable = $.ui.ddmanager.current; if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( draggable ){ this._trigger( "deactivate", event, this.ui( draggable ) ); } }, _over: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.addClass( this.options.hoverClass ); } this._trigger( "over", event, this.ui( draggable ) ); } }, _out: function( event ) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "out", event, this.ui( draggable ) ); } }, _drop: function( event, custom ) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if ( !draggable || ( draggable.currentItem || draggable.element )[ 0 ] === this.element[ 0 ] ) { return false; } this.element.find( ":data(ui-droppable)" ).not( ".ui-draggable-dragging" ).each(function() { var inst = $( this ).droppable( "instance" ); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call( inst.element[ 0 ], ( draggable.currentItem || draggable.element ) ) && $.ui.intersect( draggable, $.extend( inst, { offset: inst.element.offset() } ), inst.options.tolerance ) ) { childrenIntersection = true; return false; } }); if ( childrenIntersection ) { return false; } if ( this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { if ( this.options.activeClass ) { this.element.removeClass( this.options.activeClass ); } if ( this.options.hoverClass ) { this.element.removeClass( this.options.hoverClass ); } this._trigger( "drop", event, this.ui( draggable ) ); return this.element; } return false; }, ui: function( c ) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function() { function isOverAxis( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function( draggable, droppable, toleranceMode ) { if ( !droppable.offset ) { return false; } var draggableLeft, draggableTop, x1 = ( draggable.positionAbs || draggable.position.absolute ).left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch ( toleranceMode ) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": draggableLeft = ( ( draggable.positionAbs || draggable.position.absolute ).left + ( draggable.clickOffset || draggable.offset.click ).left ); draggableTop = ( ( draggable.positionAbs || draggable.position.absolute ).top + ( draggable.clickOffset || draggable.offset.click ).top ); return isOverAxis( draggableTop, t, droppable.proportions().height ) && isOverAxis( draggableLeft, l, droppable.proportions().width ); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { "default": [] }, prepareOffsets: function( t, event ) { var i, j, m = $.ui.ddmanager.droppables[ t.options.scope ] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find( ":data(ui-droppable)" ).addBack(); droppablesLoop: for ( i = 0; i < m.length; i++ ) { // No disabled and non-accepted if ( m[ i ].options.disabled || ( t && !m[ i ].accept.call( m[ i ].element[ 0 ], ( t.currentItem || t.element ) ) ) ) { continue; } // Filter out elements in the current dragged item for ( j = 0; j < list.length; j++ ) { if ( list[ j ] === m[ i ].element[ 0 ] ) { m[ i ].proportions().height = 0; continue droppablesLoop; } } m[ i ].visible = m[ i ].element.css( "display" ) !== "none"; if ( !m[ i ].visible ) { continue; } // Activate the droppable if used directly from draggables if ( type === "mousedown" ) { m[ i ]._activate.call( m[ i ], event ); } m[ i ].offset = m[ i ].element.offset(); m[ i ].proportions({ width: m[ i ].element[ 0 ].offsetWidth, height: m[ i ].element[ 0 ].offsetHeight }); } }, drop: function( draggable, event ) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each( ( $.ui.ddmanager.droppables[ draggable.options.scope ] || [] ).slice(), function() { if ( !this.options ) { return; } if ( !this.options.disabled && this.visible && $.ui.intersect( draggable, this, this.options.tolerance ) ) { dropped = this._drop.call( this, event ) || dropped; } if ( !this.options.disabled && this.visible && this.accept.call( this.element[ 0 ], ( draggable.currentItem || draggable.element ) ) ) { this.isout = true; this.isover = false; this._deactivate.call( this, event ); } }); return dropped; }, dragStart: function( draggable, event ) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } }); }, drag: function( draggable, event ) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if ( draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } // Run through all droppables and check their positions based on specific tolerance options $.each( $.ui.ddmanager.droppables[ draggable.options.scope ] || [], function() { if ( this.options.disabled || this.greedyChild || !this.visible ) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect( draggable, this, this.options.tolerance ), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if ( !c ) { return; } if ( this.options.greedy ) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents( ":data(ui-droppable)" ).filter(function() { return $( this ).droppable( "instance" ).options.scope === scope; }); if ( parent.length ) { parentInstance = $( parent[ 0 ] ).droppable( "instance" ); parentInstance.greedyChild = ( c === "isover" ); } } // we just moved into a greedy child if ( parentInstance && c === "isover" ) { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call( parentInstance, event ); } this[ c ] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call( this, event ); // we just moved out of a greedy child if ( parentInstance && c === "isout" ) { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call( parentInstance, event ); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if ( !draggable.options.refreshPositions ) { $.ui.ddmanager.prepareOffsets( draggable, event ); } } }; return $.ui.droppable; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.widget("ui.resizable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "resize", options: { alsoResize: false, animate: false, animateDuration: "slow", animateEasing: "swing", aspectRatio: false, autoHide: false, containment: false, ghost: false, grid: false, handles: "e,s,se", helper: false, maxHeight: null, maxWidth: null, minHeight: 10, minWidth: 10, // See #7960 zIndex: 90, // callbacks resize: null, start: null, stop: null }, _num: function( value ) { return parseInt( value, 10 ) || 0; }, _isNumber: function( value ) { return !isNaN( parseInt( value , 10 ) ); }, _hasScroll: function( el, a ) { if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; }, _create: function() { var n, i, handle, axis, hname, that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || "ui-resizable-helper" : null }); // Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { this.element.wrap( $("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({ position: this.element.css("position"), width: this.element.outerWidth(), height: this.element.outerHeight(), top: this.element.css("top"), left: this.element.css("left") }) ); this.element = this.element.parent().data( "ui-resizable", this.element.resizable( "instance" ) ); this.elementIsWrapper = true; this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") }); this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0}); // support: Safari // Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css("resize"); this.originalElement.css("resize", "none"); this._proportionallyResizeElements.push(this.originalElement.css({ position: "static", zoom: 1, display: "block" })); // support: IE9 // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css("margin") }); this._proportionallyResize(); } this.handles = o.handles || (!$(".ui-resizable-handle", this.element).length ? "e,s,se" : { n: ".ui-resizable-n", e: ".ui-resizable-e", s: ".ui-resizable-s", w: ".ui-resizable-w", se: ".ui-resizable-se", sw: ".ui-resizable-sw", ne: ".ui-resizable-ne", nw: ".ui-resizable-nw" }); if(this.handles.constructor === String) { if ( this.handles === "all") { this.handles = "n,e,s,w,se,sw,ne,nw"; } n = this.handles.split(","); this.handles = {}; for(i = 0; i < n.length; i++) { handle = $.trim(n[i]); hname = "ui-resizable-"+handle; axis = $("<div class='ui-resizable-handle " + hname + "'></div>"); axis.css({ zIndex: o.zIndex }); // TODO : What's going on here? if ("se" === handle) { axis.addClass("ui-icon ui-icon-gripsmall-diagonal-se"); } this.handles[handle] = ".ui-resizable-"+handle; this.element.append(axis); } } this._renderAxis = function(target) { var i, axis, padPos, padWrapper; target = target || this.element; for(i in this.handles) { if(this.handles[i].constructor === String) { this.handles[i] = this.element.children( this.handles[ i ] ).first().show(); } if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { axis = $(this.handles[i], this.element); padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); padPos = [ "padding", /ne|nw|n/.test(i) ? "Top" : /se|sw|s/.test(i) ? "Bottom" : /^e$/.test(i) ? "Right" : "Left" ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } // TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) { continue; } } }; // TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $(".ui-resizable-handle", this.element) .disableSelection(); this._handles.mouseover(function() { if (!that.resizing) { if (this.className) { axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); } that.axis = axis && axis[1] ? axis[1] : "se"; } }); if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) { return; } $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) { return; } if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var wrapper, _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove(); }; // TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); wrapper = this.element; this.originalElement.css({ position: wrapper.css("position"), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css("top"), left: wrapper.css("left") }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css("resize", this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var i, handle, capture = false; for (i in this.handles) { handle = $(this.handles[i])[0]; if (handle === event.target || $.contains(handle, event.target)) { capture = true; } } return !this.options.disabled && capture; }, _mouseStart: function(event) { var curleft, curtop, cursor, o = this.options, el = this.element; this.resizing = true; this._renderProxy(); curleft = this._num(this.helper.css("left")); curtop = this._num(this.helper.css("top")); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: this.helper.width(), height: this.helper.height() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; this.aspectRatio = (typeof o.aspectRatio === "number") ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); cursor = $(".ui-resizable-" + this.axis).css("cursor"); $("body").css("cursor", cursor === "auto" ? this.axis + "-resize" : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { var data, el = this.helper, props = {}, smp = this.originalMousePosition, a = this.axis, dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0, trigger = this._change[a]; this.prevPosition = { top: this.position.top, left: this.position.left }; this.prevSize = { width: this.size.width, height: this.size.height }; if (!trigger) { return false; } data = trigger.apply(this, [event, dx, dy]); this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) { data = this._updateRatio(data, event); } data = this._respectSize(data, event); this._updateCache(data); this._propagate("resize", event); if ( this.position.top !== this.prevPosition.top ) { props.top = this.position.top + "px"; } if ( this.position.left !== this.prevPosition.left ) { props.left = this.position.left + "px"; } if ( this.size.width !== this.prevSize.width ) { props.width = this.size.width + "px"; } if ( this.size.height !== this.prevSize.height ) { props.height = this.size.height + "px"; } el.css( props ); if ( !this._helper && this._proportionallyResizeElements.length ) { this._proportionallyResize(); } if ( !$.isEmptyObject( props ) ) { this._trigger( "resize", event, this.ui() ); } return false; }, _mouseStop: function(event) { this.resizing = false; var pr, ista, soffseth, soffsetw, s, left, top, o = this.options, that = this; if(this._helper) { pr = this._proportionallyResizeElements; ista = pr.length && (/textarea/i).test(pr[0].nodeName); soffseth = ista && this._hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height; soffsetw = ista ? 0 : that.sizeDiff.width; s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }; left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null; top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) { this.element.css($.extend(s, { top: top, left: left })); } that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) { this._proportionallyResize(); } } $("body").css("cursor", "auto"); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) { this.helper.remove(); } return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b, o = this.options; b = { minWidth: this._isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: this._isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: this._isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: this._isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) { b.minWidth = pMinWidth; } if(pMinHeight > b.minHeight) { b.minHeight = pMinHeight; } if(pMaxWidth < b.maxWidth) { b.maxWidth = pMaxWidth; } if(pMaxHeight < b.maxHeight) { b.maxHeight = pMaxHeight; } } this._vBoundaries = b; }, _updateCache: function(data) { this.offset = this.helper.offset(); if (this._isNumber(data.left)) { this.position.left = data.left; } if (this._isNumber(data.top)) { this.position.top = data.top; } if (this._isNumber(data.height)) { this.size.height = data.height; } if (this._isNumber(data.width)) { this.size.width = data.width; } }, _updateRatio: function( data ) { var cpos = this.position, csize = this.size, a = this.axis; if (this._isNumber(data.height)) { data.width = (data.height * this.aspectRatio); } else if (this._isNumber(data.width)) { data.height = (data.width / this.aspectRatio); } if (a === "sw") { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a === "nw") { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function( data ) { var o = this._vBoundaries, a = this.axis, ismaxw = this._isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = this._isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = this._isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = this._isNumber(data.height) && o.minHeight && (o.minHeight > data.height), dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height, cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw) { data.width = o.minWidth; } if (isminh) { data.height = o.minHeight; } if (ismaxw) { data.width = o.maxWidth; } if (ismaxh) { data.height = o.maxHeight; } if (isminw && cw) { data.left = dw - o.minWidth; } if (ismaxw && cw) { data.left = dw - o.maxWidth; } if (isminh && ch) { data.top = dh - o.minHeight; } if (ismaxh && ch) { data.top = dh - o.maxHeight; } // Fixing jump error on top/left - bug #2330 if (!data.width && !data.height && !data.left && data.top) { data.top = null; } else if (!data.width && !data.height && !data.top && data.left) { data.left = null; } return data; }, _proportionallyResize: function() { if (!this._proportionallyResizeElements.length) { return; } var i, j, borders, paddings, prel, element = this.helper || this.element; for ( i=0; i < this._proportionallyResizeElements.length; i++) { prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { this.borderDif = []; borders = [prel.css("borderTopWidth"), prel.css("borderRightWidth"), prel.css("borderBottomWidth"), prel.css("borderLeftWidth")]; paddings = [prel.css("paddingTop"), prel.css("paddingRight"), prel.css("paddingBottom"), prel.css("paddingLeft")]; for ( j = 0; j < borders.length; j++ ) { this.borderDif[ j ] = ( parseInt( borders[ j ], 10 ) || 0 ) + ( parseInt( paddings[ j ], 10 ) || 0 ); } } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); } }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $("<div style='overflow:hidden;'></div>"); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() - 1, height: this.element.outerHeight() - 1, position: "absolute", left: this.elementOffset.left +"px", top: this.elementOffset.top +"px", zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx) { return { width: this.originalSize.width + dx }; }, w: function(event, dx) { var cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n !== "resize" && this._trigger(n, event, this.ui())); }, plugins: {}, ui: function() { return { originalElement: this.originalElement, element: this.element, helper: this.helper, position: this.position, size: this.size, originalSize: this.originalSize, originalPosition: this.originalPosition, prevSize: this.prevSize, prevPosition: this.prevPosition }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "animate", { stop: function( event ) { var that = $(this).resizable( "instance" ), o = that.options, pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && that._hasScroll(pr[0], "left") /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width, style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css("left"), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css("top"), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css("width"), 10), height: parseInt(that.element.css("height"), 10), top: parseInt(that.element.css("top"), 10), left: parseInt(that.element.css("left"), 10) }; if (pr && pr.length) { $(pr[0]).css({ width: data.width, height: data.height }); } // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add( "resizable", "containment", { start: function() { var element, p, co, ch, cw, width, height, that = $( this ).resizable( "instance" ), o = that.options, el = that.element, oc = o.containment, ce = ( oc instanceof $ ) ? oc.get( 0 ) : ( /parent/.test( oc ) ) ? el.parent().get( 0 ) : oc; if ( !ce ) { return; } that.containerElement = $( ce ); if ( /document/.test( oc ) || oc === document ) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $( document ), left: 0, top: 0, width: $( document ).width(), height: $( document ).height() || document.body.parentNode.scrollHeight }; } else { element = $( ce ); p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function( i, name ) { p[ i ] = that._num( element.css( "padding" + name ) ); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: ( element.innerHeight() - p[ 3 ] ), width: ( element.innerWidth() - p[ 1 ] ) }; co = that.containerOffset; ch = that.containerSize.height; cw = that.containerSize.width; width = ( that._hasScroll ( ce, "left" ) ? ce.scrollWidth : cw ); height = ( that._hasScroll ( ce ) ? ce.scrollHeight : ch ) ; that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function( event, ui ) { var woset, hoset, isParent, isOffsetRelative, that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top: 0, left: 0 }, ce = that.containerElement, continueResize = true; if ( ce[ 0 ] !== document && ( /static/ ).test( ce.css( "position" ) ) ) { cop = co; } if ( cp.left < ( that._helper ? co.left : 0 ) ) { that.size.width = that.size.width + ( that._helper ? ( that.position.left - co.left ) : ( that.position.left - cop.left ) ); if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } that.position.left = o.helper ? co.left : 0; } if ( cp.top < ( that._helper ? co.top : 0 ) ) { that.size.height = that.size.height + ( that._helper ? ( that.position.top - co.top ) : that.position.top ); if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left + that.position.left; that.offset.top = that.parentData.top + that.position.top; woset = Math.abs( ( that._helper ? that.offset.left - cop.left : ( that.offset.left - co.left ) ) + that.sizeDiff.width ); hoset = Math.abs( ( that._helper ? that.offset.top - cop.top : ( that.offset.top - co.top ) ) + that.sizeDiff.height ); isParent = that.containerElement.get( 0 ) === that.element.parent().get( 0 ); isOffsetRelative = /relative|absolute/.test( that.containerElement.css( "position" ) ); if ( isParent && isOffsetRelative ) { woset -= Math.abs( that.parentData.left ); } if ( woset + that.size.width >= that.parentData.width ) { that.size.width = that.parentData.width - woset; if ( pRatio ) { that.size.height = that.size.width / that.aspectRatio; continueResize = false; } } if ( hoset + that.size.height >= that.parentData.height ) { that.size.height = that.parentData.height - hoset; if ( pRatio ) { that.size.width = that.size.height * that.aspectRatio; continueResize = false; } } if ( !continueResize ){ that.position.left = ui.prevPosition.left; that.position.top = ui.prevPosition.top; that.size.width = ui.prevSize.width; that.size.height = ui.prevSize.height; } }, stop: function(){ var that = $( this ).resizable( "instance" ), o = that.options, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement, helper = $( that.helper ), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if ( that._helper && !o.animate && ( /relative/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } if ( that._helper && !o.animate && ( /static/ ).test( ce.css( "position" ) ) ) { $( this ).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } } }); $.ui.plugin.add("resizable", "alsoResize", { start: function () { var that = $(this).resizable( "instance" ), o = that.options, _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("ui-resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css("left"), 10), top: parseInt(el.css("top"), 10) }); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).resizable( "instance" ), o = that.options, os = that.originalSize, op = that.originalPosition, delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("ui-resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ["width", "height"] : ["width", "height", "top", "left"]; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) { style[prop] = sum || null; } }); el.css(style); }); }; if (typeof(o.alsoResize) === "object" && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function () { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "ghost", { start: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: 0.25, display: "block", position: "relative", height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass("ui-resizable-ghost") .addClass(typeof o.ghost === "string" ? o.ghost : ""); that.ghost.appendTo(that.helper); }, resize: function(){ var that = $(this).resizable( "instance" ); if (that.ghost) { that.ghost.css({ position: "relative", height: that.size.height, width: that.size.width }); } }, stop: function() { var that = $(this).resizable( "instance" ); if (that.ghost && that.helper) { that.helper.get(0).removeChild(that.ghost.get(0)); } } }); $.ui.plugin.add("resizable", "grid", { resize: function() { var that = $(this).resizable( "instance" ), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, grid = typeof o.grid === "number" ? [o.grid, o.grid] : o.grid, gridX = (grid[0]||1), gridY = (grid[1]||1), ox = Math.round((cs.width - os.width) / gridX) * gridX, oy = Math.round((cs.height - os.height) / gridY) * gridY, newWidth = os.width + ox, newHeight = os.height + oy, isMaxWidth = o.maxWidth && (o.maxWidth < newWidth), isMaxHeight = o.maxHeight && (o.maxHeight < newHeight), isMinWidth = o.minWidth && (o.minWidth > newWidth), isMinHeight = o.minHeight && (o.minHeight > newHeight); o.grid = grid; if (isMinWidth) { newWidth = newWidth + gridX; } if (isMinHeight) { newHeight = newHeight + gridY; } if (isMaxWidth) { newWidth = newWidth - gridX; } if (isMaxHeight) { newHeight = newHeight - gridY; } if (/^(se|s|e)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; } else if (/^(ne)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = newWidth; that.size.height = newHeight; that.position.left = op.left - ox; } else { if ( newHeight - gridY > 0 ) { that.size.height = newHeight; that.position.top = op.top - oy; } else { that.size.height = gridY; that.position.top = op.top + os.height - gridY; } if ( newWidth - gridX > 0 ) { that.size.width = newWidth; that.position.left = op.left - ox; } else { that.size.width = gridX; that.position.left = op.left + os.width - gridX; } } } }); return $.ui.resizable; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget("ui.selectable", $.ui.mouse, { version: "1.11.0", options: { appendTo: "body", autoRefresh: true, distance: 0, filter: "*", tolerance: "touch", // callbacks selected: null, selecting: null, start: null, stop: null, unselected: null, unselecting: null }, _create: function() { var selectees, that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this), pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass("ui-selected"), selecting: $this.hasClass("ui-selecting"), unselecting: $this.hasClass("ui-unselecting") }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this, options = this.options; this.opos = [ event.pageX, event.pageY ]; if (this.options.disabled) { return; } this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.pageX, "top": event.pageY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter(".ui-selected").each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().addBack().each(function() { var doSelect, selectee = $.data(this, "selectable-item"); if (selectee) { doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass("ui-selected"); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { this.dragged = true; if (this.options.disabled) { return; } var tmp, that = this, options = this.options, x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({ left: x1, top: y1, width: x2 - x1, height: y2 - y1 }); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"), hit = false; //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element === that.element[0]) { return; } if (options.tolerance === "touch") { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance === "fit") { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass("ui-selecting"); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; selectee.$element.addClass("ui-selected"); selectee.selected = true; } else { selectee.$element.removeClass("ui-selecting"); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass("ui-selected"); selectee.selected = false; selectee.$element.addClass("ui-unselecting"); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; $(".ui-unselecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-unselecting"); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $(".ui-selecting", this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass("ui-selecting").addClass("ui-selected"); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget("ui.sortable", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "sort", ready: false, options: { appendTo: "parent", axis: false, connectWith: false, containment: false, cursor: "auto", cursorAt: false, dropOnEmpty: true, forcePlaceholderSize: false, forceHelperSize: false, grid: false, handle: false, helper: "original", items: "> *", opacity: false, placeholder: false, revert: false, scroll: true, scrollSensitivity: 20, scrollSpeed: 20, scope: "default", tolerance: "intersect", zIndex: 1000, // callbacks activate: null, beforeStop: null, change: null, deactivate: null, out: null, over: null, receive: null, remove: null, sort: null, start: null, stop: null, update: null }, _isOverAxis: function( x, reference, size ) { return ( x >= reference ) && ( x < ( reference + size ) ); }, _isFloating: function( item ) { return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); }, _create: function() { var o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are being displayed horizontally this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); this._setHandleClassName(); //We're ready to go this.ready = true; }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "handle" ) { this._setHandleClassName(); } }, _setHandleClassName: function() { this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" ); $.each( this.items, function() { ( this.instance.options.handle ? this.item.find( this.instance.options.handle ) : this.item ) .addClass( "ui-sortable-handle" ); }); }, _destroy: function() { this.element .removeClass( "ui-sortable ui-sortable-disabled" ) .find( ".ui-sortable-handle" ) .removeClass( "ui-sortable-handle" ); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) { this.items[i].item.removeData(this.widgetName + "-item"); } return this; }, _mouseCapture: function(event, overrideHandle) { var currentItem = null, validHandle = false, that = this; if (this.reverting) { return false; } if(this.options.disabled || this.options.type === "static") { return false; } //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items $(event.target).parents().each(function() { if($.data(this, that.widgetName + "-item") === that) { currentItem = $(this); return false; } }); if($.data(event.target, that.widgetName + "-item") === that) { currentItem = $(event.target); } if(!currentItem) { return false; } if(this.options.handle && !overrideHandle) { $(this.options.handle, currentItem).find("*").addBack().each(function() { if(this === event.target) { validHandle = true; } }); if(!validHandle) { return false; } } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var i, body, o = this.options; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if "cursorAt" is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] !== this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) { this._setContainment(); } if( o.cursor && o.cursor !== "auto" ) { // cursor option body = this.document.find( "body" ); // support: IE this.storedCursor = body.css( "cursor" ); body.css( "cursor", o.cursor ); this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body ); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) { this._storedOpacity = this.helper.css("opacity"); } this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) { this._storedZIndex = this.helper.css("zIndex"); } this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { this.overflowOffset = this.scrollParent.offset(); } //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) { this._cacheHelperProportions(); } //Post "activate" events to possible containers if( !noActivation ) { for ( i = this.containers.length - 1; i >= 0; i-- ) { this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); } } //Prepare possible droppables if($.ui.ddmanager) { $.ui.ddmanager.current = this; } if ($.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { var i, item, itemElement, intersection, o = this.options, scrolled = false; //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; } if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { $.ui.ddmanager.prepareOffsets(this, event); } } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper position if(!this.options.axis || this.options.axis !== "y") { this.helper[0].style.left = this.position.left+"px"; } if(!this.options.axis || this.options.axis !== "x") { this.helper[0].style.top = this.position.top+"px"; } //Rearrange for (i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection item = this.items[i]; itemElement = item.item[0]; intersection = this._intersectsWithPointer(item); if (!intersection) { continue; } // Only put the placeholder inside the current Container, skip all // items from other containers. This works because when moving // an item from one container to another the // currentContainer is switched before the placeholder is moved. // // Without this, moving items in "sub-sortables" can cause // the placeholder to jitter between the outer and inner container. if (item.instance !== this.currentContainer) { continue; } // cannot intersect with itself // no useless actions that have been done before // no action if the item moved is the parent of the item checked if (itemElement !== this.currentItem[0] && this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && !$.contains(this.placeholder[0], itemElement) && (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) ) { this.direction = intersection === 1 ? "down" : "up"; if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) { $.ui.ddmanager.drag(this, event); } //Call callbacks this._trigger("sort", event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) { return; } //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) { $.ui.ddmanager.drop(this, event); } if(this.options.revert) { var that = this, cur = this.placeholder.offset(), axis = this.options.axis, animation = {}; if ( !axis || axis === "x" ) { animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); } if ( !axis || axis === "y" ) { animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); } this.reverting = true; $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { that._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { if(this.dragging) { this._mouseUp({ target: null }); if(this.options.helper === "original") { this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, this._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } if (this.placeholder) { //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! if(this.placeholder[0].parentNode) { this.placeholder[0].parentNode.removeChild(this.placeholder[0]); } if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { this.helper.remove(); } $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } } return this; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected), str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); if (res) { str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); } }); if(!str.length && o.key) { str.push(o.key + "="); } return str.join("&"); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected), ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height, l = item.left, r = l + item.width, t = item.top, b = t + item.height, dyClick = this.offset.click.top, dxClick = this.offset.click.left, isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), isOverElement = isOverElementHeight && isOverElementWidth; if ( this.options.tolerance === "pointer" || this.options.forcePointerForContainers || (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) && // Right Half x2 - (this.helperProportions.width / 2) < r && // Left Half t < y1 + (this.helperProportions.height / 2) && // Bottom Half y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) { return false; } return this.floating ? ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta !== 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta !== 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this._setHandleClassName(); this.refreshPositions(); return this; }, _connectWith: function() { var options = this.options; return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var i, j, cur, inst, items = [], queries = [], connectWith = this._connectWith(); if(connectWith && connected) { for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for ( j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); } } } } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); function addItems() { items.push( this ); } for (i = queries.length - 1; i >= 0; i--){ queries[i][0].each( addItems ); } return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); this.items = $.grep(this.items, function (item) { for (var j=0; j < list.length; j++) { if(list[j] === item.item[0]) { return false; } } return true; }); }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var i, j, cur, inst, targetData, _queries, item, queriesLength, items = this.items, queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (i = connectWith.length - 1; i >= 0; i--){ cur = $(connectWith[i]); for (j = cur.length - 1; j >= 0; j--){ inst = $.data(cur[j], this.widgetFullName); if(inst && inst !== this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } } } } for (i = queries.length - 1; i >= 0; i--) { targetData = queries[i][1]; _queries = queries[i][0]; for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { item = $(_queries[j]); item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); } } }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } var i, item, t, p; for (i = this.items.length - 1; i >= 0; i--){ item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { continue; } t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } p = t.offset(); item.left = p.left; item.top = p.top; } if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (i = this.containers.length - 1; i >= 0; i--){ p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); } } return this; }, _createPlaceholder: function(that) { that = that || this; var className, o = that.options; if(!o.placeholder || o.placeholder.constructor === String) { className = o.placeholder; o.placeholder = { element: function() { var nodeName = that.currentItem[0].nodeName.toLowerCase(), element = $( "<" + nodeName + ">", that.document[0] ) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper"); if ( nodeName === "tr" ) { that.currentItem.children().each(function() { $( "<td> </td>", that.document[0] ) .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) .appendTo( element ); }); } else if ( nodeName === "img" ) { element.attr( "src", that.currentItem.attr( "src" ) ); } if ( !className ) { element.css( "visibility", "hidden" ); } return element; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) { return; } //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } } }; } //Create the placeholder that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); //Append it after the actual current item that.currentItem.after(that.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(that, that.placeholder); }, _contactContainers: function(event) { var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis, innermostContainer = null, innermostIndex = null; // get innermost container that intersects with item for (i = this.containers.length - 1; i >= 0; i--) { // never consider a container that's located within the item itself if($.contains(this.currentItem[0], this.containers[i].element[0])) { continue; } if(this._intersectsWith(this.containers[i].containerCache)) { // if we've already found a container and it's more "inner" than this, then continue if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { continue; } innermostContainer = this.containers[i]; innermostIndex = i; } else { // container doesn't intersect. trigger "out" event if necessary if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } // if no intersecting containers found, return if(!innermostContainer) { return; } // move the item into the container if it's not there already if(this.containers.length === 1) { if (!this.containers[innermostIndex].containerCache.over) { this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } } else { //When entering a new container, we will find the item with the least distance and append our item near it dist = 10000; itemWithLeastDistance = null; floating = innermostContainer.floating || this._isFloating(this.currentItem); posProperty = floating ? "left" : "top"; sizeProperty = floating ? "width" : "height"; axis = floating ? "clientX" : "clientY"; for (j = this.items.length - 1; j >= 0; j--) { if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { continue; } if(this.items[j].item[0] === this.currentItem[0]) { continue; } cur = this.items[j].item.offset()[posProperty]; nearBottom = false; if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) { nearBottom = true; } if ( Math.abs( event[ axis ] - cur ) < dist ) { dist = Math.abs( event[ axis ] - cur ); itemWithLeastDistance = this.items[ j ]; this.direction = nearBottom ? "up": "down"; } } //Check if dropOnEmpty is enabled if(!itemWithLeastDistance && !this.options.dropOnEmpty) { return; } if(this.currentContainer === this.containers[innermostIndex]) { return; } itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); this._trigger("change", event, this._uiHash()); this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); this.currentContainer = this.containers[innermostIndex]; //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } }, _createHelper: function(event) { var o = this.options, helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); //Add the helper to the DOM if that didn't happen already if(!helper.parents("body").length) { $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); } if(helper[0] === this.currentItem[0]) { this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; } if(!helper[0].style.width || o.forceHelperSize) { helper.width(this.currentItem.width()); } if(!helper[0].style.height || o.forceHelperSize) { helper.height(this.currentItem.height()); } return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj === "string") { obj = obj.split(" "); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ("left" in obj) { this.offset.click.left = obj.left + this.margins.left; } if ("right" in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ("top" in obj) { this.offset.click.top = obj.top + this.margins.top; } if ("bottom" in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } // This needs to be actually done for all browsers, since pageX/pageY includes this information // with an ugly IE fix if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { po = { top: 0, left: 0 }; } return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition === "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() }; } else { return { top: 0, left: 0 }; } }, _cacheMargins: function() { this.margins = { left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), top: (parseInt(this.currentItem.css("marginTop"),10) || 0) }; }, _cacheHelperProportions: function() { this.helperProportions = { width: this.helper.outerWidth(), height: this.helper.outerHeight() }; }, _setContainment: function() { var ce, co, over, o = this.options; if(o.containment === "parent") { o.containment = this.helper[0].parentNode; } if(o.containment === "document" || o.containment === "window") { this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; } if(!(/^(document|window|parent)$/).test(o.containment)) { ce = $(o.containment)[0]; co = $(o.containment).offset(); over = ($(ce).css("overflow") !== "hidden"); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) { pos = this.position; } var mod = d === "absolute" ? 1 : -1, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top + // The absolute mouse position this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left + // The absolute mouse position this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var top, left, o = this.options, pageX = event.pageX, pageY = event.pageY, scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) { pageX = this.containment[0] + this.offset.click.left; } if(event.pageY - this.offset.click.top < this.containment[1]) { pageY = this.containment[1] + this.offset.click.top; } if(event.pageX - this.offset.click.left > this.containment[2]) { pageX = this.containment[2] + this.offset.click.left; } if(event.pageY - this.offset.click.top > this.containment[3]) { pageY = this.containment[3] + this.offset.click.top; } } if(o.grid) { top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY - // The absolute mouse position this.offset.click.top - // Click offset (relative to the element) this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.top + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX - // The absolute mouse position this.offset.click.left - // Click offset (relative to the element) this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent this.offset.parent.left + // The offsetParent's offset without borders (offset + border) ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var counter = this.counter; this._delay(function() { if(counter === this.counter) { this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove } }); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var i, delayedTriggers = []; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem.parent().length) { this.placeholder.before(this.currentItem); } this._noFinalSort = null; if(this.helper[0] === this.currentItem[0]) { for(i in this._storedCSS) { if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { this._storedCSS[i] = ""; } } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); } if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed } // Check if the items Container has Changed and trigger appropriate // events. if (this !== this.currentContainer) { if(!noPropagation) { delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); } } //Post events to containers function delayEvent( type, instance, container ) { return function( event ) { container._trigger( type, event, instance._uiHash( instance ) ); }; } for (i = this.containers.length - 1; i >= 0; i--){ if (!noPropagation) { delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) ); } if(this.containers[i].containerCache.over) { delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) ); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if ( this.storedCursor ) { this.document.find( "body" ).css( "cursor", this.storedCursor ); this.storedStylesheet.remove(); } if(this._storedOpacity) { this.helper.css("opacity", this._storedOpacity); } if(this._storedZIndex) { this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); } this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return false; } if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); } //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.helper[0] !== this.currentItem[0]) { this.helper.remove(); } this.helper = null; if(!noPropagation) { for (i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); } //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return true; }, _trigger: function() { if ($.Widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(_inst) { var inst = _inst || this; return { helper: inst.helper, placeholder: inst.placeholder || $([]), position: inst.position, originalPosition: inst.originalPosition, offset: inst.positionAbs, item: inst.currentItem, sender: _inst ? _inst.element : null }; } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var dataSpace = "ui-effects-"; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.1.2 * https://github.com/jquery/jquery-color * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Wed Jan 16 08:47:09 2013 -0600 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor", // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [ { re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d?(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } } ], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && jQuery.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + ( q - p ) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + ( q - p ) * ( ( 2 / 3 ) - h ) * 6; } return p; } spaces.hsla.to = function( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } // chroma (diff) == 0 means greyscale which, by definition, saturation = 0% // otherwise, saturation is based on the ratio of chroma (diff) to lightness (add) if ( diff === 0 ) { s = 0; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add cssHook and .fx.step function for each named hook. // accept a space separated string of properties color.hook = function( hook ) { var hooks = hook.split( " " ); each( hooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( value !== "transparent" && ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch( e ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); }; color.hook( stepHooks ); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles( elem ) { var key, len, style = elem.ownerDocument.defaultView ? elem.ownerDocument.defaultView.getComputedStyle( elem, null ) : elem.currentStyle, styles = {}; if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { styles[ $.camelCase( key ) ] = style[ key ]; } } // support: Opera, IE <9 } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { styles[ key ] = style[ key ]; } } } return styles; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } // support: jQuery <1.8 if ( !$.fn.addBack ) { $.fn.addBack = function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); }; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).addBack() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = $.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, "" ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ addClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.addClass ), removeClass: (function( orig ) { return function( classNames, speed, easing, callback ) { return arguments.length > 1 ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : orig.apply( this, arguments ); }; })( $.fn.removeClass ), toggleClass: (function( orig ) { return function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return orig.apply( this, arguments ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }; })( $.fn.toggleClass ), switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.11.0", // Saves a set of properties in a data storage save: function( element, set ) { for ( var i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for ( i = 0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardAnimationOption( option ) { // Valid standard speeds (nothing, number, named speed) if ( !option || typeof option === "number" || $.fx.speeds[ option ] ) { return true; } // Invalid strings - treat as "normal" speed if ( typeof option === "string" && !$.effects.effect[ option ] ) { return true; } // Complete callback if ( $.isFunction( option ) ) { return true; } // Options hash (but not naming an effect) if ( typeof option === "object" && !option.effect ) { return true; } // Didn't match any standard API return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ]; if ( $.fx.off || !effectMethod ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // If the element already has the correct final state, delegate to // the core methods so the internal tracking of "olddisplay" works. if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { elem[ mode ](); done(); } else { effectMethod.call( elem[0], args, done ); } } return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); }, show: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }; })( $.fn.show ), hide: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }; })( $.fn.hide ), toggle: (function( orig ) { return function( option ) { if ( standardAnimationOption( option ) || typeof option === "boolean" ) { return orig.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }; })( $.fn.toggle ), // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); return $.effects; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.accordion", { version: "1.11.0", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, hideProps: { borderTopWidth: "hide", borderBottomWidth: "hide", paddingTop: "hide", paddingBottom: "hide", height: "hide" }, showProps: { borderTopWidth: "show", borderBottomWidth: "show", paddingTop: "show", paddingBottom: "show", height: "show" }, _create: function() { var options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ) // ARIA .attr( "role", "tablist" ); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } this._processPanels(); // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this._refresh(); }, _getCreateEventData: function() { return { header: this.active, panel: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-state-default " + "ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this._destroyIcons(); // clean up content panels contents = this.headers.next() .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom " + "ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeUniqueId(); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown: function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var options = this.options; this._processPanels(); // was collapsed or no panel if ( ( options.active === false && options.collapsible === true ) || !this.headers.length ) { options.active = false; this.active = $(); // active false only when collapsible is true } else if ( options.active === false ) { this._activate( 0 ); // was active, but active panel is gone } else if ( this.active.length && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { // all remaining panel are disabled if ( this.headers.length === this.headers.find(".ui-state-disabled").length ) { options.active = false; this.active = $(); // activate previous panel } else { this._activate( Math.max( 0, options.active - 1 ) ); } // was active, active panel still exists } else { // make sure active index is correct options.active = this.headers.index( this.active ); } this._destroyIcons(); this._refresh(); }, _processPanels: function() { this.headers = this.element.find( this.options.header ) .addClass( "ui-accordion-header ui-state-default ui-corner-all" ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .filter( ":not(.ui-accordion-content-active)" ) .hide(); }, _refresh: function() { var maxHeight, options = this.options, heightStyle = options.heightStyle, parent = this.element.parent(); this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ) .removeClass( "ui-corner-all" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this.headers .attr( "role", "tab" ) .each(function() { var header = $( this ), headerId = header.uniqueId().attr( "id" ), panel = header.next(), panelId = panel.uniqueId().attr( "id" ); header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }) .next() .attr({ "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }) .next() .attr({ "aria-hidden": "false" }); } this._createIcons(); this._setupEvents( options.event ); if ( heightStyle === "fill" ) { maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = { keydown: "_keydown" }; if ( event ) { $.each( event.split( " " ), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.headers.add( this.headers.next() ) ); this._on( this.headers, events ); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._hoverable( this.headers ); this._focusable( this.headers ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr({ "tabIndex": -1, "aria-expanded": "false" }); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr( "aria-hidden", "false" ) .prev() .attr({ "aria-selected": "true", tabIndex: 0, "aria-expanded": "true" }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( this.showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( this.hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( this.hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( this.showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[ 0 ].className = toHide.parent()[ 0 ].className; } this._trigger( "activate", null, data ); } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./position", "./menu" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.widget( "ui.autocomplete", { version: "1.11.0", defaultElement: "<input>", options: { appendTo: null, autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, requestIndex: 0, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput, nodeName = this.element[ 0 ].nodeName.toLowerCase(), isTextarea = nodeName === "textarea", isInput = nodeName === "input"; this.isMultiLine = // Textareas are always multi-line isTextarea ? true : // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable isInput ? false : // All other element types are determined by whether or not they're contentEditable this.element.prop( "isContentEditable" ); this.valueMethod = this.element[ isTextarea || isInput ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { this._value( this.term ); this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { event.preventDefault(); } return; } if ( suppressKeyPressRepeat ) { return; } // replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } }); this._initSource(); this.menu = $( "<ul>" ) .addClass( "ui-autocomplete ui-front" ) .appendTo( this._appendTo() ) .menu({ // disable ARIA support, the live region takes care of that role: null }) .hide() .menu( "instance" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; }); // clicking on the scrollbar causes focus to shift to the body // but we can't detect a mouseup or a click immediately afterward // so we have to track the next mousedown and close the menu if // the user clicks somewhere outside of the autocomplete var menuElement = this.menu.element[ 0 ]; if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { this._delay(function() { var that = this; this.document.one( "mousedown", function( event ) { if ( event.target !== that.element[ 0 ] && event.target !== menuElement && !$.contains( menuElement, event.target ) ) { that.close(); } }); }); } }, menufocus: function( event, ui ) { var label, item; // support: Firefox // Prevent accidental activation of menu items in Firefox (#7024 #9118) if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); }); return; } } item = ui.item.data( "ui-autocomplete-item" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } // Announce the value in the liveRegion label = ui.item.attr( "aria-label" ) || item.value; if ( label && jQuery.trim( label ).length ) { this.liveRegion.children().hide(); $( "<div>" ).text( label ).appendTo( this.liveRegion ); } }, menuselect: function( event, ui ) { var item = ui.item.data( "ui-autocomplete-item" ), previous = this.previous; // only trigger when focus was lost (click on menu) if ( this.element[ 0 ] !== this.document[ 0 ].activeElement ) { this.element.focus(); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay(function() { this.previous = previous; this.selectedItem = item; }); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } }); this.liveRegion = $( "<span>", { role: "status", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _destroy: function() { clearTimeout( this.searching ); this.element .removeClass( "ui-autocomplete-input" ) .removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this._appendTo() ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _initSource: function() { var array, url, that = this; if ( $.isArray( this.options.source ) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response([]); } }); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay(function() { // Search if the value has changed, or if the user retypes the same value (see #7434) var equalValues = this.term === this._value(), menuVisible = this.menu.element.is( ":visible" ), modifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey; if ( !equalValues || ( equalValues && !menuVisible && !modifierKey ) ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this.element.addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var index = ++this.requestIndex; return $.proxy(function( content ) { if ( index === this.requestIndex ) { this.__response( content ); } this.pending--; if ( !this.pending ) { this.element.removeClass( "ui-autocomplete-loading" ); } }, this ); }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[ 0 ].label && items[ 0 ].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend( {}, item, { label: item.label || item.value, value: item.value || item.label }); }); }, _suggest: function( items ) { var ul = this.menu.element.empty(); this._renderMenu( ul, items ); this.isNewMenu = true; this.menu.refresh(); // size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend({ of: this.element }, this.options.position ) ); if ( this.options.autoFocus ) { this.menu.next(); } }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ).text( item.label ).appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { if ( !this.isMultiLine ) { this._value( this.term ); } this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } } }); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); }, filter: function( array, term ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex( term ), "i" ); return $.grep( array, function( value ) { return matcher.test( value.label || value.value || value ); }); } }); // live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.children().hide(); $( "<div>" ).text( message ).appendTo( this.liveRegion ); } }); return $.ui.autocomplete; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { var lastActive, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only", formResetHandler = function() { var form = $( this ); setTimeout(function() { form.find( ":ui-button" ).button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { name = name.replace( /'/g, "\\'" ); if ( form ) { radios = $( form ).find( "[name='" + name + "'][type=radio]" ); } else { radios = $( "[name='" + name + "'][type=radio]", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "1.11.0", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : ""; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); // Can't use _focusable() because the element that receives focus // and the element that gets the ui-state-focus class are different this._on({ focus: function() { this.buttonElement.addClass( "ui-state-focus" ); }, blur: function() { this.buttonElement.removeClass( "ui-state-focus" ); } }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { that.refresh(); }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) // see #8559, we bind to blur here in case the button element loses // focus between keydown and keyup, it would be left in an "active" state .bind( "keyup" + this.eventNamespace + " blur" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " ui-state-active " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); if ( value ) { if ( this.type === "checkbox" || this.type === "radio" ) { this.buttonElement.removeClass( "ui-state-focus" ); } else { this.buttonElement.removeClass( "ui-state-focus ui-state-active" ); } } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( this ).button( "widget" ) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } }); } else if ( this.type === "checkbox" ) { if ( this.element.is( ":checked" ) ) { this.buttonElement .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { this.buttonElement .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); } } }, _resetButton: function() { if ( this.type === "input" ) { if ( this.options.label ) { this.element.val( this.options.label ); } return; } var buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "1.11.0", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(ui-button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = this.element.css( "direction" ) === "rtl", allButtons = this.element.find( this.options.items ), existingButtons = allButtons.filter( ":ui-button" ); // Initialize new buttons allButtons.not( ":ui-button" ).button(); // Refresh existing buttons existingButtons.button( "refresh" ); this.buttons = allButtons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); return $.ui.button; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.extend($.ui, { datepicker: { version: "1.11.0" } }); var datepicker_instActive; function datepicker_getZindex( elem ) { var position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } return 0; } /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class this._appendClass = "ui-datepicker-append"; // The name of the append marker class this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[""] = { // Default regional settings closeText: "Done", // Display text for close link prevText: "Prev", // Display text for previous month link nextText: "Next", // Display text for next month link currentText: "Today", // Display text for current month link monthNames: ["January","February","March","April","May","June", "July","August","September","October","November","December"], // Names of months for drop-down and formatting monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday weekHeader: "Wk", // Column header for week of the year dateFormat: "mm/dd/yy", // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: "" // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: "focus", // "focus" for popup on focus, // "button" for trigger button, or "both" for either showAnim: "fadeIn", // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: "", // Display text following the input box, e.g. showing the format buttonText: "...", // Text for trigger button buttonImage: "", // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: "c-10:c+10", // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: "+10", // Short year values < this are in the current century, // > this are in the previous century, // string value starting with "+" for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: "fast", // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "", // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: "", // Selector for an alternate field to store selected dates into altFormat: "", // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.extend(this._defaults, this.regional[""]); this.regional.en = $.extend( true, {}, this.regional[ "" ]); this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en ); this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")); } $.extend(Datepicker.prototype, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: "hasDatepicker", //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. * @param settings object - the new settings to use as defaults (anonymous object) * @return the manager object */ setDefaults: function(settings) { datepicker_extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. * @param target element - the target input field or division or span * @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { var nodeName, inline, inst; nodeName = target.nodeName.toLowerCase(); inline = (nodeName === "div" || nodeName === "span"); if (!target.id) { this.uuid += 1; target.id = "dp" + this.uuid; } inst = this._newInst($(target), inline); inst.settings = $.extend({}, settings || {}); if (nodeName === "input") { this._connectDatepicker(target, inst); } else if (inline) { this._inlineDatepicker(target, inst); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))}; }, /* Attach the date picker to an input field. */ _connectDatepicker: function(target, inst) { var input = $(target); inst.append = $([]); inst.trigger = $([]); if (input.hasClass(this.markerClassName)) { return; } this._attachments(input, inst); input.addClass(this.markerClassName).keydown(this._doKeyDown). keypress(this._doKeyPress).keyup(this._doKeyUp); this._autoSize(inst); $.data(target, "datepicker", inst); //If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _attachments: function(input, inst) { var showOn, buttonText, buttonImage, appendText = this._get(inst, "appendText"), isRTL = this._get(inst, "isRTL"); if (inst.append) { inst.append.remove(); } if (appendText) { inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>"); input[isRTL ? "before" : "after"](inst.append); } input.unbind("focus", this._showDatepicker); if (inst.trigger) { inst.trigger.remove(); } showOn = this._get(inst, "showOn"); if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field input.focus(this._showDatepicker); } if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked buttonText = this._get(inst, "buttonText"); buttonImage = this._get(inst, "buttonImage"); inst.trigger = $(this._get(inst, "buttonImageOnly") ? $("<img/>").addClass(this._triggerClass). attr({ src: buttonImage, alt: buttonText, title: buttonText }) : $("<button type='button'></button>").addClass(this._triggerClass). html(!buttonImage ? buttonText : $("<img/>").attr( { src:buttonImage, alt:buttonText, title:buttonText }))); input[isRTL ? "before" : "after"](inst.trigger); inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) { $.datepicker._hideDatepicker(); } else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) { $.datepicker._hideDatepicker(); $.datepicker._showDatepicker(input[0]); } else { $.datepicker._showDatepicker(input[0]); } return false; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, "autoSize") && !inst.inline) { var findMax, max, maxI, i, date = new Date(2009, 12 - 1, 20), // Ensure double digits dateFormat = this._get(inst, "dateFormat"); if (dateFormat.match(/[DM]/)) { findMax = function(names) { max = 0; maxI = 0; for (i = 0; i < names.length; i++) { if (names[i].length > max) { max = names[i].length; maxI = i; } } return maxI; }; date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ? "monthNames" : "monthNamesShort")))); date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ? "dayNames" : "dayNamesShort"))) + 20 - date.getDay()); } inst.input.attr("size", this._formatDate(inst, date).length); } }, /* Attach an inline date picker to a div. */ _inlineDatepicker: function(target, inst) { var divSpan = $(target); if (divSpan.hasClass(this.markerClassName)) { return; } divSpan.addClass(this.markerClassName).append(inst.dpDiv); $.data(target, "datepicker", inst); this._setDate(inst, this._getDefaultDate(inst), true); this._updateDatepicker(inst); this._updateAlternate(inst); //If disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. * @param input element - ignored * @param date string or Date - the initial date to display * @param onSelect function - the function to call when a date is selected * @param settings object - update the dialog date picker instance's settings (anonymous object) * @param pos int[2] - coordinates for the dialog's position within the screen or * event - with x/y coordinates or * leave empty for default (screen centre) * @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var id, browserWidth, browserHeight, scrollX, scrollY, inst = this._dialogInst; // internal instance if (!inst) { this.uuid += 1; id = "dp" + this.uuid; this._dialogInput = $("<input type='text' id='" + id + "' style='position: absolute; top: -100px; width: 0px;'/>"); this._dialogInput.keydown(this._doKeyDown); $("body").append(this._dialogInput); inst = this._dialogInst = this._newInst(this._dialogInput, false); inst.settings = {}; $.data(this._dialogInput[0], "datepicker", inst); } datepicker_extendRemove(inst.settings, settings || {}); date = (date && date.constructor === Date ? this._formatDate(inst, date) : date); this._dialogInput.val(date); this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null); if (!this._pos) { browserWidth = document.documentElement.clientWidth; browserHeight = document.documentElement.clientHeight; scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; scrollY = document.documentElement.scrollTop || document.body.scrollTop; this._pos = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px"); inst.settings.onSelect = onSelect; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]); if ($.blockUI) { $.blockUI(this.dpDiv); } $.data(this._dialogInput[0], "datepicker", inst); return this; }, /* Detach a datepicker from its control. * @param target element - the target input field or division or span */ _destroyDatepicker: function(target) { var nodeName, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); $.removeData(target, "datepicker"); if (nodeName === "input") { inst.append.remove(); inst.trigger.remove(); $target.removeClass(this.markerClassName). unbind("focus", this._showDatepicker). unbind("keydown", this._doKeyDown). unbind("keypress", this._doKeyPress). unbind("keyup", this._doKeyUp); } else if (nodeName === "div" || nodeName === "span") { $target.removeClass(this.markerClassName).empty(); } }, /* Enable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _enableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = false; inst.trigger.filter("button"). each(function() { this.disabled = false; }).end(). filter("img").css({opacity: "1.0", cursor: ""}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().removeClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. * @param target element - the target input field or division or span */ _disableDatepicker: function(target) { var nodeName, inline, $target = $(target), inst = $.data(target, "datepicker"); if (!$target.hasClass(this.markerClassName)) { return; } nodeName = target.nodeName.toLowerCase(); if (nodeName === "input") { target.disabled = true; inst.trigger.filter("button"). each(function() { this.disabled = true; }).end(). filter("img").css({opacity: "0.5", cursor: "default"}); } else if (nodeName === "div" || nodeName === "span") { inline = $target.children("." + this._inlineClass); inline.children().addClass("ui-state-disabled"); inline.find("select.ui-datepicker-month, select.ui-datepicker-year"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value === target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? * @param target element - the target input field or division or span * @return boolean - true if disabled, false if enabled */ _isDisabledDatepicker: function(target) { if (!target) { return false; } for (var i = 0; i < this._disabledInputs.length; i++) { if (this._disabledInputs[i] === target) { return true; } } return false; }, /* Retrieve the instance data for the target control. * @param target element - the target input field or division or span * @return object - the associated instance data * @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, "datepicker"); } catch (err) { throw "Missing instance data for this datepicker"; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. * @param target element - the target input field or division or span * @param name object - the new settings to update or * string - the name of the setting to change or retrieve, * when retrieving also "all" for all instance settings or * "defaults" for all global defaults * @param value any - the new value for the setting * (omit if above is an object or to retrieve a value) */ _optionDatepicker: function(target, name, value) { var settings, date, minDate, maxDate, inst = this._getInst(target); if (arguments.length === 2 && typeof name === "string") { return (name === "defaults" ? $.extend({}, $.datepicker._defaults) : (inst ? (name === "all" ? $.extend({}, inst.settings) : this._get(inst, name)) : null)); } settings = name || {}; if (typeof name === "string") { settings = {}; settings[name] = value; } if (inst) { if (this._curInst === inst) { this._hideDatepicker(); } date = this._getDateDatepicker(target, true); minDate = this._getMinMaxDate(inst, "min"); maxDate = this._getMinMaxDate(inst, "max"); datepicker_extendRemove(inst.settings, settings); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) { inst.settings.minDate = this._formatDate(inst, minDate); } if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) { inst.settings.maxDate = this._formatDate(inst, maxDate); } if ( "disabled" in settings ) { if ( settings.disabled ) { this._disableDatepicker(target); } else { this._enableDatepicker(target); } } this._attachments($(target), inst); this._autoSize(inst); this._setDate(inst, date); this._updateAlternate(inst); this._updateDatepicker(inst); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. * @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. * @param target element - the target input field or division or span * @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. * @param target element - the target input field or division or span * @param noDefault boolean - true if no default date is to be used * @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) { this._setDateFromField(inst, noDefault); } return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _doKeyDown: function(event) { var onSelect, dateStr, sel, inst = $.datepicker._getInst(event.target), handled = true, isRTL = inst.dpDiv.is(".ui-datepicker-rtl"); inst._keyEvent = true; if ($.datepicker._datepickerShowing) { switch (event.keyCode) { case 9: $.datepicker._hideDatepicker(); handled = false; break; // hide on tab out case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." + $.datepicker._currentClass + ")", inst.dpDiv); if (sel[0]) { $.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]); } onSelect = $.datepicker._get(inst, "onSelect"); if (onSelect) { dateStr = $.datepicker._formatDate(inst); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else { $.datepicker._hideDatepicker(); } return false; // don't submit the form case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) { $.datepicker._clearDate(event.target); } handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) { $.datepicker._gotoToday(event.target); } handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D"); } handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, "stepBigMonths") : -$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, -7, "D"); } handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D"); } handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) { $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, "stepBigMonths") : +$.datepicker._get(inst, "stepMonths")), "M"); } // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) { $.datepicker._adjustDate(event.target, +7, "D"); } handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } } else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home $.datepicker._showDatepicker(this); } else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _doKeyPress: function(event) { var chars, chr, inst = $.datepicker._getInst(event.target); if ($.datepicker._get(inst, "constrainInput")) { chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat")); chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode); return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1); } }, /* Synchronise manual entry and field/alternate field. */ _doKeyUp: function(event) { var date, inst = $.datepicker._getInst(event.target); if (inst.input.val() !== inst.lastVal) { try { date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), (inst.input ? inst.input.val() : null), $.datepicker._getFormatConfig(inst)); if (date) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { } } return true; }, /* Pop-up the date picker for a given input field. * If false returned from beforeShow event handler do not show. * @param input element - the input field attached to the date picker or * event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger input = $("input", input.parentNode)[0]; } if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here return; } var inst, beforeShow, beforeShowSettings, isFixed, offset, showAnim, duration; inst = $.datepicker._getInst(input); if ($.datepicker._curInst && $.datepicker._curInst !== inst) { $.datepicker._curInst.dpDiv.stop(true, true); if ( inst && $.datepicker._datepickerShowing ) { $.datepicker._hideDatepicker( $.datepicker._curInst.input[0] ); } } beforeShow = $.datepicker._get(inst, "beforeShow"); beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {}; if(beforeShowSettings === false){ return; } datepicker_extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) { // hide cursor input.value = ""; } if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css("position") === "fixed"; return !isFixed; }); offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing offset = $.datepicker._checkOffset(inst, offset, isFixed); inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ? "static" : (isFixed ? "fixed" : "absolute")), display: "none", left: offset.left + "px", top: offset.top + "px"}); if (!inst.inline) { showAnim = $.datepicker._get(inst, "showAnim"); duration = $.datepicker._get(inst, "duration"); inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 ); $.datepicker._datepickerShowing = true; if ( $.effects && $.effects.effect[ showAnim ] ) { inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration); } else { inst.dpDiv[showAnim || "show"](showAnim ? duration : null); } if ( $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } $.datepicker._curInst = inst; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) datepicker_instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); inst.dpDiv.find("." + this._dayOverClass + " a"); var origyearshtml, numMonths = this._getNumberOfMonths(inst), cols = numMonths[1], width = 17; inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); if (cols > 1) { inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em"); } inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl"); if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) { inst.input.focus(); } // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, // #6694 - don't focus the input if it's already focused // this breaks the change event in IE // Support: IE and jQuery <1.9 _shouldFocusInput: function( inst ) { return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" ); }, /* Check positioning to remain on screen. */ _checkOffset: function(inst, offset, isFixed) { var dpWidth = inst.dpDiv.outerWidth(), dpHeight = inst.dpDiv.outerHeight(), inputWidth = inst.input ? inst.input.outerWidth() : 0, inputHeight = inst.input ? inst.input.outerHeight() : 0, viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()), viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop()); offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0); offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0; offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0; // now check if datepicker is showing outside window viewport - move to a better place if so. offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? Math.abs(offset.left + dpWidth - viewWidth) : 0); offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? Math.abs(dpHeight + inputHeight) : 0); return offset; }, /* Find an object's position on the screen. */ _findPos: function(obj) { var position, inst = this._getInst(obj), isRTL = this._get(inst, "isRTL"); while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) { obj = obj[isRTL ? "previousSibling" : "nextSibling"]; } position = $(obj).offset(); return [position.left, position.top]; }, /* Hide the date picker from view. * @param input element - the input field attached to the date picker */ _hideDatepicker: function(input) { var showAnim, duration, postProcess, onClose, inst = this._curInst; if (!inst || (input && inst !== $.data(input, "datepicker"))) { return; } if (this._datepickerShowing) { showAnim = this._get(inst, "showAnim"); duration = this._get(inst, "duration"); postProcess = function() { $.datepicker._tidyDialog(inst); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) { inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess); } else { inst.dpDiv[(showAnim === "slideDown" ? "slideUp" : (showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess); } if (!showAnim) { postProcess(); } this._datepickerShowing = false; onClose = this._get(inst, "onClose"); if (onClose) { onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]); } this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if ($.blockUI) { $.unblockUI(); $("body").append(this.dpDiv); } } this._inDialog = false; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar"); }, /* Close date picker if clicked elsewhere. */ _checkExternalClick: function(event) { if (!$.datepicker._curInst) { return; } var $target = $(event.target), inst = $.datepicker._getInst($target[0]); if ( ( ( $target[0].id !== $.datepicker._mainDivId && $target.parents("#" + $.datepicker._mainDivId).length === 0 && !$target.hasClass($.datepicker.markerClassName) && !$target.closest("." + $.datepicker._triggerClass).length && $.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) || ( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) { $.datepicker._hideDatepicker(); } }, /* Adjust one of the date sub-fields. */ _adjustDate: function(id, offset, period) { var target = $(id), inst = this._getInst(target[0]); if (this._isDisabledDatepicker(target[0])) { return; } this._adjustInstDate(inst, offset + (period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _gotoToday: function(id) { var date, target = $(id), inst = this._getInst(target[0]); if (this._get(inst, "gotoCurrent") && inst.currentDay) { inst.selectedDay = inst.currentDay; inst.drawMonth = inst.selectedMonth = inst.currentMonth; inst.drawYear = inst.selectedYear = inst.currentYear; } else { date = new Date(); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); } this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a new month/year. */ _selectMonthYear: function(id, select, period) { var target = $(id), inst = this._getInst(target[0]); inst["selected" + (period === "M" ? "Month" : "Year")] = inst["draw" + (period === "M" ? "Month" : "Year")] = parseInt(select.options[select.selectedIndex].value,10); this._notifyChange(inst); this._adjustDate(target); }, /* Action for selecting a day. */ _selectDay: function(id, month, year, td) { var inst, target = $(id); if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) { return; } inst = this._getInst(target[0]); inst.selectedDay = inst.currentDay = $("a", td).html(); inst.selectedMonth = inst.currentMonth = month; inst.selectedYear = inst.currentYear = year; this._selectDate(id, this._formatDate(inst, inst.currentDay, inst.currentMonth, inst.currentYear)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); this._selectDate(target, ""); }, /* Update the input field with the selected date. */ _selectDate: function(id, dateStr) { var onSelect, target = $(id), inst = this._getInst(target[0]); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (inst.input) { inst.input.val(dateStr); } this._updateAlternate(inst); onSelect = this._get(inst, "onSelect"); if (onSelect) { onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback } else if (inst.input) { inst.input.trigger("change"); // fire the change event } if (inst.inline){ this._updateDatepicker(inst); } else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) !== "object") { inst.input.focus(); // restore focus } this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altFormat, date, dateStr, altField = this._get(inst, "altField"); if (altField) { // update alternate field too altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat"); date = this._getDate(inst); dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst)); $(altField).each(function() { $(this).val(dateStr); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. * @param date Date - the date to customise * @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), ""]; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. * @param date Date - the date to get the week for * @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var time, checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. * See formatDate below for the possible formats. * * @param format string - the expected format of the date * @param value string - the date in the above format * @param settings Object - attributes include: * shortYearCutoff number - the cutoff year for determining the century (optional) * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return Date - the extracted date value or null if value is blank */ parseDate: function (format, value, settings) { if (format == null || value == null) { throw "Invalid arguments"; } value = (typeof value === "object" ? value.toString() : value + ""); if (value === "") { return null; } var iFormat, dim, extra, iValue = 0, shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff, shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp : new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)), dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, year = -1, month = -1, day = -1, doy = -1, literal = false, date, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Extract a number from the string value getNumber = function(match) { var isDoubled = lookAhead(match), size = (match === "@" ? 14 : (match === "!" ? 20 : (match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))), digits = new RegExp("^\\d{1," + size + "}"), num = value.substring(iValue).match(digits); if (!num) { throw "Missing number at position " + iValue; } iValue += num[0].length; return parseInt(num[0], 10); }, // Extract a name from the string value and convert to an index getName = function(match, shortNames, longNames) { var index = -1, names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) { return [ [k, v] ]; }).sort(function (a, b) { return -(a[1].length - b[1].length); }); $.each(names, function (i, pair) { var name = pair[1]; if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) { index = pair[0]; iValue += name.length; return false; } }); if (index !== -1) { return index + 1; } else { throw "Unknown name at position " + iValue; } }, // Confirm that a literal character matches the string value checkLiteral = function() { if (value.charAt(iValue) !== format.charAt(iFormat)) { throw "Unexpected literal at position " + iValue; } iValue++; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { checkLiteral(); } } else { switch (format.charAt(iFormat)) { case "d": day = getNumber("d"); break; case "D": getName("D", dayNamesShort, dayNames); break; case "o": doy = getNumber("o"); break; case "m": month = getNumber("m"); break; case "M": month = getName("M", monthNamesShort, monthNames); break; case "y": year = getNumber("y"); break; case "@": date = new Date(getNumber("@")); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "!": date = new Date((getNumber("!") - this._ticksTo1970) / 10000); year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); break; case "'": if (lookAhead("'")){ checkLiteral(); } else { literal = true; } break; default: checkLiteral(); } } } if (iValue < value.length){ extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } if (year === -1) { year = new Date().getFullYear(); } else if (year < 100) { year += new Date().getFullYear() - new Date().getFullYear() % 100 + (year <= shortYearCutoff ? 0 : -100); } if (doy > -1) { month = 1; day = doy; do { dim = this._getDaysInMonth(year, month - 1); if (day <= dim) { break; } month++; day -= dim; } while (true); } date = this._daylightSavingAdjust(new Date(year, month - 1, day)); if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) { throw "Invalid date"; // E.g. 31/02/00 } return date; }, /* Standard date formats. */ ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601) COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", // RFC 822 TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. * The format can be combinations of the following: * d - day of month (no leading zero) * dd - day of month (two digit) * o - day of year (no leading zeros) * oo - day of year (three digit) * D - day name short * DD - day name long * m - month of year (no leading zero) * mm - month of year (two digit) * M - month name short * MM - month name long * y - year (two digit) * yy - year (four digit) * @ - Unix timestamp (ms since 01/01/1970) * ! - Windows ticks (100ns since 01/01/0001) * "..." - literal text * '' - single quote * * @param format string - the desired format of the date * @param date Date - the date value to format * @param settings Object - attributes include: * dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) * dayNames string[7] - names of the days from Sunday (optional) * monthNamesShort string[12] - abbreviated names of the months (optional) * monthNames string[12] - names of the months (optional) * @return string - the date in the above format */ formatDate: function (format, date, settings) { if (!date) { return ""; } var iFormat, dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort, dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames, monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort, monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }, // Format a number, with leading zero if necessary formatNumber = function(match, value, len) { var num = "" + value; if (lookAhead(match)) { while (num.length < len) { num = "0" + num; } } return num; }, // Format a name, short or long as requested formatName = function(match, value, shortNames, longNames) { return (lookAhead(match) ? longNames[value] : shortNames[value]); }, output = "", literal = false; if (date) { for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { output += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": output += formatNumber("d", date.getDate(), 2); break; case "D": output += formatName("D", date.getDay(), dayNamesShort, dayNames); break; case "o": output += formatNumber("o", Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3); break; case "m": output += formatNumber("m", date.getMonth() + 1, 2); break; case "M": output += formatName("M", date.getMonth(), monthNamesShort, monthNames); break; case "y": output += (lookAhead("y") ? date.getFullYear() : (date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100); break; case "@": output += date.getTime(); break; case "!": output += date.getTime() * 10000 + this._ticksTo1970; break; case "'": if (lookAhead("'")) { output += "'"; } else { literal = true; } break; default: output += format.charAt(iFormat); } } } } return output; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var iFormat, chars = "", literal = false, // Check whether a format character is doubled lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match); if (matches) { iFormat++; } return matches; }; for (iFormat = 0; iFormat < format.length; iFormat++) { if (literal) { if (format.charAt(iFormat) === "'" && !lookAhead("'")) { literal = false; } else { chars += format.charAt(iFormat); } } else { switch (format.charAt(iFormat)) { case "d": case "m": case "y": case "@": chars += "0123456789"; break; case "D": case "M": return null; // Accept anything case "'": if (lookAhead("'")) { chars += "'"; } else { literal = true; } break; default: chars += format.charAt(iFormat); } } } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _setDateFromField: function(inst, noDefault) { if (inst.input.val() === inst.lastVal) { return; } var dateFormat = this._get(inst, "dateFormat"), dates = inst.lastVal = inst.input ? inst.input.val() : null, defaultDate = this._getDefaultDate(inst), date = defaultDate, settings = this._getFormatConfig(inst); try { date = this.parseDate(dateFormat, dates, settings) || defaultDate; } catch (event) { dates = (noDefault ? "" : dates); } inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); inst.currentDay = (dates ? date.getDate() : 0); inst.currentMonth = (dates ? date.getMonth() : 0); inst.currentYear = (dates ? date.getFullYear() : 0); this._adjustInstDate(inst); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, "defaultDate"), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _determineDate: function(inst, date, defaultDate) { var offsetNumeric = function(offset) { var date = new Date(); date.setDate(date.getDate() + offset); return date; }, offsetString = function(offset) { try { return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"), offset, $.datepicker._getFormatConfig(inst)); } catch (e) { // Ignore } var date = (offset.toLowerCase().match(/^c/) ? $.datepicker._getDate(inst) : null) || new Date(), year = date.getFullYear(), month = date.getMonth(), day = date.getDate(), pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, matches = pattern.exec(offset); while (matches) { switch (matches[2] || "d") { case "d" : case "D" : day += parseInt(matches[1],10); break; case "w" : case "W" : day += parseInt(matches[1],10) * 7; break; case "m" : case "M" : month += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; case "y": case "Y" : year += parseInt(matches[1],10); day = Math.min(day, $.datepicker._getDaysInMonth(year, month)); break; } matches = pattern.exec(offset); } return new Date(year, month, day); }, newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) : (typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime())))); newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate); if (newDate) { newDate.setHours(0); newDate.setMinutes(0); newDate.setSeconds(0); newDate.setMilliseconds(0); } return this._daylightSavingAdjust(newDate); }, /* Handle switch to/from daylight saving. * Hours may be non-zero on daylight saving cut-over: * > 12 when midnight changeover, but then cannot generate * midnight datetime, so jump to 1AM, otherwise reset. * @param date (Date) the date to check * @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) { return null; } date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _setDate: function(inst, date, noChange) { var clear = !date, origMonth = inst.selectedMonth, origYear = inst.selectedYear, newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date())); inst.selectedDay = inst.currentDay = newDate.getDate(); inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth(); inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear(); if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) { this._notifyChange(inst); } this._adjustInstDate(inst); if (inst.input) { inst.input.val(clear ? "" : this._formatDate(inst)); } }, /* Retrieve the date(s) directly. */ _getDate: function(inst) { var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null : this._daylightSavingAdjust(new Date( inst.currentYear, inst.currentMonth, inst.currentDay))); return startDate; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _attachHandlers: function(inst) { var stepMonths = this._get(inst, "stepMonths"), id = "#" + inst.id.replace( /\\\\/g, "\\" ); inst.dpDiv.find("[data-handler]").map(function () { var handler = { prev: function () { $.datepicker._adjustDate(id, -stepMonths, "M"); }, next: function () { $.datepicker._adjustDate(id, +stepMonths, "M"); }, hide: function () { $.datepicker._hideDatepicker(); }, today: function () { $.datepicker._gotoToday(id); }, selectDay: function () { $.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this); return false; }, selectMonth: function () { $.datepicker._selectMonthYear(id, this, "M"); return false; }, selectYear: function () { $.datepicker._selectMonthYear(id, this, "Y"); return false; } }; $(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var maxDraw, prevText, prev, nextText, next, currentText, gotoDate, controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin, monthNames, monthNamesShort, beforeShowDay, showOtherMonths, selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate, cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows, printDate, dRow, tbody, daySettings, otherMonth, unselectable, tempDate = new Date(), today = this._daylightSavingAdjust( new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time isRTL = this._get(inst, "isRTL"), showButtonPanel = this._get(inst, "showButtonPanel"), hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"), navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"), numMonths = this._getNumberOfMonths(inst), showCurrentAtPos = this._get(inst, "showCurrentAtPos"), stepMonths = this._get(inst, "stepMonths"), isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1), currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) : new Date(inst.currentYear, inst.currentMonth, inst.currentDay))), minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), drawMonth = inst.drawMonth - showCurrentAtPos, drawYear = inst.drawYear; if (drawMonth < 0) { drawMonth += 12; drawYear--; } if (maxDate) { maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(), maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate())); maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw); while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) { drawMonth--; if (drawMonth < 0) { drawMonth = 11; drawYear--; } } } inst.drawMonth = drawMonth; inst.drawYear = drawYear; prevText = this._get(inst, "prevText"); prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText, this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)), this._getFormatConfig(inst))); prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ? "<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" + " title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>")); nextText = this._get(inst, "nextText"); nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText, this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)), this._getFormatConfig(inst))); next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ? "<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" + " title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" : (hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>")); currentText = this._get(inst, "currentText"); gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today); currentText = (!navigationAsDateFormat ? currentText : this.formatDate(currentText, gotoDate, this._getFormatConfig(inst))); controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" + this._get(inst, "closeText") + "</button>" : ""); buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") + (this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" + ">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : ""; firstDay = parseInt(this._get(inst, "firstDay"),10); firstDay = (isNaN(firstDay) ? 0 : firstDay); showWeek = this._get(inst, "showWeek"); dayNames = this._get(inst, "dayNames"); dayNamesMin = this._get(inst, "dayNamesMin"); monthNames = this._get(inst, "monthNames"); monthNamesShort = this._get(inst, "monthNamesShort"); beforeShowDay = this._get(inst, "beforeShowDay"); showOtherMonths = this._get(inst, "showOtherMonths"); selectOtherMonths = this._get(inst, "selectOtherMonths"); defaultDate = this._getDefaultDate(inst); html = ""; dow; for (row = 0; row < numMonths[0]; row++) { group = ""; this.maxRows = 4; for (col = 0; col < numMonths[1]; col++) { selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay)); cornerClass = " ui-corner-all"; calender = ""; if (isMultiMonth) { calender += "<div class='ui-datepicker-group"; if (numMonths[1] > 1) { switch (col) { case 0: calender += " ui-datepicker-group-first"; cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break; case numMonths[1]-1: calender += " ui-datepicker-group-last"; cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break; default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break; } } calender += "'>"; } calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" + (/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") + (/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") + this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate, row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers "</div><table class='ui-datepicker-calendar'><thead>" + "<tr>"; thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : ""); for (dow = 0; dow < 7; dow++) { // days of the week day = (dow + firstDay) % 7; thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" + "<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>"; } calender += thead + "</tr></thead><tbody>"; daysInMonth = this._getDaysInMonth(drawYear, drawMonth); if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) { inst.selectedDay = Math.min(inst.selectedDay, daysInMonth); } leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7; curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += "<tr>"; tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" + this._get(inst, "calculateWeek")(printDate) + "</td>"); for (dow = 0; dow < 7; dow++) { // create date picker days daySettings = (beforeShowDay ? beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]); otherMonth = (printDate.getMonth() !== drawMonth); unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] || (minDate && printDate < minDate) || (maxDate && printDate > maxDate); tbody += "<td class='" + ((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends (otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months ((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate " " + this._dayOverClass : "") + // highlight selected day (unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days (otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates (printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day (printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title (unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions (otherMonth && !showOtherMonths ? " " : // display for other months (unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" + (printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") + (printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day (otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months "' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date printDate.setDate(printDate.getDate() + 1); printDate = this._daylightSavingAdjust(printDate); } calender += tbody + "</tr>"; } drawMonth++; if (drawMonth > 11) { drawMonth = 0; drawYear++; } calender += "</tbody></table>" + (isMultiMonth ? "</div>" + ((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : ""); group += calender; } html += group; } html += buttonPanel; inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate, secondary, monthNames, monthNamesShort) { var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear, changeMonth = this._get(inst, "changeMonth"), changeYear = this._get(inst, "changeYear"), showMonthAfterYear = this._get(inst, "showMonthAfterYear"), html = "<div class='ui-datepicker-title'>", monthHtml = ""; // month selection if (secondary || !changeMonth) { monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>"; } else { inMinYear = (minDate && minDate.getFullYear() === drawYear); inMaxYear = (maxDate && maxDate.getFullYear() === drawYear); monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>"; for ( month = 0; month < 12; month++) { if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) { monthHtml += "<option value='" + month + "'" + (month === drawMonth ? " selected='selected'" : "") + ">" + monthNamesShort[month] + "</option>"; } } monthHtml += "</select>"; } if (!showMonthAfterYear) { html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : ""); } // year selection if ( !inst.yearshtml ) { inst.yearshtml = ""; if (secondary || !changeYear) { html += "<span class='ui-datepicker-year'>" + drawYear + "</span>"; } else { // determine range of years to display years = this._get(inst, "yearRange").split(":"); thisYear = new Date().getFullYear(); determineYear = function(value) { var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) : (value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) : parseInt(value, 10))); return (isNaN(year) ? thisYear : year); }; year = determineYear(years[0]); endYear = Math.max(year, determineYear(years[1] || "")); year = (minDate ? Math.max(year, minDate.getFullYear()) : year); endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear); inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>"; for (; year <= endYear; year++) { inst.yearshtml += "<option value='" + year + "'" + (year === drawYear ? " selected='selected'" : "") + ">" + year + "</option>"; } inst.yearshtml += "</select>"; html += inst.yearshtml; inst.yearshtml = null; } } html += this._get(inst, "yearSuffix"); if (showMonthAfterYear) { html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml; } html += "</div>"; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _adjustInstDate: function(inst, offset, period) { var year = inst.drawYear + (period === "Y" ? offset : 0), month = inst.drawMonth + (period === "M" ? offset : 0), day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0), date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day))); inst.selectedDay = date.getDate(); inst.drawMonth = inst.selectedMonth = date.getMonth(); inst.drawYear = inst.selectedYear = date.getFullYear(); if (period === "M" || period === "Y") { this._notifyChange(inst); } }, /* Ensure a date is within any min/max bounds. */ _restrictMinMax: function(inst, date) { var minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), newDate = (minDate && date < minDate ? minDate : date); return (maxDate && newDate > maxDate ? maxDate : newDate); }, /* Notify change of month/year. */ _notifyChange: function(inst) { var onChange = this._get(inst, "onChangeMonthYear"); if (onChange) { onChange.apply((inst.input ? inst.input[0] : null), [inst.selectedYear, inst.selectedMonth + 1, inst]); } }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, "numberOfMonths"); return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + "Date"), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _canAdjustMonth: function(inst, offset, curYear, curMonth) { var numMonths = this._getNumberOfMonths(inst), date = this._daylightSavingAdjust(new Date(curYear, curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1)); if (offset < 0) { date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth())); } return this._isInRange(inst, date); }, /* Is the given date in the accepted range? */ _isInRange: function(inst, date) { var yearSplit, currentYear, minDate = this._getMinMaxDate(inst, "min"), maxDate = this._getMinMaxDate(inst, "max"), minYear = null, maxYear = null, years = this._get(inst, "yearRange"); if (years){ yearSplit = years.split(":"); currentYear = new Date().getFullYear(); minYear = parseInt(yearSplit[0], 10); maxYear = parseInt(yearSplit[1], 10); if ( yearSplit[0].match(/[+\-].*/) ) { minYear += currentYear; } if ( yearSplit[1].match(/[+\-].*/) ) { maxYear += currentYear; } } return ((!minDate || date.getTime() >= minDate.getTime()) && (!maxDate || date.getTime() <= maxDate.getTime()) && (!minYear || date.getFullYear() >= minYear) && (!maxYear || date.getFullYear() <= maxYear)); }, /* Provide the configuration settings for formatting/parsing. */ _getFormatConfig: function(inst) { var shortYearCutoff = this._get(inst, "shortYearCutoff"); shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff : new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10)); return {shortYearCutoff: shortYearCutoff, dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"), monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")}; }, /* Format the given date for display. */ _formatDate: function(inst, day, month, year) { if (!day) { inst.currentDay = inst.selectedDay; inst.currentMonth = inst.selectedMonth; inst.currentYear = inst.selectedYear; } var date = (day ? (typeof day === "object" ? day : this._daylightSavingAdjust(new Date(year, month, day))) : this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay))); return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function datepicker_bindHover(dpDiv) { var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a"; return dpDiv.delegate(selector, "mouseout", function() { $(this).removeClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).removeClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).removeClass("ui-datepicker-next-hover"); } }) .delegate(selector, "mouseover", function(){ if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? dpDiv.parent()[0] : datepicker_instActive.input[0])) { $(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); $(this).addClass("ui-state-hover"); if (this.className.indexOf("ui-datepicker-prev") !== -1) { $(this).addClass("ui-datepicker-prev-hover"); } if (this.className.indexOf("ui-datepicker-next") !== -1) { $(this).addClass("ui-datepicker-next-hover"); } } }); } /* jQuery extend now ignores nulls! */ function datepicker_extendRemove(target, props) { $.extend(target, props); for (var name in props) { if (props[name] == null) { target[name] = props[name]; } } return target; } /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick); $.datepicker.initialized = true; } /* Append datepicker main container to body if not exist. */ if ($("#"+$.datepicker._mainDivId).length === 0) { $("body").append($.datepicker.dpDiv); } var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") { return $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this[0]].concat(otherArgs)); } return this.each(function() { typeof options === "string" ? $.datepicker["_" + options + "Datepicker"]. apply($.datepicker, [this].concat(otherArgs)) : $.datepicker._attachDatepicker(this, options); }); }; $.datepicker = new Datepicker(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.11.0"; return $.datepicker; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./button", "./draggable", "./mouse", "./position", "./resizable" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.dialog", { version: "1.11.0", options: { appendTo: "body", autoOpen: true, buttons: [], closeOnEscape: true, closeText: "Close", dialogClass: "", draggable: true, hide: null, height: "auto", maxHeight: null, maxWidth: null, minHeight: 150, minWidth: 150, modal: false, position: { my: "center", at: "center", of: window, collision: "fit", // Ensure the titlebar is always visible using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, title: null, width: 300, // callbacks beforeClose: null, close: null, drag: null, dragStart: null, dragStop: null, focus: null, open: null, resize: null, resizeStart: null, resizeStop: null }, sizeRelatedOptions: { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions: { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }, _create: function() { this.originalCss = { display: this.element[ 0 ].style.display, width: this.element[ 0 ].style.width, minHeight: this.element[ 0 ].style.minHeight, maxHeight: this.element[ 0 ].style.maxHeight, height: this.element[ 0 ].style.height }; this.originalPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.originalTitle = this.element.attr( "title" ); this.options.title = this.options.title || this.originalTitle; this._createWrapper(); this.element .show() .removeAttr( "title" ) .addClass( "ui-dialog-content ui-widget-content" ) .appendTo( this.uiDialog ); this._createTitlebar(); this._createButtonPane(); if ( this.options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( this.options.resizable && $.fn.resizable ) { this._makeResizable(); } this._isOpen = false; this._trackFocus(); }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _appendTo: function() { var element = this.options.appendTo; if ( element && (element.jquery || element.nodeType) ) { return $( element ); } return this.document.find( element || "body" ).eq( 0 ); }, _destroy: function() { var next, originalPosition = this.originalPosition; this._destroyOverlay(); this.element .removeUniqueId() .removeClass( "ui-dialog-content ui-widget-content" ) .css( this.originalCss ) // Without detaching first, the following becomes really slow .detach(); this.uiDialog.stop( true, true ).remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = originalPosition.parent.children().eq( originalPosition.index ); // Don't try to place the dialog next to itself (#8613) if ( next.length && next[ 0 ] !== this.element[ 0 ] ) { next.before( this.element ); } else { originalPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, disable: $.noop, enable: $.noop, close: function( event ) { var activeElement, that = this; if ( !this._isOpen || this._trigger( "beforeClose", event ) === false ) { return; } this._isOpen = false; this._focusedElement = null; this._destroyOverlay(); this._untrackInstance(); if ( !this.opener.filter( ":focusable" ).focus().length ) { // support: IE9 // IE9 throws an "Unspecified error" accessing document.activeElement from an <iframe> try { activeElement = this.document[ 0 ].activeElement; // Support: IE9, IE10 // If the <body> is blurred, IE will switch windows, see #4520 if ( activeElement && activeElement.nodeName.toLowerCase() !== "body" ) { // Hiding a focused element doesn't trigger blur in WebKit // so in case we have nothing to focus on, explicitly blur the active element // https://bugs.webkit.org/show_bug.cgi?id=47182 $( activeElement ).blur(); } } catch ( error ) {} } this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); }, isOpen: function() { return this._isOpen; }, moveToTop: function() { this._moveToTop(); }, _moveToTop: function( event, silent ) { var moved = false, zIndicies = this.uiDialog.siblings( ".ui-front:visible" ).map(function() { return +$( this ).css( "z-index" ); }).get(), zIndexMax = Math.max.apply( null, zIndicies ); if ( zIndexMax >= +this.uiDialog.css( "z-index" ) ) { this.uiDialog.css( "z-index", zIndexMax + 1 ); moved = true; } if ( moved && !silent ) { this._trigger( "focus", event ); } return moved; }, open: function() { var that = this; if ( this._isOpen ) { if ( this._moveToTop() ) { this._focusTabbable(); } return; } this._isOpen = true; this.opener = $( this.document[ 0 ].activeElement ); this._size(); this._position(); this._createOverlay(); this._moveToTop( null, true ); this._show( this.uiDialog, this.options.show, function() { that._focusTabbable(); that._trigger( "focus" ); }); this._trigger( "open" ); }, _focusTabbable: function() { // Set focus to the first match: // 1. An element that was focused previously // 2. First element inside the dialog matching [autofocus] // 3. Tabbable element inside the content element // 4. Tabbable element inside the buttonpane // 5. The close button // 6. The dialog itself var hasFocus = this._focusedElement; if ( !hasFocus ) { hasFocus = this.element.find( "[autofocus]" ); } if ( !hasFocus.length ) { hasFocus = this.element.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialogTitlebarClose.filter( ":tabbable" ); } if ( !hasFocus.length ) { hasFocus = this.uiDialog; } hasFocus.eq( 0 ).focus(); }, _keepFocus: function( event ) { function checkFocus() { var activeElement = this.document[0].activeElement, isActive = this.uiDialog[0] === activeElement || $.contains( this.uiDialog[0], activeElement ); if ( !isActive ) { this._focusTabbable(); } } event.preventDefault(); checkFocus.call( this ); // support: IE // IE <= 8 doesn't prevent moving focus even with event.preventDefault() // so we check again later this._delay( checkFocus ); }, _createWrapper: function() { this.uiDialog = $("<div>") .addClass( "ui-dialog ui-widget ui-widget-content ui-corner-all ui-front " + this.options.dialogClass ) .hide() .attr({ // Setting tabIndex makes the div focusable tabIndex: -1, role: "dialog" }) .appendTo( this._appendTo() ); this._on( this.uiDialog, { keydown: function( event ) { if ( this.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { event.preventDefault(); this.close( event ); return; } // prevent tabbing out of dialogs if ( event.keyCode !== $.ui.keyCode.TAB || event.isDefaultPrevented() ) { return; } var tabbables = this.uiDialog.find( ":tabbable" ), first = tabbables.filter( ":first" ), last = tabbables.filter( ":last" ); if ( ( event.target === last[0] || event.target === this.uiDialog[0] ) && !event.shiftKey ) { this._delay(function() { first.focus(); }); event.preventDefault(); } else if ( ( event.target === first[0] || event.target === this.uiDialog[0] ) && event.shiftKey ) { this._delay(function() { last.focus(); }); event.preventDefault(); } }, mousedown: function( event ) { if ( this._moveToTop( event ) ) { this._focusTabbable(); } } }); // We assume that any existing aria-describedby attribute means // that the dialog content is marked up properly // otherwise we brute force the content as the description if ( !this.element.find( "[aria-describedby]" ).length ) { this.uiDialog.attr({ "aria-describedby": this.element.uniqueId().attr( "id" ) }); } }, _createTitlebar: function() { var uiDialogTitle; this.uiDialogTitlebar = $( "<div>" ) .addClass( "ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix" ) .prependTo( this.uiDialog ); this._on( this.uiDialogTitlebar, { mousedown: function( event ) { // Don't prevent click on close button (#8838) // Focusing a dialog that is partially scrolled out of view // causes the browser to scroll it into view, preventing the click event if ( !$( event.target ).closest( ".ui-dialog-titlebar-close" ) ) { // Dialog isn't getting focus when dragging (#8063) this.uiDialog.focus(); } } }); // support: IE // Use type="button" to prevent enter keypresses in textboxes from closing the // dialog in IE (#9312) this.uiDialogTitlebarClose = $( "<button type='button'></button>" ) .button({ label: this.options.closeText, icons: { primary: "ui-icon-closethick" }, text: false }) .addClass( "ui-dialog-titlebar-close" ) .appendTo( this.uiDialogTitlebar ); this._on( this.uiDialogTitlebarClose, { click: function( event ) { event.preventDefault(); this.close( event ); } }); uiDialogTitle = $( "<span>" ) .uniqueId() .addClass( "ui-dialog-title" ) .prependTo( this.uiDialogTitlebar ); this._title( uiDialogTitle ); this.uiDialog.attr({ "aria-labelledby": uiDialogTitle.attr( "id" ) }); }, _title: function( title ) { if ( !this.options.title ) { title.html( " " ); } title.text( this.options.title ); }, _createButtonPane: function() { this.uiDialogButtonPane = $( "<div>" ) .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); this.uiButtonSet = $( "<div>" ) .addClass( "ui-dialog-buttonset" ) .appendTo( this.uiDialogButtonPane ); this._createButtons(); }, _createButtons: function() { var that = this, buttons = this.options.buttons; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( $.isEmptyObject( buttons ) || ($.isArray( buttons ) && !buttons.length) ) { this.uiDialog.removeClass( "ui-dialog-buttons" ); return; } $.each( buttons, function( name, props ) { var click, buttonOptions; props = $.isFunction( props ) ? { click: props, text: name } : props; // Default to a non-submitting button props = $.extend( { type: "button" }, props ); // Change the context for the click callback to be the main element click = props.click; props.click = function() { click.apply( that.element[ 0 ], arguments ); }; buttonOptions = { icons: props.icons, text: props.showText }; delete props.icons; delete props.showText; $( "<button></button>", props ) .button( buttonOptions ) .appendTo( that.uiButtonSet ); }); this.uiDialog.addClass( "ui-dialog-buttons" ); this.uiDialogButtonPane.appendTo( this.uiDialog ); }, _makeDraggable: function() { var that = this, options = this.options; function filteredUi( ui ) { return { position: ui.position, offset: ui.offset }; } this.uiDialog.draggable({ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function( event, ui ) { $( this ).addClass( "ui-dialog-dragging" ); that._blockFrames(); that._trigger( "dragStart", event, filteredUi( ui ) ); }, drag: function( event, ui ) { that._trigger( "drag", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var left = ui.offset.left - that.document.scrollLeft(), top = ui.offset.top - that.document.scrollTop(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-dragging" ); that._unblockFrames(); that._trigger( "dragStop", event, filteredUi( ui ) ); } }); }, _makeResizable: function() { var that = this, options = this.options, handles = options.resizable, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = this.uiDialog.css("position"), resizeHandles = typeof handles === "string" ? handles : "n,e,s,w,se,sw,ne,nw"; function filteredUi( ui ) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } this.uiDialog.resizable({ cancel: ".ui-dialog-content", containment: "document", alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: this._minHeight(), handles: resizeHandles, start: function( event, ui ) { $( this ).addClass( "ui-dialog-resizing" ); that._blockFrames(); that._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { var offset = that.uiDialog.offset(), left = offset.left - that.document.scrollLeft(), top = offset.top - that.document.scrollTop(); options.height = that.uiDialog.height(); options.width = that.uiDialog.width(); options.position = { my: "left top", at: "left" + (left >= 0 ? "+" : "") + left + " " + "top" + (top >= 0 ? "+" : "") + top, of: that.window }; $( this ).removeClass( "ui-dialog-resizing" ); that._unblockFrames(); that._trigger( "resizeStop", event, filteredUi( ui ) ); } }) .css( "position", position ); }, _trackFocus: function() { this._on( this.widget(), { "focusin": function( event ) { this._untrackInstance(); this._trackingInstances().unshift( this ); this._focusedElement = $( event.target ); } }); }, _untrackInstance: function() { var instances = this._trackingInstances(), exists = $.inArray( this, instances ); if ( exists !== -1 ) { instances.splice( exists, 1 ); } }, _trackingInstances: function() { var instances = this.document.data( "ui-dialog-instances" ); if ( !instances ) { instances = []; this.document.data( "ui-dialog-instances", instances ); } return instances; }, _minHeight: function() { var options = this.options; return options.height === "auto" ? options.minHeight : Math.min( options.minHeight, options.height ); }, _position: function() { // Need to show the dialog to get the actual offset in the position plugin var isVisible = this.uiDialog.is( ":visible" ); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( this.options.position ); if ( !isVisible ) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var that = this, resize = false, resizableOptions = {}; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key in that.sizeRelatedOptions ) { resize = true; } if ( key in that.resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); this._position(); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { var isDraggable, isResizable, uiDialog = this.uiDialog; if ( key === "dialogClass" ) { uiDialog .removeClass( this.options.dialogClass ) .addClass( value ); } if ( key === "disabled" ) { return; } this._super( key, value ); if ( key === "appendTo" ) { this.uiDialog.appendTo( this._appendTo() ); } if ( key === "buttons" ) { this._createButtons(); } if ( key === "closeText" ) { this.uiDialogTitlebarClose.button({ // Ensure that we always pass a string label: "" + value }); } if ( key === "draggable" ) { isDraggable = uiDialog.is( ":data(ui-draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { this._makeDraggable(); } } if ( key === "position" ) { this._position(); } if ( key === "resizable" ) { // currently resizable, becoming non-resizable isResizable = uiDialog.is( ":data(ui-resizable)" ); if ( isResizable && !value ) { uiDialog.resizable( "destroy" ); } // currently resizable, changing handles if ( isResizable && typeof value === "string" ) { uiDialog.resizable( "option", "handles", value ); } // currently non-resizable, becoming resizable if ( !isResizable && value !== false ) { this._makeResizable(); } } if ( key === "title" ) { this._title( this.uiDialogTitlebar.find( ".ui-dialog-title" ) ); } }, _size: function() { // If the user has resized the dialog, the .ui-dialog and .ui-dialog-content // divs will both have width and height set, so we need to reset them var nonContentHeight, minContentHeight, maxContentHeight, options = this.options; // Reset content sizing this.element.show().css({ width: "auto", minHeight: 0, maxHeight: "none", height: 0 }); if ( options.minWidth > options.width ) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: "auto", width: options.width }) .outerHeight(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); maxContentHeight = typeof options.maxHeight === "number" ? Math.max( 0, options.maxHeight - nonContentHeight ) : "none"; if ( options.height === "auto" ) { this.element.css({ minHeight: minContentHeight, maxHeight: maxContentHeight, height: "auto" }); } else { this.element.height( Math.max( 0, options.height - nonContentHeight ) ); } if ( this.uiDialog.is( ":data(ui-resizable)" ) ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } }, _blockFrames: function() { this.iframeBlocks = this.document.find( "iframe" ).map(function() { var iframe = $( this ); return $( "<div>" ) .css({ position: "absolute", width: iframe.outerWidth(), height: iframe.outerHeight() }) .appendTo( iframe.parent() ) .offset( iframe.offset() )[0]; }); }, _unblockFrames: function() { if ( this.iframeBlocks ) { this.iframeBlocks.remove(); delete this.iframeBlocks; } }, _allowInteraction: function( event ) { if ( $( event.target ).closest( ".ui-dialog" ).length ) { return true; } // TODO: Remove hack when datepicker implements // the .ui-front logic (#8989) return !!$( event.target ).closest( ".ui-datepicker" ).length; }, _createOverlay: function() { if ( !this.options.modal ) { return; } // We use a delay in case the overlay is created from an // event that we're going to be cancelling (#2804) var isOpening = true; this._delay(function() { isOpening = false; }); if ( !this.document.data( "ui-dialog-overlays" ) ) { // Prevent use of anchors and inputs // Using _on() for an event handler shared across many instances is // safe because the dialogs stack and must be closed in reverse order this._on( this.document, { focusin: function( event ) { if ( isOpening ) { return; } if ( !this._allowInteraction( event ) ) { event.preventDefault(); this._trackingInstances()[ 0 ]._focusTabbable(); } } }); } this.overlay = $( "<div>" ) .addClass( "ui-widget-overlay ui-front" ) .appendTo( this._appendTo() ); this._on( this.overlay, { mousedown: "_keepFocus" }); this.document.data( "ui-dialog-overlays", (this.document.data( "ui-dialog-overlays" ) || 0) + 1 ); }, _destroyOverlay: function() { if ( !this.options.modal ) { return; } if ( this.overlay ) { var overlays = this.document.data( "ui-dialog-overlays" ) - 1; if ( !overlays ) { this.document .unbind( "focusin" ) .removeData( "ui-dialog-overlays" ); } else { this.document.data( "ui-dialog-overlays", overlays ); } this.overlay.remove(); this.overlay = null; } } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.blind = function( o, done ) { // Create element var el = $( this ), rvertical = /up|down|vertical/, rpositivemotion = /up|left|vertical|horizontal/, props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), direction = o.direction || "up", vertical = rvertical.test( direction ), ref = vertical ? "height" : "width", ref2 = vertical ? "top" : "left", motion = rpositivemotion.test( direction ), animation = {}, show = mode === "show", wrapper, distance, margin; // if already wrapped, the wrapper's properties are my property. #6245 if ( el.parent().is( ".ui-effects-wrapper" ) ) { $.effects.save( el.parent(), props ); } else { $.effects.save( el, props ); } el.show(); wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = wrapper[ ref ](); margin = parseFloat( wrapper.css( ref2 ) ) || 0; animation[ ref ] = show ? distance : 0; if ( !motion ) { el .css( vertical ? "bottom" : "right", 0 ) .css( vertical ? "top" : "left", "auto" ) .css({ position: "absolute" }); animation[ ref2 ] = show ? margin : distance + margin; } // start at 0 if we are showing if ( show ) { wrapper.css( ref, 0 ); if ( !motion ) { wrapper.css( ref2, margin + distance ); } } // Animate wrapper.animate( animation, { duration: o.duration, easing: o.easing, queue: false, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.bounce = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], // defaults: mode = $.effects.setMode( el, o.mode || "effect" ), hide = mode === "hide", show = mode === "show", direction = o.direction || "up", distance = o.distance, times = o.times || 5, // number of internal animations anims = times * 2 + ( show || hide ? 1 : 0 ), speed = o.duration / anims, easing = o.easing, // utility: ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ), i, upAnim, downAnim, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; // Avoid touching opacity to prevent clearType and PNG issues in IE if ( show || hide ) { props.push( "opacity" ); } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Create Wrapper // default distance for the BIGGEST bounce is the outer Distance / 3 if ( !distance ) { distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; } if ( show ) { downAnim = { opacity: 1 }; downAnim[ ref ] = 0; // if we are showing, force opacity 0 and set the initial position // then do the "first" animation el.css( "opacity", 0 ) .css( ref, motion ? -distance * 2 : distance * 2 ) .animate( downAnim, speed, easing ); } // start at the smallest distance if we are hiding if ( hide ) { distance = distance / Math.pow( 2, times - 1 ); } downAnim = {}; downAnim[ ref ] = 0; // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here for ( i = 0; i < times; i++ ) { upAnim = {}; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ) .animate( downAnim, speed, easing ); distance = hide ? distance * 2 : distance / 2; } // Last Bounce when Hiding if ( hide ) { upAnim = { opacity: 0 }; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ); } el.queue(function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.clip = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "vertical", vert = direction === "vertical", size = vert ? "height" : "width", position = vert ? "top" : "left", animation = {}, wrapper, animate, distance; // Save & Show $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); animate = ( el[0].tagName === "IMG" ) ? wrapper : el; distance = animate[ size ](); // Shift if ( show ) { animate.css( size, 0 ); animate.css( position, distance / 2 ); } // Create Animation Object: animation[ size ] = show ? distance : 0; animation[ position ] = show ? 0 : distance / 2; // Animate animate.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( !show ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.drop = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "left", ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", animation = { opacity: show ? 1 : 0 }, distance; // Adjust $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; if ( show ) { el .css( "opacity", 0 ) .css( ref, motion === "pos" ? -distance : distance ); } // Animation animation[ ref ] = ( show ? ( motion === "pos" ? "+=" : "-=" ) : ( motion === "pos" ? "-=" : "+=" ) ) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.explode = function( o, done ) { var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, cells = rows, el = $( this ), mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", // show and then visibility:hidden the element before calculating offset offset = el.show().css( "visibility", "hidden" ).offset(), // width and height of a piece width = Math.ceil( el.outerWidth() / cells ), height = Math.ceil( el.outerHeight() / rows ), pieces = [], // loop i, j, left, top, mx, my; // children animate complete: function childComplete() { pieces.push( this ); if ( pieces.length === rows * cells ) { animComplete(); } } // clone the element for each row and cell. for ( i = 0; i < rows ; i++ ) { // ===> top = offset.top + i * height; my = i - ( rows - 1 ) / 2 ; for ( j = 0; j < cells ; j++ ) { // ||| left = offset.left + j * width; mx = j - ( cells - 1 ) / 2 ; // Create a clone of the now hidden main element that will be absolute positioned // within a wrapper div off the -left and -top equal to size of our pieces el .clone() .appendTo( "body" ) .wrap( "<div></div>" ) .css({ position: "absolute", visibility: "visible", left: -j * width, top: -i * height }) // select the wrapper - make it overflow: hidden and absolute positioned based on // where the original was located +left and +top equal to the size of pieces .parent() .addClass( "ui-effects-explode" ) .css({ position: "absolute", overflow: "hidden", width: width, height: height, left: left + ( show ? mx * width : 0 ), top: top + ( show ? my * height : 0 ), opacity: show ? 0 : 1 }).animate({ left: left + ( show ? 0 : mx * width ), top: top + ( show ? 0 : my * height ), opacity: show ? 1 : 0 }, o.duration || 500, o.easing, childComplete ); } } function animComplete() { el.css({ visibility: "visible" }); $( pieces ).remove(); if ( !show ) { el.hide(); } done(); } }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.fade = function( o, done ) { var el = $( this ), mode = $.effects.setMode( el, o.mode || "toggle" ); el.animate({ opacity: mode }, { queue: false, duration: o.duration, easing: o.easing, complete: done }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.highlight = function( o, done ) { var elem = $( this ), props = [ "backgroundImage", "backgroundColor", "opacity" ], mode = $.effects.setMode( elem, o.mode || "show" ), animation = { backgroundColor: elem.css( "backgroundColor" ) }; if (mode === "hide") { animation.opacity = 0; } $.effects.save( elem, props ); elem .show() .css({ backgroundImage: "none", backgroundColor: o.color || "#ffff99" }) .animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { elem.hide(); } $.effects.restore( elem, props ); done(); } }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect", "./effect-scale" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.puff = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "hide" ), hide = mode === "hide", percent = parseInt( o.percent, 10 ) || 150, factor = percent / 100, original = { height: elem.height(), width: elem.width(), outerHeight: elem.outerHeight(), outerWidth: elem.outerWidth() }; $.extend( o, { effect: "scale", queue: false, fade: true, mode: mode, complete: done, percent: hide ? percent : 100, from: hide ? original : { height: original.height * factor, width: original.width * factor, outerHeight: original.outerHeight * factor, outerWidth: original.outerWidth * factor } }); elem.effect( o ); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.pulsate = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "show" ), show = mode === "show", hide = mode === "hide", showhide = ( show || mode === "hide" ), // showing or hiding leaves of the "last" animation anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), duration = o.duration / anims, animateTo = 0, queue = elem.queue(), queuelen = queue.length, i; if ( show || !elem.is(":visible")) { elem.css( "opacity", 0 ).show(); animateTo = 1; } // anims - 1 opacity "toggles" for ( i = 1; i < anims; i++ ) { elem.animate({ opacity: animateTo }, duration, o.easing ); animateTo = 1 - animateTo; } elem.animate({ opacity: animateTo }, duration, o.easing); elem.queue(function() { if ( hide ) { elem.hide(); } done(); }); // We just queued up "anims" animations, we need to put them next in the queue if ( queuelen > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } elem.dequeue(); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect", "./effect-size" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.scale = function( o, done ) { // Create element var el = $( this ), options = $.extend( true, {}, o ), mode = $.effects.setMode( el, o.mode || "effect" ), percent = parseInt( o.percent, 10 ) || ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), direction = o.direction || "both", origin = o.origin, original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }, factor = { y: direction !== "horizontal" ? (percent / 100) : 1, x: direction !== "vertical" ? (percent / 100) : 1 }; // We are going to pass this effect to the size effect: options.effect = "size"; options.queue = false; options.complete = done; // Set default origin and restore for show/hide if ( mode !== "effect" ) { options.origin = origin || [ "middle", "center" ]; options.restore = true; } options.from = o.from || ( mode === "show" ? { height: 0, width: 0, outerHeight: 0, outerWidth: 0 } : original ); options.to = { height: original.height * factor.y, width: original.width * factor.x, outerHeight: original.outerHeight * factor.y, outerWidth: original.outerWidth * factor.x }; // Fade option to support puff if ( options.fade ) { if ( mode === "show" ) { options.from.opacity = 0; options.to.opacity = 1; } if ( mode === "hide" ) { options.from.opacity = 1; options.to.opacity = 0; } } // Animate el.effect( options ); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.shake = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "effect" ), direction = o.direction || "left", distance = o.distance || 20, times = o.times || 3, anims = times * 2 + 1, speed = Math.round( o.duration / anims ), ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), animation = {}, animation1 = {}, animation2 = {}, i, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Animation animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; // Animate el.animate( animation, speed, o.easing ); // Shakes for ( i = 1; i < times; i++ ) { el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); } el .animate( animation1, speed, o.easing ) .animate( animation, speed / 2, o.easing ) .queue(function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.size = function( o, done ) { // Create element var original, baseline, factor, el = $( this ), props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], // Always restore props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], // Copy for children props2 = [ "width", "height", "overflow" ], cProps = [ "fontSize" ], vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], // Set options mode = $.effects.setMode( el, o.mode || "effect" ), restore = o.restore || mode !== "effect", scale = o.scale || "both", origin = o.origin || [ "middle", "center" ], position = el.css( "position" ), props = restore ? props0 : props1, zero = { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; if ( mode === "show" ) { el.show(); } original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }; if ( o.mode === "toggle" && mode === "show" ) { el.from = o.to || zero; el.to = o.from || original; } else { el.from = o.from || ( mode === "show" ? zero : original ); el.to = o.to || ( mode === "hide" ? zero : original ); } // Set scaling factor factor = { from: { y: el.from.height / original.height, x: el.from.width / original.width }, to: { y: el.to.height / original.height, x: el.to.width / original.width } }; // Scale the css box if ( scale === "box" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( vProps ); el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { props = props.concat( hProps ); el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); } } // Scale the content if ( scale === "content" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( cProps ).concat( props2 ); el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); } } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); el.css( "overflow", "hidden" ).css( el.from ); // Adjust if (origin) { // Calculate baseline shifts baseline = $.effects.getBaseline( origin, original ); el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; } el.css( el.from ); // set top & left // Animate if ( scale === "content" || scale === "both" ) { // Scale the children // Add margins/font-size vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); hProps = hProps.concat([ "marginLeft", "marginRight" ]); props2 = props0.concat(vProps).concat(hProps); el.find( "*[width]" ).each( function() { var child = $( this ), c_original = { height: child.height(), width: child.width(), outerHeight: child.outerHeight(), outerWidth: child.outerWidth() }; if (restore) { $.effects.save(child, props2); } child.from = { height: c_original.height * factor.from.y, width: c_original.width * factor.from.x, outerHeight: c_original.outerHeight * factor.from.y, outerWidth: c_original.outerWidth * factor.from.x }; child.to = { height: c_original.height * factor.to.y, width: c_original.width * factor.to.x, outerHeight: c_original.height * factor.to.y, outerWidth: c_original.width * factor.to.x }; // Vertical props scaling if ( factor.from.y !== factor.to.y ) { child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); } // Animate children child.css( child.from ); child.animate( child.to, o.duration, o.easing, function() { // Restore children if ( restore ) { $.effects.restore( child, props2 ); } }); }); } // Animate el.animate( el.to, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( el.to.opacity === 0 ) { el.css( "opacity", el.from.opacity ); } if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); if ( !restore ) { // we need to calculate our new positioning based on the scaling if ( position === "static" ) { el.css({ position: "relative", top: el.to.top, left: el.to.left }); } else { $.each([ "top", "left" ], function( idx, pos ) { el.css( pos, function( _, str ) { var val = parseInt( str, 10 ), toRef = idx ? el.to.left : el.to.top; // if original was "auto", recalculate the new value from wrapper if ( str === "auto" ) { return toRef + "px"; } return val + toRef + "px"; }); }); } } $.effects.removeWrapper( el ); done(); } }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./effect" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop, left: endPosition.left - fixLeft, height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop, left: startPosition.left - fixLeft, height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./position" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.menu", { version: "1.11.0", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, items: "> *", menus: "ul", position: { my: "left-1 top", at: "right top" }, role: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; // Flag used to prevent firing of the click handler // as the event bubbles up through nested menus this.mouseHandled = false; this.element .uniqueId() .addClass( "ui-menu ui-widget ui-widget-content" ) .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) .attr({ role: this.options.role, tabIndex: 0 }); if ( this.options.disabled ) { this.element .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } this._on({ // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item": function( event ) { event.preventDefault(); }, "click .ui-menu-item": function( event ) { var target = $( event.target ); if ( !this.mouseHandled && target.not( ".ui-state-disabled" ).length ) { this.select( event ); // Only set the mouseHandled flag if the event will bubble, see #9469. if ( !event.isPropagationStopped() ) { this.mouseHandled = true; } // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) && $( this.document[ 0 ].activeElement ).closest( ".ui-menu" ).length ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { var target = $( event.currentTarget ); // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border target.siblings( ".ui-state-active" ).removeClass( "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.find( this.options.items ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay(function() { if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { this.collapseAll( event ); } }); }, keydown: "_keydown" }); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( this._closeOnDocumentClick( event ) ) { this.collapseAll( event ); } // Reset the mouseHandled flag this.mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).addBack() .removeClass( "ui-menu ui-widget ui-widget-content ui-menu-icons ui-front" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .show(); // Destroy menu items this.element.find( ".ui-menu-item" ) .removeClass( "ui-menu-item" ) .removeAttr( "role" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .removeClass( "ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "role" ) .removeAttr( "aria-haspopup" ) .children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-carat" ) ) { elem.remove(); } }); // Destroy menu dividers this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); }, _keydown: function( event ) { var match, prev, character, skip, regex, preventDefault = true; function escape( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); } switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; character = String.fromCharCode( event.keyCode ); skip = false; clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.find( this.options.items ).filter(function() { return regex.test( $( this ).text() ); }); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.find( this.options.items ).filter(function() { return regex.test( $( this ).text() ); }); } if ( match.length ) { this.focus( event, match ); if ( match.length > 1 ) { this.previousFilter = character; this.filterTimer = this._delay(function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.is( "[aria-haspopup='true']" ) ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, items, that = this, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); this.element.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ); // Initialize nested menus submenus.filter( ":not(.ui-menu)" ) .addClass( "ui-menu ui-widget ui-widget-content ui-front" ) .hide() .attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }) .each(function() { var menu = $( this ), item = menu.parent(), submenuCarat = $( "<span>" ) .addClass( "ui-menu-icon ui-icon " + icon ) .data( "ui-menu-submenu-carat", true ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCarat ); menu.attr( "aria-labelledby", item.attr( "id" ) ); }); menus = submenus.add( this.element ); items = menus.find( this.options.items ); // Initialize menu-items containing spaces and/or dashes only as dividers items.not( ".ui-menu-item" ).each(function() { var item = $( this ); if ( that._isDivider( item ) ) { item.addClass( "ui-widget-content ui-menu-divider" ); } }); // Don't refresh list items that are already adapted items.not( ".ui-menu-item, .ui-menu-divider" ) .addClass( "ui-menu-item" ) .uniqueId() .attr({ tabIndex: -1, role: this._itemRole() }); // Add aria-disabled attribute to any disabled menu item items.filter( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, _setOption: function( key, value ) { if ( key === "icons" ) { this.element.find( ".ui-menu-icon" ) .removeClass( this.options.icons.submenu ) .addClass( value.submenu ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, focus: function( event, item ) { var nested, focused; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.addClass( "ui-state-focus" ).removeClass( "ui-state-active" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any this.active .parent() .closest( ".ui-menu-item" ) .addClass( "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay(function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && event && ( /^mouse/.test( event.type ) ) ) { this._startOpening(nested); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.outerHeight(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this.active.removeClass( "ui-state-focus" ); this.active = null; this._trigger( "blur", event, { item: this.active } ); }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the carat icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay(function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend({ of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay(function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu .find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ) .end() .find( ".ui-state-active" ).not( ".ui-state-focus" ) .removeClass( "ui-state-active" ); }, _closeOnDocumentClick: function( event ) { return !$( event.target ).closest( ".ui-menu" ).length; }, _isDivider: function( item ) { // Match hyphen, em dash, en dash return !/[^\-\u2014\u2013\s]/.test( item.text() ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .find( this.options.items ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay(function() { this.focus( event, newItem ); }); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.find( this.options.items )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base - height < 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base + height > 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.find( this.options.items ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define( [ "jquery" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { (function() { $.ui = $.ui || {}; var cachedScrollbarWidth, supportsOffsetFractions, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+(\.[\d]+)?%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseFloat( offsets[ 0 ] ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseFloat( offsets[ 1 ] ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } function getDimensions( elem ) { var raw = elem[0]; if ( raw.nodeType === 9 ) { return { width: elem.width(), height: elem.height(), offset: { top: 0, left: 0 } }; } if ( $.isWindow( raw ) ) { return { width: elem.width(), height: elem.height(), offset: { top: elem.scrollTop(), left: elem.scrollLeft() } }; } if ( raw.preventDefault ) { return { width: 0, height: 0, offset: { top: raw.pageY, left: raw.pageX } }; } return { width: elem.outerWidth(), height: elem.outerHeight(), offset: elem.offset() }; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow || within.isDocument ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowY ? $.position.scrollbarWidth() : 0, height: hasOverflowX ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ), isDocument = !!withinElement[ 0 ] && withinElement[ 0 ].nodeType === 9; return { element: withinElement, isWindow: isWindow, isDocument: isDocument, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, dimensions, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), collision = ( options.collision || "flip" ).split( " " ), offsets = {}; dimensions = getDimensions( target ); if ( target[0].preventDefault ) { // force left top to allow flipping options.at = "left top"; } targetWidth = dimensions.width; targetHeight = dimensions.height; targetOffset = dimensions.offset; // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !supportsOffsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem: elem }); } }); if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function() { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; supportsOffsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); })(); return $.ui.position; })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.progressbar", { version: "1.11.0", options: { max: 100, value: 0, change: null, complete: null }, min: 0, _create: function() { // Constrain initial value this.oldValue = this.options.value = this._constrainedValue(); this.element .addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .attr({ // Only set static values, aria-valuenow and aria-valuemax are // set inside _refreshValue() role: "progressbar", "aria-valuemin": this.min }); this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" ) .appendTo( this.element ); this._refreshValue(); }, _destroy: function() { this.element .removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.valueDiv.remove(); }, value: function( newValue ) { if ( newValue === undefined ) { return this.options.value; } this.options.value = this._constrainedValue( newValue ); this._refreshValue(); }, _constrainedValue: function( newValue ) { if ( newValue === undefined ) { newValue = this.options.value; } this.indeterminate = newValue === false; // sanitize value if ( typeof newValue !== "number" ) { newValue = 0; } return this.indeterminate ? false : Math.min( this.options.max, Math.max( this.min, newValue ) ); }, _setOptions: function( options ) { // Ensure "value" option is set after other values (like max) var value = options.value; delete options.value; this._super( options ); this.options.value = this._constrainedValue( value ); this._refreshValue(); }, _setOption: function( key, value ) { if ( key === "max" ) { // Don't allow a max less than min value = Math.max( this.min, value ); } if ( key === "disabled" ) { this.element .toggleClass( "ui-state-disabled", !!value ) .attr( "aria-disabled", value ); } this._super( key, value ); }, _percentage: function() { return this.indeterminate ? 100 : 100 * ( this.options.value - this.min ) / ( this.options.max - this.min ); }, _refreshValue: function() { var value = this.options.value, percentage = this._percentage(); this.valueDiv .toggle( this.indeterminate || value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.toggleClass( "ui-progressbar-indeterminate", this.indeterminate ); if ( this.indeterminate ) { this.element.removeAttr( "aria-valuenow" ); if ( !this.overlayDiv ) { this.overlayDiv = $( "<div class='ui-progressbar-overlay'></div>" ).appendTo( this.valueDiv ); } } else { this.element.attr({ "aria-valuemax": this.options.max, "aria-valuenow": value }); if ( this.overlayDiv ) { this.overlayDiv.remove(); this.overlayDiv = null; } } if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } if ( value === this.options.max ) { this._trigger( "complete" ); } } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./position", "./menu" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.selectmenu", { version: "1.11.0", defaultElement: "<select>", options: { appendTo: null, disabled: null, icons: { button: "ui-icon-triangle-1-s" }, position: { my: "left top", at: "left bottom", collision: "none" }, width: null, // callbacks change: null, close: null, focus: null, open: null, select: null }, _create: function() { var selectmenuId = this.element.uniqueId().attr( "id" ); this.ids = { element: selectmenuId, button: selectmenuId + "-button", menu: selectmenuId + "-menu" }; this._drawButton(); this._drawMenu(); if ( this.options.disabled ) { this.disable(); } }, _drawButton: function() { var that = this, tabindex = this.element.attr( "tabindex" ); // Associate existing label with the new button this.label = $( "label[for='" + this.ids.element + "']" ).attr( "for", this.ids.button ); this._on( this.label, { click: function( event ) { this.button.focus(); event.preventDefault(); } }); // Hide original select element this.element.hide(); // Create button this.button = $( "<span>", { "class": "ui-selectmenu-button ui-widget ui-state-default ui-corner-all", tabindex: tabindex || this.options.disabled ? -1 : 0, id: this.ids.button, role: "combobox", "aria-expanded": "false", "aria-autocomplete": "list", "aria-owns": this.ids.menu, "aria-haspopup": "true" }) .insertAfter( this.element ); $( "<span>", { "class": "ui-icon " + this.options.icons.button }) .prependTo( this.button ); this.buttonText = $( "<span>", { "class": "ui-selectmenu-text" }) .appendTo( this.button ); this._setText( this.buttonText, this.element.find( "option:selected" ).text() ); this._setOption( "width", this.options.width ); this._on( this.button, this._buttonEvents ); this.button.one( "focusin", function() { // Delay rendering the menu items until the button receives focus. // The menu may have already been rendered via a programmatic open. if ( !that.menuItems ) { that._refreshMenu(); } }); this._hoverable( this.button ); this._focusable( this.button ); }, _drawMenu: function() { var that = this; // Create menu this.menu = $( "<ul>", { "aria-hidden": "true", "aria-labelledby": this.ids.button, id: this.ids.menu }); // Wrap menu this.menuWrap = $( "<div>", { "class": "ui-selectmenu-menu ui-front" }) .append( this.menu ) .appendTo( this._appendTo() ); // Initialize menu widget this.menuInstance = this.menu .menu({ role: "listbox", select: function( event, ui ) { event.preventDefault(); that._select( ui.item.data( "ui-selectmenu-item" ), event ); }, focus: function( event, ui ) { var item = ui.item.data( "ui-selectmenu-item" ); // Prevent inital focus from firing and check if its a newly focused item if ( that.focusIndex != null && item.index !== that.focusIndex ) { that._trigger( "focus", event, { item: item } ); if ( !that.isOpen ) { that._select( item, event ); } } that.focusIndex = item.index; that.button.attr( "aria-activedescendant", that.menuItems.eq( item.index ).attr( "id" ) ); } }) .menu( "instance" ); // Adjust menu styles to dropdown this.menu .addClass( "ui-corner-bottom" ) .removeClass( "ui-corner-all" ); // Don't close the menu on mouseleave this.menuInstance._off( this.menu, "mouseleave" ); // Cancel the menu's collapseAll on document click this.menuInstance._closeOnDocumentClick = function() { return false; }; // Selects often contain empty items, but never contain dividers this.menuInstance._isDivider = function() { return false; }; }, refresh: function() { this._refreshMenu(); this._setText( this.buttonText, this._getSelectedItem().text() ); this._setOption( "width", this.options.width ); }, _refreshMenu: function() { this.menu.empty(); var item, options = this.element.find( "option" ); if ( !options.length ) { return; } this._parseOptions( options ); this._renderMenu( this.menu, this.items ); this.menuInstance.refresh(); this.menuItems = this.menu.find( "li" ).not( ".ui-selectmenu-optgroup" ); item = this._getSelectedItem(); // Update the menu to have the correct item focused this.menuInstance.focus( null, item ); this._setAria( item.data( "ui-selectmenu-item" ) ); // Set disabled state this._setOption( "disabled", this.element.prop( "disabled" ) ); }, open: function( event ) { if ( this.options.disabled ) { return; } // If this is the first time the menu is being opened, render the items if ( !this.menuItems ) { this._refreshMenu(); } else { // Menu clears focus on close, reset focus to selected item this.menu.find( ".ui-state-focus" ).removeClass( "ui-state-focus" ); this.menuInstance.focus( null, this._getSelectedItem() ); } this.isOpen = true; this._toggleAttr(); this._resizeMenu(); this._position(); this._on( this.document, this._documentClick ); this._trigger( "open", event ); }, _position: function() { this.menuWrap.position( $.extend( { of: this.button }, this.options.position ) ); }, close: function( event ) { if ( !this.isOpen ) { return; } this.isOpen = false; this._toggleAttr(); this._off( this.document ); this._trigger( "close", event ); }, widget: function() { return this.button; }, menuWidget: function() { return this.menu; }, _renderMenu: function( ul, items ) { var that = this, currentOptgroup = ""; $.each( items, function( index, item ) { if ( item.optgroup !== currentOptgroup ) { $( "<li>", { "class": "ui-selectmenu-optgroup ui-menu-divider" + ( item.element.parent( "optgroup" ).prop( "disabled" ) ? " ui-state-disabled" : "" ), text: item.optgroup }) .appendTo( ul ); currentOptgroup = item.optgroup; } that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-selectmenu-item", item ); }, _renderItem: function( ul, item ) { var li = $( "<li>" ); if ( item.disabled ) { li.addClass( "ui-state-disabled" ); } this._setText( li, item.label ); return li.appendTo( ul ); }, _setText: function( element, value ) { if ( value ) { element.text( value ); } else { element.html( " " ); } }, _move: function( direction, event ) { var item, next, filter = ".ui-menu-item"; if ( this.isOpen ) { item = this.menuItems.eq( this.focusIndex ); } else { item = this.menuItems.eq( this.element[ 0 ].selectedIndex ); filter += ":not(.ui-state-disabled)"; } if ( direction === "first" || direction === "last" ) { next = item[ direction === "first" ? "prevAll" : "nextAll" ]( filter ).eq( -1 ); } else { next = item[ direction + "All" ]( filter ).eq( 0 ); } if ( next.length ) { this.menuInstance.focus( event, next ); } }, _getSelectedItem: function() { return this.menuItems.eq( this.element[ 0 ].selectedIndex ); }, _toggle: function( event ) { this[ this.isOpen ? "close" : "open" ]( event ); }, _documentClick: { mousedown: function( event ) { if ( !this.isOpen ) { return; } if ( !$( event.target ).closest( ".ui-selectmenu-menu, #" + this.ids.button ).length ) { this.close( event ); } } }, _buttonEvents: { click: "_toggle", keydown: function( event ) { var preventDefault = true; switch ( event.keyCode ) { case $.ui.keyCode.TAB: case $.ui.keyCode.ESCAPE: this.close( event ); preventDefault = false; break; case $.ui.keyCode.ENTER: if ( this.isOpen ) { this._selectFocusedItem( event ); } break; case $.ui.keyCode.UP: if ( event.altKey ) { this._toggle( event ); } else { this._move( "prev", event ); } break; case $.ui.keyCode.DOWN: if ( event.altKey ) { this._toggle( event ); } else { this._move( "next", event ); } break; case $.ui.keyCode.SPACE: if ( this.isOpen ) { this._selectFocusedItem( event ); } else { this._toggle( event ); } break; case $.ui.keyCode.LEFT: this._move( "prev", event ); break; case $.ui.keyCode.RIGHT: this._move( "next", event ); break; case $.ui.keyCode.HOME: case $.ui.keyCode.PAGE_UP: this._move( "first", event ); break; case $.ui.keyCode.END: case $.ui.keyCode.PAGE_DOWN: this._move( "last", event ); break; default: this.menu.trigger( event ); preventDefault = false; } if ( preventDefault ) { event.preventDefault(); } } }, _selectFocusedItem: function( event ) { var item = this.menuItems.eq( this.focusIndex ); if ( !item.hasClass( "ui-state-disabled" ) ) { this._select( item.data( "ui-selectmenu-item" ), event ); } }, _select: function( item, event ) { var oldIndex = this.element[ 0 ].selectedIndex; // Change native select element this.element[ 0 ].selectedIndex = item.index; this._setText( this.buttonText, item.label ); this._setAria( item ); this._trigger( "select", event, { item: item } ); if ( item.index !== oldIndex ) { this._trigger( "change", event, { item: item } ); } this.close( event ); }, _setAria: function( item ) { var id = this.menuItems.eq( item.index ).attr( "id" ); this.button.attr({ "aria-labelledby": id, "aria-activedescendant": id }); this.menu.attr( "aria-activedescendant", id ); }, _setOption: function( key, value ) { if ( key === "icons" ) { this.button.find( "span.ui-icon" ) .removeClass( this.options.icons.button ) .addClass( value.button ); } this._super( key, value ); if ( key === "appendTo" ) { this.menuWrap.appendTo( this._appendTo() ); } if ( key === "disabled" ) { this.menuInstance.option( "disabled", value ); this.button .toggleClass( "ui-state-disabled", value ) .attr( "aria-disabled", value ); this.element.prop( "disabled", value ); if ( value ) { this.button.attr( "tabindex", -1 ); this.close(); } else { this.button.attr( "tabindex", 0 ); } } if ( key === "width" ) { if ( !value ) { value = this.element.outerWidth(); } this.button.outerWidth( value ); } }, _appendTo: function() { var element = this.options.appendTo; if ( element ) { element = element.jquery || element.nodeType ? $( element ) : this.document.find( element ).eq( 0 ); } if ( !element || !element[ 0 ] ) { element = this.element.closest( ".ui-front" ); } if ( !element.length ) { element = this.document[ 0 ].body; } return element; }, _toggleAttr: function() { this.button .toggleClass( "ui-corner-top", this.isOpen ) .toggleClass( "ui-corner-all", !this.isOpen ) .attr( "aria-expanded", this.isOpen ); this.menuWrap.toggleClass( "ui-selectmenu-open", this.isOpen ); this.menu.attr( "aria-hidden", !this.isOpen ); }, _resizeMenu: function() { this.menu.outerWidth( Math.max( this.button.outerWidth(), // support: IE10 // IE10 wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping this.menu.width( "" ).outerWidth() + 1 ) ); }, _getCreateOptions: function() { return { disabled: this.element.prop( "disabled" ) }; }, _parseOptions: function( options ) { var data = []; options.each(function( index, item ) { var option = $( item ), optgroup = option.parent( "optgroup" ); data.push({ element: option, index: index, value: option.attr( "value" ), label: option.text(), optgroup: optgroup.attr( "label" ) || "", disabled: optgroup.prop( "disabled" ) || option.prop( "disabled" ) }); }); this.items = data; }, _destroy: function() { this.menuWrap.remove(); this.button.remove(); this.element.show(); this.element.removeUniqueId(); this.label.attr( "for", this.ids.element ); } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./mouse", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.slider", $.ui.mouse, { version: "1.11.0", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null, // callbacks change: null, slide: null, start: null, stop: null }, // number of pages in a slider // (how many times can you page up/down to go through the whole range) numPages: 5, _create: function() { this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass( "ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this._refresh(); this._setOption( "disabled", this.options.disabled ); this._animateOff = false; }, _refresh: function() { this._createRange(); this._createHandles(); this._setupEvents(); this._refreshValue(); }, _createHandles: function() { var i, handleCount, options = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<span class='ui-slider-handle ui-state-default ui-corner-all' tabindex='0'></span>", handles = []; handleCount = ( options.values && options.values.length ) || 1; if ( existingHandles.length > handleCount ) { existingHandles.slice( handleCount ).remove(); existingHandles = existingHandles.slice( 0, handleCount ); } for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); }, _createRange: function() { var options = this.options, classes = ""; if ( options.range ) { if ( options.range === true ) { if ( !options.values ) { options.values = [ this._valueMin(), this._valueMin() ]; } else if ( options.values.length && options.values.length !== 2 ) { options.values = [ options.values[0], options.values[0] ]; } else if ( $.isArray( options.values ) ) { options.values = options.values.slice(0); } } if ( !this.range || !this.range.length ) { this.range = $( "<div></div>" ) .appendTo( this.element ); classes = "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header ui-corner-all"; } else { this.range.removeClass( "ui-slider-range-min ui-slider-range-max" ) // Handle range switching from true to min/max .css({ "left": "", "bottom": "" }); } this.range.addClass( classes + ( ( options.range === "min" || options.range === "max" ) ? " ui-slider-range-" + options.range : "" ) ); } else { if ( this.range ) { this.range.remove(); } this.range = null; } }, _setupEvents: function() { this._off( this.handles ); this._on( this.handles, this._handleEvents ); this._hoverable( this.handles ); this._focusable( this.handles ); }, _destroy: function() { this.handles.remove(); if ( this.range ) { this.range.remove(); } this.element .removeClass( "ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-widget" + " ui-widget-content" + " ui-corner-all" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if (( distance > thisDistance ) || ( distance === thisDistance && (i === that._lastChangedValue || that.values(i) === o.min ))) { distance = thisDistance; closestHandle = $( this ); index = i; } }); allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().addBack().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, this._handleIndex ); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal"; }, _normValueFromMouse: function( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } //store the last changed value index for reference when handles overlap this._lastChangedValue = index; this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( key === "range" && this.options.range === true ) { if ( value === "min" ) { this.options.value = this._values( 0 ); this.options.values = null; } else if ( value === "max" ) { this.options.value = this._values( this.options.values.length - 1 ); this.options.values = null; } } if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } if ( key === "disabled" ) { this.element.toggleClass( "ui-state-disabled", !!value ); } this._super( key, value ); switch ( key ) { case "orientation": this._detectOrientation(); this.element .removeClass( "ui-slider-horizontal ui-slider-vertical" ) .addClass( "ui-slider-" + this.orientation ); this._refreshValue(); break; case "value": this._animateOff = true; this._refreshValue(); this._change( null, 0 ); this._animateOff = false; break; case "values": this._animateOff = true; this._refreshValue(); for ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case "range": this._animateOff = true; this._refresh(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else if ( this.options.values && this.options.values.length ) { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } else { return []; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } }, _handleEvents: { keydown: function( event ) { var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( ( this._valueMax() - this._valueMin() ) / this.numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / this.numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).removeClass( "ui-state-active" ); } } } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./button" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { function spinner_modifier( fn ) { return function() { var previous = this.element.val(); fn.apply( this, arguments ); this._refresh(); if ( previous !== this.element.val() ) { this._trigger( "change" ); } }; } return $.widget( "ui.spinner", { version: "1.11.0", defaultElement: "<input>", widgetEventPrefix: "spin", options: { culture: null, icons: { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }, incremental: true, max: null, min: null, numberFormat: null, page: 10, step: 1, change: null, spin: null, start: null, stop: null }, _create: function() { // handle string values that need to be parsed this._setOption( "max", this.options.max ); this._setOption( "min", this.options.min ); this._setOption( "step", this.options.step ); // Only format if there is a value, prevents the field from being marked // as invalid in Firefox, see #9573. if ( this.value() !== "" ) { // Format the value, but don't constrain. this._value( this.element.val(), true ); } this._draw(); this._on( this._events ); this._refresh(); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _getCreateOptions: function() { var options = {}, element = this.element; $.each( [ "min", "max", "step" ], function( i, option ) { var value = element.attr( option ); if ( value !== undefined && value.length ) { options[ option ] = value; } }); return options; }, _events: { keydown: function( event ) { if ( this._start( event ) && this._keydown( event ) ) { event.preventDefault(); } }, keyup: "_stop", focus: function() { this.previous = this.element.val(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } this._stop(); this._refresh(); if ( this.previous !== this.element.val() ) { this._trigger( "change", event ); } }, mousewheel: function( event, delta ) { if ( !delta ) { return; } if ( !this.spinning && !this._start( event ) ) { return false; } this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); clearTimeout( this.mousewheelTimer ); this.mousewheelTimer = this._delay(function() { if ( this.spinning ) { this._stop( event ); } }, 100 ); event.preventDefault(); }, "mousedown .ui-spinner-button": function( event ) { var previous; // We never want the buttons to have focus; whenever the user is // interacting with the spinner, the focus should be on the input. // If the input is focused then this.previous is properly set from // when the input first received focus. If the input is not focused // then we need to set this.previous based on the value before spinning. previous = this.element[0] === this.document[0].activeElement ? this.previous : this.element.val(); function checkFocus() { var isActive = this.element[0] === this.document[0].activeElement; if ( !isActive ) { this.element.focus(); this.previous = previous; // support: IE // IE sets focus asynchronously, so we need to check if focus // moved off of the input because the user clicked on the button. this._delay(function() { this.previous = previous; }); } } // ensure focus is on (or stays on) the text field event.preventDefault(); checkFocus.call( this ); // support: IE // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event // and check (again) if focus moved off of the input. this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; checkFocus.call( this ); }); if ( this._start( event ) === false ) { return; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, "mouseup .ui-spinner-button": "_stop", "mouseenter .ui-spinner-button": function( event ) { // button will add ui-state-active if mouse was down while mouseleave and kept down if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { return; } if ( this._start( event ) === false ) { return false; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, // TODO: do we really want to consider this a stop? // shouldn't we just stop the repeater and wait until mouseup before // we trigger the stop event? "mouseleave .ui-spinner-button": "_stop" }, _draw: function() { var uiSpinner = this.uiSpinner = this.element .addClass( "ui-spinner-input" ) .attr( "autocomplete", "off" ) .wrap( this._uiSpinnerHtml() ) .parent() // add buttons .append( this._buttonHtml() ); this.element.attr( "role", "spinbutton" ); // button bindings this.buttons = uiSpinner.find( ".ui-spinner-button" ) .attr( "tabIndex", -1 ) .button() .removeClass( "ui-corner-all" ); // IE 6 doesn't understand height: 50% for the buttons // unless the wrapper has an explicit height if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && uiSpinner.height() > 0 ) { uiSpinner.height( uiSpinner.height() ); } // disable spinner if element was already disabled if ( this.options.disabled ) { this.disable(); } }, _keydown: function( event ) { var options = this.options, keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.UP: this._repeat( null, 1, event ); return true; case keyCode.DOWN: this._repeat( null, -1, event ); return true; case keyCode.PAGE_UP: this._repeat( null, options.page, event ); return true; case keyCode.PAGE_DOWN: this._repeat( null, -options.page, event ); return true; } return false; }, _uiSpinnerHtml: function() { return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; }, _buttonHtml: function() { return "" + "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + "<span class='ui-icon " + this.options.icons.up + "'>▲</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>▼</span>" + "</a>"; }, _start: function( event ) { if ( !this.spinning && this._trigger( "start", event ) === false ) { return false; } if ( !this.counter ) { this.counter = 1; } this.spinning = true; return true; }, _repeat: function( i, steps, event ) { i = i || 500; clearTimeout( this.timer ); this.timer = this._delay(function() { this._repeat( 40, steps, event ); }, i ); this._spin( steps * this.options.step, event ); }, _spin: function( step, event ) { var value = this.value() || 0; if ( !this.counter ) { this.counter = 1; } value = this._adjustValue( value + step * this._increment( this.counter ) ); if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { this._value( value ); this.counter++; } }, _increment: function( i ) { var incremental = this.options.incremental; if ( incremental ) { return $.isFunction( incremental ) ? incremental( i ) : Math.floor( i * i * i / 50000 - i * i / 500 + 17 * i / 200 + 1 ); } return 1; }, _precision: function() { var precision = this._precisionOf( this.options.step ); if ( this.options.min !== null ) { precision = Math.max( precision, this._precisionOf( this.options.min ) ); } return precision; }, _precisionOf: function( num ) { var str = num.toString(), decimal = str.indexOf( "." ); return decimal === -1 ? 0 : str.length - decimal - 1; }, _adjustValue: function( value ) { var base, aboveMin, options = this.options; // make sure we're at a valid step // - find out where we are relative to the base (min or 0) base = options.min !== null ? options.min : 0; aboveMin = value - base; // - round to the nearest step aboveMin = Math.round(aboveMin / options.step) * options.step; // - rounding is based on 0, so adjust back to our base value = base + aboveMin; // fix precision from bad JS floating point math value = parseFloat( value.toFixed( this._precision() ) ); // clamp the value if ( options.max !== null && value > options.max) { return options.max; } if ( options.min !== null && value < options.min ) { return options.min; } return value; }, _stop: function( event ) { if ( !this.spinning ) { return; } clearTimeout( this.timer ); clearTimeout( this.mousewheelTimer ); this.counter = 0; this.spinning = false; this._trigger( "stop", event ); }, _setOption: function( key, value ) { if ( key === "culture" || key === "numberFormat" ) { var prevValue = this._parse( this.element.val() ); this.options[ key ] = value; this.element.val( this._format( prevValue ) ); return; } if ( key === "max" || key === "min" || key === "step" ) { if ( typeof value === "string" ) { value = this._parse( value ); } } if ( key === "icons" ) { this.buttons.first().find( ".ui-icon" ) .removeClass( this.options.icons.up ) .addClass( value.up ); this.buttons.last().find( ".ui-icon" ) .removeClass( this.options.icons.down ) .addClass( value.down ); } this._super( key, value ); if ( key === "disabled" ) { this.widget().toggleClass( "ui-state-disabled", !!value ); this.element.prop( "disabled", !!value ); this.buttons.button( value ? "disable" : "enable" ); } }, _setOptions: spinner_modifier(function( options ) { this._super( options ); }), _parse: function( val ) { if ( typeof val === "string" && val !== "" ) { val = window.Globalize && this.options.numberFormat ? Globalize.parseFloat( val, 10, this.options.culture ) : +val; } return val === "" || isNaN( val ) ? null : val; }, _format: function( value ) { if ( value === "" ) { return ""; } return window.Globalize && this.options.numberFormat ? Globalize.format( value, this.options.numberFormat, this.options.culture ) : value; }, _refresh: function() { this.element.attr({ "aria-valuemin": this.options.min, "aria-valuemax": this.options.max, // TODO: what should we do with values that can't be parsed? "aria-valuenow": this._parse( this.element.val() ) }); }, isValid: function() { var value = this.value(); // null is invalid if ( value === null ) { return false; } // if value gets adjusted, it's invalid return value === this._adjustValue( value ); }, // update the value without triggering change _value: function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }, _destroy: function() { this.element .removeClass( "ui-spinner-input" ) .prop( "disabled", false ) .removeAttr( "autocomplete" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: spinner_modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * this.options.step ); this._stop(); } }, stepDown: spinner_modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { if ( this._start() ) { this._spin( (steps || 1) * -this.options.step ); this._stop(); } }, pageUp: spinner_modifier(function( pages ) { this._stepUp( (pages || 1) * this.options.page ); }), pageDown: spinner_modifier(function( pages ) { this._stepDown( (pages || 1) * this.options.page ); }), value: function( newVal ) { if ( !arguments.length ) { return this._parse( this.element.val() ); } spinner_modifier( this._value ).call( this, newVal ); }, widget: function() { return this.uiSpinner; } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.tabs", { version: "1.11.0", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _isLocal: (function() { var rhash = /#.*$/; return function( anchor ) { var anchorUrl, locationUrl; // support: IE7 // IE7 doesn't normalize the href property when set via script (#9317) anchor = anchor.cloneNode( false ); anchorUrl = anchor.href.replace( rhash, "" ); locationUrl = location.href.replace( rhash, "" ); // decoding may throw an error if the URL isn't UTF-8 (#9518) try { anchorUrl = decodeURIComponent( anchorUrl ); } catch ( error ) {} try { locationUrl = decodeURIComponent( locationUrl ); } catch ( error ) {} return anchor.hash.length > 1 && anchorUrl === locationUrl; }; })(), _create: function() { var that = this, options = this.options; this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); options.active = this._initialActive(); // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _initialActive: function() { var active = this.options.active, collapsible = this.options.collapsible, locationHash = location.hash.substring( 1 ); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = collapsible ? false : 0; } } // don't allow collapsible: false and active: false if ( !collapsible && active === false && this.anchors.length ) { active = 0; } return active; }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", "aria-expanded": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( that._isLocal( anchor ) ) { selector = anchor.hash; panelId = selector.substring( 1 ); panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { // If the tab doesn't already have aria-controls, // generate an id by using a throw-away element panelId = tab.attr( "aria-controls" ) || $( {} ).uniqueId()[ 0 ].id; selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": panelId, "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.tablist || this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = {}; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); // Always prevent the default action, even when disabled this._on( true, this.anchors, { click: function( event ) { event.preventDefault(); } }); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, parent = this.element.parent(); if ( heightStyle === "fill" ) { maxHeight = parent.height(); maxHeight -= this.element.outerHeight() - this.element.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr( "aria-hidden", "true" ); eventData.oldTab.attr({ "aria-selected": "false", "aria-expanded": "false" }); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr( "aria-hidden", "false" ); eventData.newTab.attr({ "aria-selected": "true", "aria-expanded": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li .attr( "aria-controls", prev ) .removeData( "ui-tabs-aria-controls" ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( this._isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR: jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); })); (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./position" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { return $.widget( "ui.tooltip", { version: "1.11.0", options: { content: function() { // support: IE<9, Opera in jQuery <1.7 // .text() can't accept undefined, so coerce to a string var title = $( this ).attr( "title" ) || ""; // Escape title, since we're going from an attribute to raw HTML return $( "<a>" ).text( title ).html(); }, hide: true, // Disabled elements have inconsistent behavior across browsers (#8661) items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, open: null }, _addDescribedBy: function( elem, id ) { var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); describedby.push( id ); elem .data( "ui-tooltip-id", id ) .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); }, _removeDescribedBy: function( elem ) { var id = elem.data( "ui-tooltip-id" ), describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), index = $.inArray( id, describedby ); if ( index !== -1 ) { describedby.splice( index, 1 ); } elem.removeData( "ui-tooltip-id" ); describedby = $.trim( describedby.join( " " ) ); if ( describedby ) { elem.attr( "aria-describedby", describedby ); } else { elem.removeAttr( "aria-describedby" ); } }, _create: function() { this._on({ mouseover: "open", focusin: "open" }); // IDs of generated tooltips, needed for destroy this.tooltips = {}; // IDs of parent tooltips where we removed the title attribute this.parents = {}; if ( this.options.disabled ) { this._disable(); } // Append the aria-live region so tooltips announce correctly this.liveRegion = $( "<div>" ) .attr({ role: "log", "aria-live": "assertive", "aria-relevant": "additions" }) .addClass( "ui-helper-hidden-accessible" ) .appendTo( this.document[ 0 ].body ); }, _setOption: function( key, value ) { var that = this; if ( key === "disabled" ) { this[ value ? "_disable" : "_enable" ](); this.options[ key ] = value; // disable element style changes return; } this._super( key, value ); if ( key === "content" ) { $.each( this.tooltips, function( id, element ) { that._updateContent( element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); }); // remove title attributes to prevent native tooltips this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.is( "[title]" ) ) { element .data( "ui-tooltip-title", element.attr( "title" ) ) .removeAttr( "title" ); } }); }, _enable: function() { // restore title attributes this.element.find( this.options.items ).addBack().each(function() { var element = $( this ); if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } }); }, open: function( event ) { var that = this, target = $( event ? event.target : this.element ) // we need closest here due to mouseover bubbling, // but always pointing at the same event target .closest( this.options.items ); // No element to show a tooltip for or the tooltip is already open if ( !target.length || target.data( "ui-tooltip-id" ) ) { return; } if ( target.attr( "title" ) ) { target.data( "ui-tooltip-title", target.attr( "title" ) ); } target.data( "ui-tooltip-open", true ); // kill parent tooltips, custom or native, for hover if ( event && event.type === "mouseover" ) { target.parents().each(function() { var parent = $( this ), blurEvent; if ( parent.data( "ui-tooltip-open" ) ) { blurEvent = $.Event( "blur" ); blurEvent.target = blurEvent.currentTarget = this; that.close( blurEvent, true ); } if ( parent.attr( "title" ) ) { parent.uniqueId(); that.parents[ this.id ] = { element: this, title: parent.attr( "title" ) }; parent.attr( "title", "" ); } }); } this._updateContent( target, event ); }, _updateContent: function( target, event ) { var content, contentOption = this.options.content, that = this, eventType = event ? event.type : null; if ( typeof contentOption === "string" ) { return this._open( event, target, contentOption ); } content = contentOption.call( target[0], function( response ) { // ignore async response if tooltip was closed already if ( !target.data( "ui-tooltip-open" ) ) { return; } // IE may instantly serve a cached response for ajax requests // delay this call to _open so the other call to _open runs first that._delay(function() { // jQuery creates a special event for focusin when it doesn't // exist natively. To improve performance, the native event // object is reused and the type is changed. Therefore, we can't // rely on the type being correct after the event finished // bubbling, so we set it back to the previous value. (#8740) if ( event ) { event.type = eventType; } this._open( event, target, response ); }); }); if ( content ) { this._open( event, target, content ); } }, _open: function( event, target, content ) { var tooltip, events, delayedShow, a11yContent, positionOption = $.extend( {}, this.options.position ); if ( !content ) { return; } // Content can be updated multiple times. If the tooltip already // exists, then just update the content and bail. tooltip = this._find( target ); if ( tooltip.length ) { tooltip.find( ".ui-tooltip-content" ).html( content ); return; } // if we have a title, clear it to prevent the native tooltip // we have to check first to avoid defining a title if none exists // (we don't want to cause an element to start matching [title]) // // We use removeAttr only for key events, to allow IE to export the correct // accessible attributes. For mouse events, set to empty string to avoid // native tooltip showing up (happens only when removing inside mouseover). if ( target.is( "[title]" ) ) { if ( event && event.type === "mouseover" ) { target.attr( "title", "" ); } else { target.removeAttr( "title" ); } } tooltip = this._tooltip( target ); this._addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); // Support: Voiceover on OS X, JAWS on IE <= 9 // JAWS announces deletions even when aria-relevant="additions" // Voiceover will sometimes re-read the entire log region's contents from the beginning this.liveRegion.children().hide(); if ( content.clone ) { a11yContent = content.clone(); a11yContent.removeAttr( "id" ).find( "[id]" ).removeAttr( "id" ); } else { a11yContent = content; } $( "<div>" ).html( a11yContent ).appendTo( this.liveRegion ); function position( event ) { positionOption.of = event; if ( tooltip.is( ":hidden" ) ) { return; } tooltip.position( positionOption ); } if ( this.options.track && event && /^mouse/.test( event.type ) ) { this._on( this.document, { mousemove: position }); // trigger once to override element-relative positioning position( event ); } else { tooltip.position( $.extend({ of: target }, this.options.position ) ); } tooltip.hide(); this._show( tooltip, this.options.show ); // Handle tracking tooltips that are shown with a delay (#8644). As soon // as the tooltip is visible, position the tooltip using the most recent // event. if ( this.options.show && this.options.show.delay ) { delayedShow = this.delayedShow = setInterval(function() { if ( tooltip.is( ":visible" ) ) { position( positionOption.of ); clearInterval( delayedShow ); } }, $.fx.interval ); } this._trigger( "open", event, { tooltip: tooltip } ); events = { keyup: function( event ) { if ( event.keyCode === $.ui.keyCode.ESCAPE ) { var fakeEvent = $.Event(event); fakeEvent.currentTarget = target[0]; this.close( fakeEvent, true ); } } }; // Only bind remove handler for delegated targets. Non-delegated // tooltips will handle this in destroy. if ( target[ 0 ] !== this.element[ 0 ] ) { events.remove = function() { this._removeTooltip( tooltip ); }; } if ( !event || event.type === "mouseover" ) { events.mouseleave = "close"; } if ( !event || event.type === "focusin" ) { events.focusout = "close"; } this._on( true, target, events ); }, close: function( event ) { var that = this, target = $( event ? event.currentTarget : this.element ), tooltip = this._find( target ); // disabling closes the tooltip, so we need to track when we're closing // to avoid an infinite loop in case the tooltip becomes disabled on close if ( this.closing ) { return; } // Clear the interval for delayed tracking tooltips clearInterval( this.delayedShow ); // only set title if we had one before (see comment in _open()) // If the title attribute has changed since open(), don't restore if ( target.data( "ui-tooltip-title" ) && !target.attr( "title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } this._removeDescribedBy( target ); tooltip.stop( true ); this._hide( tooltip, this.options.hide, function() { that._removeTooltip( $( this ) ); }); target.removeData( "ui-tooltip-open" ); this._off( target, "mouseleave focusout keyup" ); // Remove 'remove' binding only on delegated targets if ( target[ 0 ] !== this.element[ 0 ] ) { this._off( target, "remove" ); } this._off( this.document, "mousemove" ); if ( event && event.type === "mouseleave" ) { $.each( this.parents, function( id, parent ) { $( parent.element ).attr( "title", parent.title ); delete that.parents[ id ]; }); } this.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); this.closing = false; }, _tooltip: function( element ) { var tooltip = $( "<div>" ) .attr( "role", "tooltip" ) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ), id = tooltip.uniqueId().attr( "id" ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); this.tooltips[ id ] = element; return tooltip; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? $( "#" + id ) : $(); }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); // Remove immediately; destroying an open tooltip doesn't use the // hide animation $( "#" + id ).remove(); // Restore the title if ( element.data( "ui-tooltip-title" ) ) { // If the title attribute has changed since open(), don't restore if ( !element.attr( "title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } element.removeData( "ui-tooltip-title" ); } }); this.liveRegion.remove(); } }); })); /* Chinese initialisation for the jQuery UI date picker plugin. */ /* Written by Cloudream (cloudream@gmail.com). */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "../datepicker" ], factory ); } else { // Browser globals factory( jQuery.datepicker ); } }(function( datepicker ) { datepicker.regional['zh-CN'] = { closeText: '???', prevText: '<???', nextText: '???>', currentText: '???', monthNames: ['????','???','???','???','???','???', '???','???','???','???','?????','?????'], monthNamesShort: ['????','???','???','???','???','???', '???','???','???','???','?????','?????'], dayNames: ['?????','?????','?????','?????','?????','?????','?????'], dayNamesShort: ['???','???','???','???','???','???','???'], dayNamesMin: ['??','??','??','??','??','??','??'], weekHeader: '??', dateFormat: 'yy-mm-dd', firstDay: 1, isRTL: false, showMonthAfterYear: true, yearSuffix: '??'}; datepicker.setDefaults(datepicker.regional['zh-CN']); return datepicker.regional['zh-CN']; })); /*! Flowplayer v5.4.6 (2014-08-14) | flowplayer.org/license */ !function($) { /* jQuery.browser for 1.9+ We all love feature detection but that's sometimes not enough. @author Tero Piirainen */ !function($) { if (!$.browser) { var b = $.browser = {}, ua = navigator.userAgent.toLowerCase(), match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(safari)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; if (match[1]) { b[match[1]] = true; b.version = match[2] || "0"; } } }(jQuery); // auto-install (any video tag with parent .flowplayer) $(function() { if (typeof $.fn.flowplayer == 'function') { $("video").parent(".flowplayer").flowplayer(); } }); var instances = [], extensions = [], UA = window.navigator.userAgent; /* flowplayer() */ window.flowplayer = function(fn) { return $.isFunction(fn) ? extensions.push(fn) : typeof fn == 'number' || fn === undefined ? instances[fn || 0] : $(fn).data("flowplayer"); }; $(window).on('beforeunload', function() { $.each(instances, function(i, api) { if (api.conf.splash) { api.unload(); } else { api.bind("error", function () { $(".flowplayer.is-error .fp-message").remove(); }); } }); }); var supportLocalStorage = false; try { if (typeof window.localStorage == "object") { window.localStorage.flowplayerTestStorage = "test"; supportLocalStorage = true; } } catch (ignored) {} $.extend(flowplayer, { version: '5.4.6', engine: {}, conf: {}, support: {}, defaults: { debug: false, // true = forced playback disabled: false, // first engine to try engine: 'html5', fullscreen: window == window.top, // keyboard shortcuts keyboard: true, // default aspect ratio ratio: 9 / 16, adaptiveRatio: false, // scale flash object to video's aspect ratio in normal mode? flashfit: false, rtmp: 0, splash: false, live: false, swf: "//releases.flowplayer.org/5.4.6/flowplayer.swf", speeds: [0.25, 0.5, 1, 1.5, 2], tooltip: true, // initial volume level volume: !supportLocalStorage ? 1 : localStorage.muted == "true" ? 0 : !isNaN(localStorage.volume) ? localStorage.volume || 1 : 1, // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#error-codes errors: [ // video exceptions '', 'Video loading aborted', 'Network error', 'Video not properly encoded', 'Video file not found', // player exceptions 'Unsupported video', 'Skin not found', 'SWF file not found', 'Subtitles not found', 'Invalid RTMP URL', 'Unsupported video format. Try installing Adobe Flash.' ], errorUrls: ['','','','','','','','','','', 'http://get.adobe.com/flashplayer/' ], playlist: [] } }); // keep track of players var playerCount = 1; // jQuery plugin $.fn.flowplayer = function(opts, callback) { if (typeof opts == 'string') opts = { swf: opts } if ($.isFunction(opts)) { callback = opts; opts = {} } return !opts && this.data("flowplayer") || this.each(function() { // private variables var root = $(this).addClass("is-loading"), conf = $.extend({}, flowplayer.defaults, flowplayer.conf, opts, root.data()), videoTag = $("video", root).addClass("fp-engine").removeAttr("controls"), urlResolver = videoTag.length ? new URLResolver(videoTag) : null, storage = {}, lastSeekPosition, engine; if (conf.playlist.length) { // Create initial video tag if called without var preload = videoTag.attr('preload'), placeHolder; if (videoTag.length) videoTag.replaceWith(placeHolder = $('<p />')); videoTag = $('<video />').addClass('fp-engine'); placeHolder ? placeHolder.replaceWith(videoTag) : root.prepend(videoTag); if (flowplayer.support.video) videoTag.attr('preload', preload); if (typeof conf.playlist[0] === 'string') videoTag.attr('src', conf.playlist[0]); else { $.each(conf.playlist[0], function(i, plObj) { for (var type in plObj) { if (plObj.hasOwnProperty(type)) { videoTag.append($('<source />').attr({type: 'video/' + type, src: plObj[type]})); } } }); } urlResolver = new URLResolver(videoTag); } //stop old instance var oldApi = root.data('flowplayer'); if (oldApi) oldApi.unload(); root.data('fp-player_id', root.data('fp-player_id') || playerCount++); try { storage = window.localStorage || storage; } catch(e) {} var isRTL = (this.currentStyle && this.currentStyle['direction'] === 'rtl') || (window.getComputedStyle && window.getComputedStyle(this, null).getPropertyValue('direction') === 'rtl'); if (isRTL) root.addClass('is-rtl'); /*** API ***/ var api = oldApi || { // properties conf: conf, currentSpeed: 1, volumeLevel: typeof conf.volume === "undefined" ? storage.volume * 1 : conf.volume, video: {}, // states disabled: false, finished: false, loading: false, muted: storage.muted == "true" || conf.muted, paused: false, playing: false, ready: false, splash: false, rtl: isRTL, // methods load: function(video, callback) { if (api.error || api.loading || api.disabled) return; // resolve URL video = urlResolver.resolve(video); $.extend(video, engine.pick(video.sources)); if (video.src) { var e = $.Event("load"); root.trigger(e, [api, video, engine]); if (!e.isDefaultPrevented()) { engine.load(video); // callback if ($.isFunction(video)) callback = video; if (callback) root.one("ready", callback); } else { api.loading = false; } } return api; }, pause: function(fn) { if (api.ready && !api.seeking && !api.disabled && !api.loading) { engine.pause(); api.one("pause", fn); } return api; }, resume: function() { if (api.ready && api.paused && !api.disabled) { engine.resume(); // Firefox (+others?) does not fire "resume" after finish if (api.finished) { api.trigger("resume", [api]); api.finished = false; } } return api; }, toggle: function() { return api.ready ? api.paused ? api.resume() : api.pause() : api.load(); }, /* seek(1.4) -> 1.4s time seek(true) -> 10% forward seek(false) -> 10% backward */ seek: function(time, callback) { if (api.ready) { if (typeof time == "boolean") { var delta = api.video.duration * 0.1; time = api.video.time + (time ? delta : -delta); } time = lastSeekPosition = Math.min(Math.max(time, 0), api.video.duration).toFixed(1); var ev = $.Event('beforeseek'); root.trigger(ev, [api, time]); if (!ev.isDefaultPrevented()) { engine.seek(time); if ($.isFunction(callback)) root.one("seek", callback); } else { api.seeking = false; root.toggleClass("is-seeking", api.seeking); // remove loading indicator } } return api; }, /* seekTo(1) -> 10% seekTo(2) -> 20% seekTo(3) -> 30% ... seekTo() -> last position */ seekTo: function(position, fn) { var time = position === undefined ? lastSeekPosition : api.video.duration * 0.1 * position; return api.seek(time, fn); }, mute: function(flag) { if (flag === undefined) flag = !api.muted; storage.muted = api.muted = flag; storage.volume = !isNaN(storage.volume) ? storage.volume : conf.volume; // make sure storage has volume api.volume(flag ? 0 : storage.volume, true); api.trigger("mute", flag); return api; }, volume: function(level, skipStore) { if (api.ready) { level = Math.min(Math.max(level, 0), 1); if (!skipStore) storage.volume = level; engine.volume(level); } return api; }, speed: function(val, callback) { if (api.ready) { // increase / decrease if (typeof val == "boolean") { val = conf.speeds[$.inArray(api.currentSpeed, conf.speeds) + (val ? 1 : -1)] || api.currentSpeed; } engine.speed(val); if (callback) root.one("speed", callback); } return api; }, stop: function() { if (api.ready) { api.pause(); api.seek(0, function() { root.trigger("stop"); }); } return api; }, unload: function() { if (!root.hasClass("is-embedding")) { if (conf.splash) { api.trigger("unload"); engine.unload(); } else { api.stop(); } } return api; }, disable: function(flag) { if (flag === undefined) flag = !api.disabled; if (flag != api.disabled) { api.disabled = flag; api.trigger("disable", flag); } return api; } }; api.conf = $.extend(api.conf, conf); /* event binding / unbinding */ $.each(['bind', 'one', 'unbind'], function(i, key) { api[key] = function(type, fn) { root[key](type, fn); return api; }; }); api.trigger = function(event, arg) { root.trigger(event, [api, arg]); return api; }; /*** Behaviour ***/ if (!root.data('flowplayer')) { // Only bind once root.bind("boot", function() { // conf $.each(['autoplay', 'loop', 'preload', 'poster'], function(i, key) { var val = videoTag.attr(key); if (val !== undefined) conf[key] = val ? val : true; }); // splash if (conf.splash || root.hasClass("is-splash") || !flowplayer.support.firstframe) { api.forcedSplash = !conf.splash && !root.hasClass("is-splash"); api.splash = conf.splash = conf.autoplay = true; root.addClass("is-splash"); if (flowplayer.support.video) videoTag.attr("preload", "none"); } if (conf.live || root.hasClass('is-live')) { api.live = conf.live = true; root.addClass('is-live'); } // extensions $.each(extensions, function(i) { this(api, root); }); // 1. use the configured engine engine = flowplayer.engine[conf.engine]; if (engine) engine = engine(api, root); if (engine.pick(urlResolver.initialSources)) { api.engine = conf.engine; // 2. failed -> try another } else { $.each(flowplayer.engine, function(name, impl) { if (name != conf.engine) { engine = this(api, root); if (engine.pick(urlResolver.initialSources)) api.engine = name; return false; } }); } // instances instances.push(api); // no engine if (!api.engine) return api.trigger("error", { code: flowplayer.support.flashVideo ? 5 : 10 }); // start conf.splash ? api.unload() : api.load(); // disabled if (conf.disabled) api.disable(); //initial volumelevel engine.volume(api.volumeLevel); // initial callback root.one("ready", callback); }).bind("load", function(e, api, video) { // unload others if (conf.splash) { $(".flowplayer").filter(".is-ready, .is-loading").not(root).each(function() { var api = $(this).data("flowplayer"); if (api.conf.splash) api.unload(); }); } // loading root.addClass("is-loading"); api.loading = true; }).bind("ready", function(e, api, video) { video.time = 0; api.video = video; function notLoading() { root.removeClass("is-loading"); api.loading = false; } if (conf.splash) root.one("progress", notLoading); else notLoading(); // saved state if (api.muted) api.mute(true); else api.volume(api.volumeLevel); }).bind("unload", function(e) { if (conf.splash) videoTag.remove(); root.removeClass("is-loading"); api.loading = false; }).bind("ready unload", function(e) { var is_ready = e.type == "ready"; root.toggleClass("is-splash", !is_ready).toggleClass("is-ready", is_ready); api.ready = is_ready; api.splash = !is_ready; }).bind("progress", function(e, api, time) { api.video.time = time; }).bind("speed", function(e, api, val) { api.currentSpeed = val; }).bind("volume", function(e, api, level) { api.volumeLevel = Math.round(level * 100) / 100; if (!api.muted) storage.volume = level; else if (level) api.mute(false); }).bind("beforeseek seek", function(e) { api.seeking = e.type == "beforeseek"; root.toggleClass("is-seeking", api.seeking); }).bind("ready pause resume unload finish stop", function(e, _api, video) { // PAUSED: pause / finish api.paused = /pause|finish|unload|stop/.test(e.type); // SHAKY HACK: first-frame / preload=none if (e.type == "ready") { api.paused = conf.preload == 'none'; if (video) { api.paused = !video.duration || !conf.autoplay && (conf.preload != 'none'); } } // the opposite api.playing = !api.paused; // CSS classes root.toggleClass("is-paused", api.paused).toggleClass("is-playing", api.playing); // sanity check if (!api.load.ed) api.pause(); }).bind("finish", function(e) { api.finished = true; }).bind("error", function() { videoTag.remove(); }); } // boot root.trigger("boot", [api, root]).data("flowplayer", api); }); }; !function() { var parseIpadVersion = function(UA) { var e = /Version\/(\d\.\d)/.exec(UA); if (e && e.length > 1) { return parseFloat(e[1], 10); } return 0; }; var s = flowplayer.support, browser = $.browser, video = $("<video loop autoplay preload/>")[0], IS_IE = browser.msie, UA = navigator.userAgent, IS_IPAD = /iPad|MeeGo/.test(UA) && !/CriOS/.test(UA), IS_IPAD_CHROME = /iPad/.test(UA) && /CriOS/.test(UA), IS_IPHONE = /iP(hone|od)/i.test(UA) && !/iPad/.test(UA), IS_ANDROID = /Android/.test(UA) && !/Firefox/.test(UA), IS_ANDROID_FIREFOX = /Android/.test(UA) && /Firefox/.test(UA), IS_SILK = /Silk/.test(UA), IS_WP = /IEMobile/.test(UA), IPAD_VER = IS_IPAD ? parseIpadVersion(UA) : 0, ANDROID_VER = IS_ANDROID ? parseFloat(/Android\ (\d\.\d)/.exec(UA)[1], 10) : 0; $.extend(s, { subtitles: !!video.addTextTrack, fullscreen: !IS_ANDROID && (typeof document.webkitCancelFullScreen == 'function' && !/Mac OS X 10_5.+Version\/5\.0\.\d Safari/.test(UA) || document.mozFullScreenEnabled || typeof document.exitFullscreen == 'function'), inlineBlock: !(IS_IE && browser.version < 8), touch: ('ontouchstart' in window), dataload: !IS_IPAD && !IS_IPHONE && !IS_WP, zeropreload: !IS_IE && !IS_ANDROID, // IE supports only preload=metadata volume: !IS_IPAD && !IS_ANDROID && !IS_IPHONE && !IS_SILK && !IS_IPAD_CHROME, cachedVideoTag: !IS_IPAD && !IS_IPHONE && !IS_IPAD_CHROME && !IS_WP, firstframe: !IS_IPHONE && !IS_IPAD && !IS_ANDROID && !IS_SILK && !IS_IPAD_CHROME && !IS_WP && !IS_ANDROID_FIREFOX, inlineVideo: !IS_IPHONE && !IS_WP && (!IS_ANDROID || ANDROID_VER >= 3), hlsDuration: !browser.safari || IS_IPAD || IS_IPHONE || IS_IPAD_CHROME, seekable: !IS_IPAD && !IS_IPAD_CHROME }); // flashVideo try { var plugin = navigator.plugins["Shockwave Flash"], ver = IS_IE ? new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable('$version') : plugin.description; if (!IS_IE && !plugin[0].enabledPlugin) s.flashVideo = false; else { ver = ver.split(/\D+/); if (ver.length && !ver[0]) ver = ver.slice(1); s.flashVideo = ver[0] > 9 || ver[0] == 9 && ver[3] >= 115; } } catch (ignored) {} try { s.video = !!video.canPlayType; s.video && video.canPlayType('video/mp4'); } catch (e) { s.video = false; } // animation s.animation = (function() { var vendors = ['','Webkit','Moz','O','ms','Khtml'], el = $("<p/>")[0]; for (var i = 0; i < vendors.length; i++) { if (el.style[vendors[i] + 'AnimationName'] !== 'undefined') return true; } })(); }(); /* The most minimal Flash embedding */ // movie required in opts function embed(swf, flashvars) { var id = "obj" + ("" + Math.random()).slice(2, 15), tag = '<object class="fp-engine" id="' + id+ '" name="' + id + '" '; tag += $.browser.msie ? 'classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">' : ' data="' + swf + '" type="application/x-shockwave-flash">'; var opts = { width: "100%", height: "100%", allowscriptaccess: "always", wmode: "transparent", quality: "high", flashvars: "", // https://github.com/flowplayer/flowplayer/issues/13#issuecomment-9369919 movie: swf + ($.browser.msie ? "?" + id : ""), name: id }; // flashvars $.each(flashvars, function(key, value) { opts.flashvars += key + "=" + value + "&"; }); // parameters $.each(opts, function(key, value) { tag += '<param name="' + key + '" value="'+ value +'"/>'; }); tag += "</object>"; return $(tag); } // Flash is buggy allover if (window.attachEvent) { window.attachEvent("onbeforeunload", function() { __flash_savedUnloadHandler = __flash_unloadHandler = function() {}; }); } flowplayer.engine.flash = function(player, root) { var conf = player.conf, video = player.video, callbackId, objectTag, api; var engine = { pick: function(sources) { if (flowplayer.support.flashVideo) { // always pick video/flash first var flash = $.grep(sources, function(source) { return source.type == 'flash'; })[0]; if (flash) return flash; for (var i = 0, source; i < sources.length; i++) { source = sources[i]; if (/mp4|flv/.test(source.type)) return source; } } }, load: function(video) { function escapeURL(url) { return url.replace(/&/g, '%26').replace(/&/g, '%26').replace(/=/g, '%3D'); } var html5Tag = $("video", root), url = escapeURL(video.src); is_absolute = /^https?:/.test(url); // html5 tag not needed (pause needed for firefox) try { if (html5Tag.length > 0 && flowplayer.support.video) html5Tag[0].pause(); } catch (e) { // Omit errors on calling pause(), see https://github.com/flowplayer/flowplayer/issues/490 } var removeTag = function() { html5Tag.remove(); }; var hasSupportedSource = function(sources) { return $.grep(sources, function(src) { return !!html5Tag[0].canPlayType('video/' + src.type); }).length > 0; }; if (flowplayer.support.video && html5Tag.prop('autoplay') && hasSupportedSource(video.sources)) html5Tag.one('timeupdate', removeTag); else removeTag(); // convert to absolute if (!is_absolute && !conf.rtmp) url = $("<img/>").attr("src", url)[0].src; if (api) { api.__play(url); } else { callbackId = "fp" + ("" + Math.random()).slice(3, 15); var opts = { hostname: conf.embedded ? conf.hostname : location.hostname, url: url, callback: "jQuery."+ callbackId }; if (root.data("origin")) { opts.origin = root.data("origin"); } if (is_absolute) delete conf.rtmp; // optional conf $.each(['key', 'autoplay', 'preload', 'rtmp', 'loop', 'debug', 'preload', 'splash', 'bufferTime'], function(i, key) { if (conf[key]) opts[key] = conf[key]; }); // issue #376 if (opts.rtmp) { opts.rtmp = escapeURL(opts.rtmp); } objectTag = embed(conf.swf, opts); objectTag.prependTo(root); api = objectTag[0]; // throw error if no loading occurs setTimeout(function() { try { if (!api.PercentLoaded()) { return root.trigger("error", [player, { code: 7, url: conf.swf }]); } } catch (e) {} }, 5000); // detect disabled flash setTimeout(function() { if (typeof api.PercentLoaded === 'undefined') { root.trigger('flashdisabled', [player]); } }, 1000); // listen $[callbackId] = function(type, arg) { if (conf.debug && type != "status") console.log("--", type, arg); var event = $.Event(type); switch (type) { // RTMP sends a lot of finish events in vain // case "finish": if (conf.rtmp) return; case "ready": arg = $.extend(video, arg); break; case "click": event.flash = true; break; case "keydown": event.which = arg; break; case "seek": video.time = arg; break; case "status": player.trigger("progress", arg.time); if (arg.buffer < video.bytes && !video.buffered) { video.buffer = arg.buffer / video.bytes * video.duration; player.trigger("buffer", video.buffer); } else if (!video.buffered) { video.buffered = true; player.trigger("buffered"); } break; } if (type != 'buffered') { // add some delay so that player is truly ready after an event setTimeout(function() { player.trigger(event, arg); }, 1) } }; } }, // not supported yet speed: $.noop, unload: function() { api && api.__unload && api.__unload(); delete $[callbackId]; $("object", root).remove(); api = 0; } }; $.each("pause,resume,seek,volume".split(","), function(i, name) { engine[name] = function(arg) { try { if (player.ready) { if (name == 'seek' && player.video.time && !player.paused) { player.trigger("beforeseek"); } if (arg === undefined) { api["__" + name](); } else { api["__" + name](arg); } } } catch (e) { if (typeof api["__" + name] === 'undefined') { //flash lost it's methods return root.trigger('flashdisabled', [player]); } throw e; } }; }); var win = $(window); // handle Flash object aspect ratio player.bind("ready fullscreen fullscreen-exit", function(e) { var origH = root.height(), origW = root.width(); if (player.conf.flashfit || /full/.test(e.type)) { var fs = player.isFullscreen, truefs = fs && FS_SUPPORT, ie7 = !flowplayer.support.inlineBlock, screenW = fs ? (truefs ? screen.width : win.width()) : origW, screenH = fs ? (truefs ? screen.height : win.height()) : origH, // default values for fullscreen-exit without flashfit hmargin = 0, vmargin = 0, objwidth = ie7 ? origW : '', objheight = ie7 ? origH : '', aspectratio, dataratio; if (player.conf.flashfit || e.type === "fullscreen") { aspectratio = player.video.width / player.video.height, dataratio = player.video.height / player.video.width, objheight = Math.max(dataratio * screenW), objwidth = Math.max(aspectratio * screenH); objheight = objheight > screenH ? objwidth * dataratio : objheight; objheight = Math.min(Math.round(objheight), screenH); objwidth = objwidth > screenW ? objheight * aspectratio : objwidth; objwidth = Math.min(Math.round(objwidth), screenW); vmargin = Math.max(Math.round((screenH + vmargin - objheight) / 2), 0); hmargin = Math.max(Math.round((screenW + hmargin - objwidth) / 2), 0); } $("object", root).css({ width: objwidth, height: objheight, marginTop: vmargin, marginLeft: hmargin }); } }); return engine; }; var VIDEO = $('<video/>')[0]; // HTML5 --> Flowplayer event var EVENTS = { // fired ended: 'finish', pause: 'pause', play: 'resume', progress: 'buffer', timeupdate: 'progress', volumechange: 'volume', ratechange: 'speed', //seeking: 'beforeseek', seeked: 'seek', // abort: 'resume', // not fired loadeddata: 'ready', // loadedmetadata: 0, // canplay: 0, // error events // load: 0, // emptied: 0, // empty: 0, error: 'error', dataunavailable: 'error' }; function round(val, per) { per = per || 100; return Math.round(val * per) / per; } function getType(type) { return /mpegurl/i.test(type) ? "application/x-mpegurl" : "video/" + type; } function canPlay(type) { if (!/^(video|application)/.test(type)) type = getType(type); return !!VIDEO.canPlayType(type).replace("no", ''); } function findFromSourcesByType(sources, type) { var arr = $.grep(sources, function(s) { return s.type === type; }); return arr.length ? arr[0] : null; } var videoTagCache; var createVideoTag = function(video) { if (videoTagCache) { return videoTagCache.attr({type: getType(video.type), src: video.src}); } return (videoTagCache = $("<video/>", { src: video.src, type: getType(video.type), 'class': 'fp-engine', 'autoplay': 'autoplay', preload: 'none', 'x-webkit-airplay': 'allow' })); } flowplayer.engine.html5 = function(player, root) { var videoTag = $("video", root), support = flowplayer.support, track = $("track", videoTag), conf = player.conf, self, timer, api; return self = { pick: function(sources) { if (support.video) { if (conf.videoTypePreference) { var mp4source = findFromSourcesByType(sources, conf.videoTypePreference); if (mp4source) return mp4source; } for (var i = 0, source; i < sources.length; i++) { if (canPlay(sources[i].type)) return sources[i]; } } }, load: function(video) { if (conf.splash && !api) { videoTag = createVideoTag(video).prependTo(root); if (!support.inlineVideo) { videoTag.css({ position: 'absolute', top: '-9999em' }); } if (track.length) videoTag.append(track.attr("default", "")); if (conf.loop) videoTag.attr("loop", "loop"); api = videoTag[0]; } else { api = videoTag[0]; var sources = videoTag.find('source'); if (!api.src && sources.length) { api.src = video.src; sources.remove(); } // change of clip if (player.video.src && video.src != player.video.src) { videoTag.attr("autoplay", "autoplay"); api.src = video.src; // preload=none or no initial "loadeddata" event } else if (conf.preload == 'none' || !support.dataload) { if (support.zeropreload) { player.trigger("ready", video).trigger("pause").one("ready", function() { root.trigger("resume", [player]); }); } else { player.one("ready", function() { root.trigger("pause", [player]); }); } } } listen(api, $("source", videoTag).add(videoTag), video); // iPad (+others?) demands load() if (conf.preload != 'none' || !support.zeropreload || !support.dataload) api.load(); if (conf.splash) api.load(); }, pause: function() { api.pause(); }, resume: function() { api.play(); }, speed: function(val) { api.playbackRate = val; }, seek: function(time) { try { var pausedState = player.paused; api.currentTime = time; if (pausedState) api.pause(); } catch (ignored) {} }, volume: function(level) { api.volume = level; }, unload: function() { $("video.fp-engine", root).remove(); if (!support.cachedVideoTag) videoTagCache = null; timer = clearInterval(timer); api = 0; } }; function listen(api, sources, video) { // listen only once if (api.listeners && api.listeners.hasOwnProperty(root.data('fp-player_id'))) return; (api.listeners || (api.listeners = {}))[root.data('fp-player_id')] = true; sources.bind("error", function(e) { try { if (e.originalEvent && $(e.originalEvent.originalTarget).is('img')) return e.preventDefault(); if (canPlay($(e.target).attr("type"))) { player.trigger("error", { code: 4 }); } } catch (er) { // Most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427 } }); $.each(EVENTS, function(type, flow) { api.addEventListener(type, function(e) { // safari hack for bad URL (10s before fails) if (flow == "progress" && e.srcElement && e.srcElement.readyState === 0) { setTimeout(function() { if (!player.video.duration) { flow = "error"; player.trigger(flow, { code: 4 }); } }, 10000); } if (conf.debug && !/progress/.test(flow)) console.log(type, "->", flow, e); // no events if player not ready if (!player.ready && !/ready|error/.test(flow) || !flow || !$("video", root).length) { return; } var event = $.Event(flow), arg; switch (flow) { case "ready": arg = $.extend(video, { duration: api.duration, width: api.videoWidth, height: api.videoHeight, url: api.currentSrc, src: api.currentSrc }); try { arg.seekable = api.seekable && api.seekable.end(null); } catch (ignored) {} // buffer timer = timer || setInterval(function() { try { arg.buffer = api.buffered.end(null); } catch (ignored) {} if (arg.buffer) { if (round(arg.buffer, 1000) < round(arg.duration, 1000) && !arg.buffered) { player.trigger("buffer", e); } else if (!arg.buffered) { arg.buffered = true; player.trigger("buffer", e).trigger("buffered", e); clearInterval(timer); timer = 0; } } }, 250); if (!conf.live && !arg.duration && !support.hlsDuration && type === "loadeddata") { var durationChanged = function() { arg.duration = api.duration; try { arg.seekable = api.seekable && api.seekable.end(null); } catch (ignored) {} player.trigger(event, arg); api.removeEventListener('durationchange', durationChanged); }; api.addEventListener('durationchange', durationChanged); return; } break; case "progress": case "seek": var dur = player.video.duration if (api.currentTime > 0) { arg = Math.max(api.currentTime, 0); break; } else if (flow == 'progress') { return; } case "speed": arg = round(api.playbackRate); break; case "volume": arg = round(api.volume); break; case "error": try { arg = (e.srcElement || e.originalTarget).error; } catch (er) { // Most likely https://bugzilla.mozilla.org/show_bug.cgi?id=208427 return; } } player.trigger(event, arg); }, false); }); } }; var TYPE_RE = /\.(\w{3,4})(\?.*)?$/i; function parseSource(el) { var src = el.attr("src"), type = el.attr("type") || "", suffix = src.split(TYPE_RE)[1]; type = /mpegurl/.test(type) ? "mpegurl" : type.replace("video/", ""); return { src: src, suffix: suffix || type, type: type || suffix }; } /* Resolves video object from initial configuration and from load() method */ function URLResolver(videoTag) { var self = this, sources = []; // initial sources $("source", videoTag).each(function() { sources.push(parseSource($(this))); }); if (!sources.length) sources.push(parseSource(videoTag)); self.initialSources = sources; self.resolve = function(video) { if (!video) return { sources: sources }; if ($.isArray(video)) { video = { sources: $.map(video, function(el) { var type, ret = $.extend({}, el); $.each(el, function(key, value) { type = key; }); ret.type = type; ret.src = el[type]; delete ret[type]; return ret; })}; } else if (typeof video == 'string') { video = { src: video, sources: [] }; $.each(sources, function(i, source) { if (source.type != 'flash') { video.sources.push({ type: source.type, src: video.src.replace(TYPE_RE, "." + source.suffix + "$2") }); } }); } return video; }; }; /* A minimal jQuery Slider plugin with all goodies */ // skip IE policies // document.ondragstart = function () { return false; }; // execute function every <delay> ms $.throttle = function(fn, delay) { var locked; return function () { if (!locked) { fn.apply(this, arguments); locked = 1; setTimeout(function () { locked = 0; }, delay); } }; }; $.fn.slider2 = function(rtl) { var IS_IPAD = /iPad/.test(navigator.userAgent) && !/CriOS/.test(navigator.userAgent); return this.each(function() { var root = $(this), doc = $(document), progress = root.children(":last"), disabled, offset, width, height, vertical, size, maxValue, max, skipAnimation = false, /* private */ calc = function() { offset = root.offset(); width = root.width(); height = root.height(); /* exit from fullscreen can mess this up.*/ // vertical = height > width; size = vertical ? height : width; max = toDelta(maxValue); }, fire = function(value) { if (!disabled && value != api.value && (!maxValue || value < maxValue)) { root.trigger("slide", [ value ]); api.value = value; } }, mousemove = function(e) { var pageX = e.pageX; if (!pageX && e.originalEvent && e.originalEvent.touches && e.originalEvent.touches.length) { pageX = e.originalEvent.touches[0].pageX; } var delta = vertical ? e.pageY - offset.top : pageX - offset.left; delta = Math.max(0, Math.min(max || size, delta)); var value = delta / size; if (vertical) value = 1 - value; if (rtl) value = 1 - value; return move(value, 0, true); }, move = function(value, speed) { if (speed === undefined) { speed = 0; } if (value > 1) value = 1; var to = (Math.round(value * 1000) / 10) + "%"; if (!maxValue || value <= maxValue) { if (!IS_IPAD) progress.stop(); // stop() broken on iPad if (skipAnimation) { progress.css('width', to); } else { progress.animate(vertical ? { height: to } : { width: to }, speed, "linear"); } } return value; }, toDelta = function(value) { return Math.max(0, Math.min(size, vertical ? (1 - value) * height : value * width)); }, /* public */ api = { max: function(value) { maxValue = value; }, disable: function(flag) { disabled = flag; }, slide: function(value, speed, fireEvent) { calc(); if (fireEvent) fire(value); move(value, speed); }, // Should animation be handled via css disableAnimation: function(value) { skipAnimation = value !== false; } }; calc(); // bound dragging into document root.data("api", api).bind("mousedown.sld touchstart", function(e) { e.preventDefault(); if (!disabled) { // begin --> recalculate. allows dynamic resizing of the slider var delayedFire = $.throttle(fire, 100); calc(); api.dragging = true; root.addClass('is-dragging'); fire(mousemove(e)); doc.bind("mousemove.sld touchmove", function(e) { e.preventDefault(); delayedFire(mousemove(e)); }).one("mouseup touchend", function() { api.dragging = false; root.removeClass('is-dragging'); doc.unbind("mousemove.sld touchmove"); }); } }); }); }; function zeropad(val) { val = parseInt(val, 10); return val >= 10 ? val : "0" + val; } // display seconds in hh:mm:ss format function format(sec) { sec = sec || 0; var h = Math.floor(sec / 3600), min = Math.floor(sec / 60); sec = sec - (min * 60); if (h >= 1) { min -= h * 60; return h + ":" + zeropad(min) + ":" + zeropad(sec); } return zeropad(min) + ":" + zeropad(sec); } flowplayer(function(api, root) { var conf = api.conf, support = flowplayer.support, hovertimer; root.find('.fp-ratio,.fp-ui').remove(); root.addClass("flowplayer").append('\ <div class="ratio"/>\ <div class="ui">\ <div class="waiting"><em/><em/><em/></div>\ <a class="fullscreen"/>\ <a class="unload"/>\ <p class="speed"/>\ <div class="controls">\ <a class="play"></a>\ <div class="timeline">\ <div class="buffer"/>\ <div class="progress"/>\ </div>\ <div class="volume">\ <a class="mute"></a>\ <div class="volumeslider">\ <div class="volumelevel"/>\ </div>\ </div>\ </div>\ <div class="time">\ <em class="elapsed">00:00</em>\ <em class="remaining"/>\ <em class="duration">00:00</em>\ </div>\ <div class="message"><h2/><p/></div>\ </div>'.replace(/class="/g, 'class="fp-') ); function find(klass) { return $(".fp-" + klass, root); } // widgets var progress = find("progress"), buffer = find("buffer"), elapsed = find("elapsed"), remaining = find("remaining"), waiting = find("waiting"), ratio = find("ratio"), speed = find("speed"), durationEl = find("duration"), origRatio = ratio.css("paddingTop"), // sliders timeline = find("timeline").slider2(api.rtl), timelineApi = timeline.data("api"), volume = find("volume"), fullscreen = find("fullscreen"), volumeSlider = find("volumeslider").slider2(api.rtl), volumeApi = volumeSlider.data("api"), noToggle = root.is(".fixed-controls, .no-toggle"); timelineApi.disableAnimation(root.hasClass('is-touch')); // aspect ratio function setRatio(val) { if ((root.css('width') === '0px' || root.css('height') === '0px') || val !== flowplayer.defaults.ratio) { if (!parseInt(origRatio, 10)) ratio.css("paddingTop", val * 100 + "%"); } if (!support.inlineBlock) $("object", root).height(root.height()); } function hover(flag) { root.toggleClass("is-mouseover", flag).toggleClass("is-mouseout", !flag); } // loading... if (!support.animation) waiting.html("<p>loading …</p>"); setRatio(conf.ratio); // no fullscreen in IFRAME try { if (!conf.fullscreen) fullscreen.remove(); } catch (e) { fullscreen.remove(); } api.bind("ready", function() { var duration = api.video.duration; timelineApi.disable(api.disabled || !duration); conf.adaptiveRatio && setRatio(api.video.height / api.video.width); // initial time & volume durationEl.add(remaining).html(format(duration)); // do we need additional space for showing hour ((duration >= 3600) && root.addClass('is-long')) || root.removeClass('is-long'); volumeApi.slide(api.volumeLevel); }).bind("unload", function() { if (!origRatio) ratio.css("paddingTop", ""); // buffer }).bind("buffer", function() { var video = api.video, max = video.buffer / video.duration; if (!video.seekable && support.seekable) timelineApi.max(max); if (max < 1) buffer.css("width", (max * 100) + "%"); else buffer.css({ width: '100%' }); }).bind("speed", function(e, api, val) { speed.text(val + "x").addClass("fp-hilite"); setTimeout(function() { speed.removeClass("fp-hilite") }, 1000); }).bind("buffered", function() { buffer.css({ width: '100%' }); timelineApi.max(1); // progress }).bind("progress", function() { var time = api.video.time, duration = api.video.duration; if (!timelineApi.dragging) { timelineApi.slide(time / duration, api.seeking ? 0 : 250); } elapsed.html(format(time)); remaining.html("-" + format(duration - time)); }).bind("finish resume seek", function(e) { root.toggleClass("is-finished", e.type == "finish"); }).bind("stop", function() { elapsed.html(format(0)); timelineApi.slide(0, 100); }).bind("finish", function() { elapsed.html(format(api.video.duration)); timelineApi.slide(1, 100); root.removeClass("is-seeking"); // misc }).bind("beforeseek", function() { progress.stop(); }).bind("volume", function() { volumeApi.slide(api.volumeLevel); }).bind("disable", function() { var flag = api.disabled; timelineApi.disable(flag); volumeApi.disable(flag); root.toggleClass("is-disabled", api.disabled); }).bind("mute", function(e, api, flag) { root.toggleClass("is-muted", flag); }).bind("error", function(e, api, error) { root.removeClass("is-loading").addClass("is-error"); if (error) { error.message = conf.errors[error.code]; api.error = true; var el = $(".fp-message", root); $("h2", el).text((api.engine || 'html5') + ": " + error.message); $("p", el).text(error.url || api.video.url || api.video.src || conf.errorUrls[error.code]); root.unbind("mouseenter click").removeClass("is-mouseover"); } // hover }).bind("mouseenter mouseleave", function(e) { if (noToggle) return; var is_over = e.type == "mouseenter", lastMove; // is-mouseover/out hover(is_over); if (is_over) { root.bind("pause.x mousemove.x volume.x", function() { hover(true); lastMove = new Date; }); hovertimer = setInterval(function() { if (new Date - lastMove > 5000) { hover(false) lastMove = new Date; } }, 100); } else { root.unbind(".x"); clearInterval(hovertimer); } // allow dragging over the player edge }).bind("mouseleave", function() { if (timelineApi.dragging || volumeApi.dragging) { root.addClass("is-mouseover").removeClass("is-mouseout"); } // click }).bind("click.player", function(e) { if ($(e.target).is(".fp-ui, .fp-engine") || e.flash) { e.preventDefault(); return api.toggle(); } }).bind('contextmenu', function(ev) { ev.preventDefault(); var o = root.offset(), w = $(window), left = ev.clientX - o.left, t = ev.clientY - o.top + w.scrollTop(); var menu = root.find('.fp-context-menu').css({ left: left + 'px', top: t + 'px', display: 'block' }).on('click', function(ev) { ev.stopPropagation(); }); $('html').on('click.outsidemenu', function(ev) { menu.hide(); $('html').off('click.outsidemenu'); }); }).bind('flashdisabled', function() { root.addClass('is-flash-disabled').one('ready', function() { root.removeClass('is-flash-disabled').find('.fp-flash-disabled').remove(); }).append('<div class="fp-flash-disabled">Adobe Flash is disabled for this page, click player area to enable.</div>'); }); // poster -> background image if (conf.poster) root.css("backgroundImage", "url(" + conf.poster + ")"); var bc = root.css("backgroundColor"), has_bg = root.css("backgroundImage") != "none" || bc && bc != "rgba(0, 0, 0, 0)" && bc != "transparent"; // is-poster class if (has_bg && !conf.splash && !conf.autoplay) { api.bind("ready stop", function() { root.addClass("is-poster").one("progress", function() { root.removeClass("is-poster"); }); }); } // default background color if not present if (!has_bg && api.forcedSplash) { root.css("backgroundColor", "#555"); } $(".fp-toggle, .fp-play", root).click(api.toggle); /* controlbar elements */ $.each(['mute', 'fullscreen', 'unload'], function(i, key) { find(key).click(function() { api[key](); }); }); timeline.bind("slide", function(e, val) { api.seeking = true; api.seek(val * api.video.duration); }); volumeSlider.bind("slide", function(e, val) { api.volume(val); }); // times find("time").click(function(e) { $(this).toggleClass("is-inverted"); }); hover(noToggle); }); var focused, focusedRoot, IS_HELP = "is-help"; // keyboard. single global listener $(document).bind("keydown.fp", function(e) { var el = focused, metaKeyPressed = e.ctrlKey || e.metaKey || e.altKey, key = e.which, conf = el && el.conf; if (!el || !conf.keyboard || el.disabled) return; // help dialog (shift key not truly required) if ($.inArray(key, [63, 187, 191]) != -1) { focusedRoot.toggleClass(IS_HELP); return false; } // close help / unload if (key == 27 && focusedRoot.hasClass(IS_HELP)) { focusedRoot.toggleClass(IS_HELP); return false; } if (!metaKeyPressed && el.ready) { e.preventDefault(); // slow motion / fast forward if (e.shiftKey) { if (key == 39) el.speed(true); else if (key == 37) el.speed(false); return; } // 1, 2, 3, 4 .. if (key < 58 && key > 47) return el.seekTo(key - 48); switch (key) { case 38: case 75: el.volume(el.volumeLevel + 0.15); break; // volume up case 40: case 74: el.volume(el.volumeLevel - 0.15); break; // volume down case 39: case 76: el.seeking = true; el.seek(true); break; // forward case 37: case 72: el.seeking = true; el.seek(false); break; // backward case 190: el.seekTo(); break; // to last seek position case 32: el.toggle(); break; // spacebar case 70: conf.fullscreen && el.fullscreen(); break; // toggle fullscreen case 77: el.mute(); break; // mute case 81: el.unload(); break; // unload/stop } } }); flowplayer(function(api, root) { // no keyboard configured if (!api.conf.keyboard) return; // hover root.bind("mouseenter mouseleave", function(e) { focused = !api.disabled && e.type == 'mouseenter' ? api : 0; if (focused) focusedRoot = root; }); // TODO: add to player-layout.html root.append('\ <div class="fp-help">\ <a class="fp-close"></a>\ <div class="fp-help-section fp-help-basics">\ <p><em>space</em>play / pause</p>\ <p><em>q</em>unload | stop</p>\ <p><em>f</em>fullscreen</p>\ <p><em>shift</em> + <em>←</em><em>→</em>slower / faster <small>(latest Chrome and Safari)</small></p>\ </div>\ <div class="fp-help-section">\ <p><em>↑</em><em>↓</em>volume</p>\ <p><em>m</em>mute</p>\ </div>\ <div class="fp-help-section">\ <p><em>←</em><em>→</em>seek</p>\ <p><em> . </em>seek to previous\ </p><p><em>1</em><em>2</em>…<em>6</em> seek to 10%, 20%, …60% </p>\ </div>\ </div>\ '); if (api.conf.tooltip) { $(".fp-ui", root).attr("title", "Hit ? for help").on("mouseout.tip", function() { $(this).removeAttr("title").off("mouseout.tip"); }); } $(".fp-close", root).click(function() { root.toggleClass(IS_HELP); }); }); var VENDOR = $.browser.mozilla ? "moz": "webkit", FS_ENTER = "fullscreen", FS_EXIT = "fullscreen-exit", FULL_PLAYER, FS_SUPPORT = flowplayer.support.fullscreen, FS_NATIVE_SUPPORT = typeof document.exitFullscreen == 'function', ua = navigator.userAgent.toLowerCase(), IS_SAFARI = /(safari)[ \/]([\w.]+)/.exec(ua) && !/(chrome)[ \/]([\w.]+)/.exec(ua); // esc button $(document).bind(FS_NATIVE_SUPPORT ? "fullscreenchange" : VENDOR + "fullscreenchange", function(e) { var el = $(document.webkitCurrentFullScreenElement || document.mozFullScreenElement || document.fullscreenElement || e.target); if (el.length && !FULL_PLAYER) { FULL_PLAYER = el.trigger(FS_ENTER, [el]); } else { FULL_PLAYER.trigger(FS_EXIT, [FULL_PLAYER]); FULL_PLAYER = null; } }); flowplayer(function(player, root) { if (!player.conf.fullscreen) return; var win = $(window), fsResume = {index: 0, pos: 0, play: false}, scrollTop; player.isFullscreen = false; player.fullscreen = function(flag) { if (player.disabled) return; if (flag === undefined) flag = !player.isFullscreen; if (flag) scrollTop = win.scrollTop(); if ((VENDOR == "webkit" || IS_SAFARI) && player.engine == "flash") { // play current index on fullscreen toggle fsResume.index = player.video.index; if (player.conf.rtmp) // avoid restart $.extend(fsResume, {pos: player.video.time, play: player.playing}); } if (FS_SUPPORT) { if (flag) { if (FS_NATIVE_SUPPORT) { root[0].requestFullscreen(); } else { root[0][VENDOR + 'RequestFullScreen'](Element.ALLOW_KEYBOARD_INPUT); if (IS_SAFARI && !document.webkitCurrentFullScreenElement && !document.mozFullScreenElement) { // Element.ALLOW_KEYBOARD_INPUT not allowed root[0][VENDOR + 'RequestFullScreen'](); } } } else { if (FS_NATIVE_SUPPORT) { document.exitFullscreen(); } else { document[VENDOR + 'CancelFullScreen'](); } } } else { player.trigger(flag ? FS_ENTER : FS_EXIT, [player]); } return player; }; var lastClick; root.bind("mousedown.fs", function() { if (+new Date - lastClick < 150 && player.ready) player.fullscreen(); lastClick = +new Date; }); player.bind(FS_ENTER, function(e) { root.addClass("is-fullscreen"); player.isFullscreen = true; }).bind(FS_EXIT, function(e) { var oldOpacity; if (!FS_SUPPORT && player.engine === "html5") { oldOpacity = root.css('opacity') || ''; root.css('opacity', 0); } root.removeClass("is-fullscreen"); if (!FS_SUPPORT && player.engine === "html5") setTimeout(function() { root.css('opacity', oldOpacity); }); player.isFullscreen = false; win.scrollTop(scrollTop); }).bind("ready", function () { if (fsResume.index > 0) { player.play(fsResume.index); // above loads "different" clip, resume position below fsResume.index = 0; } else if (fsResume.pos && !isNaN(fsResume.pos)) { var fsreset = function () { if (!fsResume.play) player.pause(); $.extend(fsResume, {pos: 0, play: false}); }; if (player.conf.live) { player.resume(); fsreset(); } else { player.resume().seek(fsResume.pos, fsreset); } } }); }); flowplayer(function(player, root) { var conf = $.extend({ active: 'is-active', advance: true, query: ".fp-playlist a" }, player.conf), klass = conf.active; // getters function els() { return $(conf.query, root); } function active() { return $(conf.query + "." + klass, root); } player.play = function(i) { if (i === undefined) return player.resume(); if (typeof i === 'number' && !player.conf.playlist[i]) return player; else if (typeof i != 'number') player.load.apply(null, arguments); player.unbind('resume.fromfirst'); // Don't start from beginning if clip explicitely chosen player.video.index = i; player.load(typeof player.conf.playlist[i] === 'string' ? player.conf.playlist[i].toString() : $.map(player.conf.playlist[i], function(item) { return $.extend({}, item); }) ); return player; }; player.next = function(e) { e && e.preventDefault(); var current = player.video.index; if (current != -1) { current = current === player.conf.playlist.length - 1 ? 0 : current + 1; player.play(current); } return player; }; player.prev = function(e) { e && e.preventDefault(); var current = player.video.index; if (current != -1) { current = current === 0 ? player.conf.playlist.length - 1 : current - 1; player.play(current); } return player; }; $('.fp-next', root).click(player.next); $('.fp-prev', root).click(player.prev); if (conf.advance) { root.unbind("finish.pl").bind("finish.pl", function(e, player) { // next clip is found or loop var next = player.video.index + 1; if (next < player.conf.playlist.length || conf.loop) { next = next === player.conf.playlist.length ? 0 : next; root.removeClass('is-finished'); setTimeout(function() { // Let other finish callbacks fire first player.play(next); }); // stop to last clip, play button starts from 1:st clip } else { root.addClass("is-playing"); // show play button // If we have multiple items in playlist, start from first if (player.conf.playlist.length > 1) player.one("resume.fromfirst", function() { player.play(0); return false; }); } }); } var playlistInitialized = false; if (player.conf.playlist.length) { // playlist configured by javascript, generate playlist playlistInitialized = true; var plEl = root.find('.fp-playlist'); if (!plEl.length) { plEl = $('<div class="fp-playlist"></div>'); var cntrls = $('.fp-next,.fp-prev', root); if (!cntrls.length) $('video', root).after(plEl); else cntrls.eq(0).before(plEl); } plEl.empty(); $.each(player.conf.playlist, function(i, item) { var href; if (typeof item === 'string') { href = item; } else { for (var key in item[0]) { if (item[0].hasOwnProperty(key)) { href = item[0][key]; break; } } } plEl.append($('<a />').attr({ href: href, 'data-index': i })); }); } if (els().length) { if (!playlistInitialized) { player.conf.playlist = []; els().each(function() { var src = $(this).attr('href'); $(this).attr('data-index', player.conf.playlist.length); player.conf.playlist.push(src); }); } /* click -> play */ root.on("click", conf.query, function(e) { e.preventDefault(); var el = $(e.target).closest(conf.query); var toPlay = Number(el.attr('data-index')); if (toPlay != -1) { player.play(toPlay); } }); // playlist wide cuepoint support var has_cuepoints = els().filter("[data-cuepoints]").length; // highlight player.bind("load", function(e, api, video) { var prev = active().removeClass(klass), prevIndex = prev.attr('data-index'), index = video.index = player.video.index || 0, el = $('a[data-index="' + index + '"]', root).addClass(klass), is_last = index == player.conf.playlist.length - 1; // index root.removeClass("video" + prevIndex).addClass("video" + index).toggleClass("last-video", is_last); // video properties video.index = api.video.index = index; video.is_last = api.video.is_last = is_last; // cuepoints if (has_cuepoints) player.cuepoints = el.data("cuepoints"); // without namespace callback called only once. unknown rason. }).bind("unload.pl", function() { active().toggleClass(klass); }); } if (player.conf.playlist.length) { // disable single clip looping player.conf.loop = false; } }); var CUE_RE = / ?cue\d+ ?/; flowplayer(function(player, root) { var lastTime = 0; player.cuepoints = player.conf.cuepoints || []; function setClass(index) { root[0].className = root[0].className.replace(CUE_RE, " "); if (index >= 0) root.addClass("cue" + index); } player.bind("progress", function(e, api, time) { // avoid throwing multiple times if (lastTime && time - lastTime < 0.015) return lastTime = time; lastTime = time; var cues = player.cuepoints || []; for (var i = 0, cue; i < cues.length; i++) { cue = cues[i]; if (!isNaN(cue)) cue = { time: cue }; if (cue.time < 0) cue.time = player.video.duration + cue.time; cue.index = i; // progress_interval / 2 = 0.125 if (Math.abs(cue.time - time) < 0.125 * player.currentSpeed) { setClass(i); root.trigger("cuepoint", [player, cue]); } } // no CSS class name }).bind("unload seek", setClass); if (player.conf.generate_cuepoints) { player.bind("load", function() { // clean up cuepoint elements of previous playlist items $(".fp-cuepoint", root).remove(); }).bind("ready", function() { var cues = player.cuepoints || [], duration = player.video.duration, timeline = $(".fp-timeline", root).css("overflow", "visible"); $.each(cues, function(i, cue) { var time = cue.time || cue; if (time < 0) time = duration + cue; var el = $("<a/>").addClass("fp-cuepoint fp-cuepoint" + i) .css("left", (time / duration * 100) + "%"); el.appendTo(timeline).mousedown(function() { player.seek(time); // preventDefault() doesn't work return false; }); }); }); } }); flowplayer(function(player, root, engine) { var track = $("track", root), conf = player.conf; if (flowplayer.support.subtitles) { player.subtitles = track.length && track[0].track; // use native when supported if (conf.nativesubtitles && conf.engine == 'html5') return; } // avoid duplicate loads track.remove(); var TIMECODE_RE = /^(([0-9]{2}:)?[0-9]{2}:[0-9]{2}[,.]{1}[0-9]{3}) --\> (([0-9]{2}:)?[0-9]{2}:[0-9]{2}[,.]{1}[0-9]{3})(.*)/; function seconds(timecode) { var els = timecode.split(':'); if (els.length == 2) els.unshift(0); return els[0] * 60 * 60 + els[1] * 60 + parseFloat(els[2].replace(',','.')); } player.subtitles = []; var url = track.attr("src"); if (!url) return; setTimeout(function() { $.get(url, function(txt) { for (var i = 0, lines = txt.split("\n"), len = lines.length, entry = {}, title, timecode, text, cue; i < len; i++) { timecode = TIMECODE_RE.exec(lines[i]); if (timecode) { // title title = lines[i - 1]; // text text = "<p>" + lines[++i] + "</p><br/>"; while ($.trim(lines[++i]) && i < lines.length) text += "<p>" + lines[i] + "</p><br/>"; // entry entry = { title: title, startTime: seconds(timecode[1]), endTime: seconds(timecode[2] || timecode[3]), text: text }; cue = { time: entry.startTime, subtitle: entry }; player.subtitles.push(entry); player.cuepoints.push(cue); player.cuepoints.push({ time: entry.endTime, subtitleEnd: title }); // initial cuepoint if (entry.startTime === 0) { player.trigger("cuepoint", cue); } } } }).fail(function() { player.trigger("error", {code: 8, url: url }); return false; }); }); var wrap = $("<div class='fp-subtitle'/>").appendTo(root), currentPoint; player.bind("cuepoint", function(e, api, cue) { if (cue.subtitle) { currentPoint = cue.index; wrap.html(cue.subtitle.text).addClass("fp-active"); } else if (cue.subtitleEnd) { wrap.removeClass("fp-active"); currentPoint = cue.index; } }).bind("seek", function(e, api, time) { // Clear future subtitles if seeking backwards if (currentPoint && player.cuepoints[currentPoint] && player.cuepoints[currentPoint].time > time) { wrap.removeClass('fp-active'); currentPoint = null; } $.each(player.cuepoints || [], function(i, cue) { var entry = cue.subtitle; //Trigger cuepoint if start time before seek position and end time nonexistent or in the future if (entry && currentPoint != cue.index) { if (time >= cue.time && (!entry.endTime || time <= entry.endTime)) player.trigger("cuepoint", cue); } // Also handle cuepoints that act as the removal trigger else if (cue.subtitleEnd && time >= cue.time && cue.index == currentPoint + 1) player.trigger("cuepoint", cue); }); }); }); flowplayer(function(player, root) { var id = player.conf.analytics, time = 0, last = 0; if (id) { // load Analytics script if needed if (typeof _gat == 'undefined') $.getScript("//google-analytics.com/ga.js"); function track(e) { if (time && typeof _gat != 'undefined') { var tracker = _gat._getTracker(id), video = player.video; tracker._setAllowLinker(true); // http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html tracker._trackEvent( "Video / Seconds played", player.engine + "/" + video.type, root.attr("title") || video.src.split("/").slice(-1)[0].replace(TYPE_RE, ''), Math.round(time / 1000) ); time = 0; } } player.bind("load unload", track).bind("progress", function() { if (!player.seeking) { time += last ? (+new Date - last) : 0; last = +new Date; } }).bind("pause", function() { last = 0; }); $(window).unload(track); } });var isIeMobile = /IEMobile/.test(UA); if (flowplayer.support.touch || isIeMobile) { flowplayer(function(player, root) { var isAndroid = /Android/.test(UA) && !/Firefox/.test(UA) && !/Opera/.test(UA), isSilk = /Silk/.test(UA), androidVer = isAndroid ? parseFloat(/Android\ (\d\.\d)/.exec(UA)[1], 10) : 0; // custom load for android if (isAndroid) { player.conf.videoTypePreference = "mp4"; // Android has problems with webm aspect ratio if (!/Chrome/.test(UA) && androidVer < 4) { var originalLoad = player.load; player.load = function(video, callback) { var ret = originalLoad.apply(player, arguments); player.trigger('ready', [player, player.video]); return ret; }; } } // hide volume if (!flowplayer.support.volume) { root.addClass("no-volume no-mute"); } root.addClass("is-touch"); root.find('.fp-timeline').data('api').disableAnimation(); // fake mouseover effect with click var hasMoved = false; root.bind('touchmove', function() { hasMoved = true; }).bind("touchend click", function(e) { if (hasMoved) { //not intentional, most likely scrolling hasMoved = false; return; } if (player.playing && !root.hasClass("is-mouseover")) { root.addClass("is-mouseover").removeClass("is-mouseout"); return false; } if (player.paused && root.hasClass("is-mouseout") && !player.splash) { player.toggle(); } if (player.paused && isIeMobile) { // IE on WP7 need an additional api.play() call $('video.fp-engine', root)[0].play(); } }); // native fullscreen if (player.conf.native_fullscreen && typeof $('<video />')[0].webkitEnterFullScreen === 'function') { player.fullscreen = function() { var video = $('video.fp-engine', root); video[0].webkitEnterFullScreen(); video.one('webkitendfullscreen', function() { video.prop('controls', true).prop('controls', false); }); }; } // Android browser gives video.duration == 1 until second 'timeupdate' event (isAndroid || isSilk) && player.bind("ready", function() { var video = $('video.fp-engine', root); video.one('canplay', function() { video[0].play(); }); video[0].play(); player.bind("progress.dur", function() { var duration = video[0].duration; if (duration !== 1) { player.video.duration = duration; $(".fp-duration", root).html(format(duration)); player.unbind("progress.dur"); } }); }); }); } flowplayer(function(player, root) { // no embedding if (player.conf.embed === false) return; var conf = player.conf, ui = $(".fp-ui", root), trigger = $("<a/>", { "class": "fp-embed", title: 'Copy to your site'}).appendTo(ui), target = $("<div/>", { 'class': 'fp-embed-code'}) .append("<label>Paste this HTML code on your site to embed.</label><textarea/>").appendTo(ui), area = $("textarea", target); player.embedCode = function() { var video = player.video, width = video.width || root.width(), height = video.height || root.height(), el = $("<div/>", { 'class': 'flowplayer', css: { width: width, height: height }}), tag = $("<video/>").appendTo(el); // configuration $.each(['origin', 'analytics', 'key', 'rtmp'], function(i, key) { if (conf[key]) el.attr("data-" + key, conf[key]); }); //logo if (conf.logo) { el.attr('data-logo', $('<img />').attr('src', conf.logo)[0].src); } // sources $.each(video.sources, function(i, src) { var path = src.src; if (!/^https?:/.test(src.src) && src.type !== 'flash' || !conf.rtmp) { path = $("<img/>").attr("src", src.src)[0].src; } tag.append($("<source/>", { type: "video/" + src.type, src: path })); }); var scriptAttrs = { src: "//embed.flowplayer.org/5.4.6/embed.min.js" }; if ($.isPlainObject(conf.embed)) { scriptAttrs['data-swf'] = conf.embed.swf; scriptAttrs['data-library'] = conf.embed.library; scriptAttrs['src'] = conf.embed.script || scriptAttrs['src']; if (conf.embed.skin) { scriptAttrs['data-skin'] = conf.embed.skin; } } var code = $("<foo/>", scriptAttrs).append(el); return $("<p/>").append(code).html().replace(/<(\/?)foo/g, "<$1script"); }; root.fptip(".fp-embed", "is-embedding"); area.click(function() { this.select(); }); trigger.click(function() { area.text(player.embedCode()); area[0].focus(); area[0].select(); }); }); $.fn.fptip = function(trigger, active) { return this.each(function() { var root = $(this); function close() { root.removeClass(active); $(document).unbind(".st"); } $(trigger || "a", this).click(function(e) { e.preventDefault(); root.toggleClass(active); if (root.hasClass(active)) { $(document).bind("keydown.st", function(e) { if (e.which == 27) close(); // click:close }).bind("click.st", function(e) { if (!$(e.target).parents("." + active).length) close(); }); } }); }); }; }(jQuery); flowplayer(function(e,o){function l(e){var o=a("<a/>")[0];return o.href=e,o.hostname}var a=jQuery,r=e.conf,i=r.swf.indexOf("flowplayer.org")&&r.e&&o.data("origin"),n=i?l(i):location.hostname,t=r.key;if("file:"==location.protocol&&(n="localhost"),e.load.ed=1,r.hostname=n,r.origin=i||location.href,i&&o.addClass("is-embedded"),"string"==typeof t&&(t=t.split(/,\s*/)),t&&"function"==typeof key_check&&key_check(t,n))r.logo&&o.append(a("<a>",{"class":"fp-logo",href:i}).append(a("<img/>",{src:r.logo})));else{var s=a("<a/>").attr("href","http://flowplayer.org").appendTo(o);a(".fp-controls",o);var p=a('<div class="fp-context-menu"><ul><li class="copyright">© 2013</li><li><a href="http://flowplayer.org">About Flowplayer</a></li><li><a href="http://flowplayer.org/license">GPL based license</a></li></ul></div>').appendTo(o);e.bind("pause resume finish unload",function(e,l){var r=-1;l.video.src&&a.each([["org","flowplayer","drive"],["org","flowplayer","my"]],function(e,o){return r=l.video.src.indexOf("://"+o.reverse().join(".")),-1===r}),/pause|resume/.test(e.type)&&"flash"!=l.engine&&4!=r&&5!=r?(s.show().css({position:"absolute",left:16,bottom:36,zIndex:99999,width:100,height:20,backgroundImage:"url("+[".png","logo","/",".net",".cloudfront","d32wqyuo10o653","//"].reverse().join("")+")"}),l.load.ed=s.is(":visible")&&a.contains(o[0],p[0]),l.load.ed||l.pause()):s.hide()})}}); /* * Edwoard * * * Copyright (c) 2014 Chan9ry.ian * Licensed under the MIT license. */ (function($) { (function() { var cache = {}; this.tmpl = function tmpl(str, data) { // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn(data) : fn; }; })(); var pluginName = 'ScissorHands', playerAPI = null, wrapper = {}, events = [], cuepoints = [], colors = ["#fcfcfc", "#fcfcfc"], //tracker={start:time,end:time,id:id} defaults = { url: '', paramsData: '' }, contorl_panel_template = tmpl( '<div id="content_panel"><div id="panel_cues" class="panel"><div class="rail_cues" id="rail_cues"> </div><div id="play_progress"></div></div><div id="trackers"></div><div id="panels_line" ' + ' style="display:none;"></div></div><div class="track_control_panel" id=control_panel><div class="btn-group' + ' dropup"><button type="button" class="btn btn-default add_track" id=add_track><span class="">??????</span></button><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"><span class="caret"></span><span' + ' class="sr-only"> </span> </button><ul class="dropdown-menu add_track_cuepoints_content" id="add_track_cuepoints_content" ></ul>' + ' <a id=finish_button class="finnish_button btn btn-default" href="#">??????<p>(<span class="output_codeline">??????...</span>)</p></a> </div></div>' ), cuepoints_templeate = tmpl( '<% for(var key in cuepoints){ %>' + '<a class="cue" style="left:<%= cuepoints[key]["position"]%>px; background:<%= cuepoints[key]["color"]%>;" title=" <%= cuepoints[key]["title"] %> | <%= cuepoints[key].seekTime.toString().toHHMMSS() %>" ><p class=""></p></a>' + '<% } %>' ), cuepoints_list_template = tmpl( '<% for(var key in cuepoints){ %>' + '<li><a class="add_track_by_cue" title=" <%= cuepoints[key]["title"] %> | <%= cuepoints[key].seekTime.toString().toHHMMSS() %>" id="cue_<%= key %>" data-cue-start="<%=cuepoints[key]["start"]%>" data-cue-end="<%=cuepoints[key]["end"]%>"><p class=""><%= cuepoints[key]["title"] %></p></a></li>' + '<% } %>' ), track_template = tmpl( '<div id="panel_<%= id %>" class="panel"><div id="rails_<%= id %>" class="rails"></div><div id="tracer_<%= id %>" class="tracer" style="width: <%= clip_width %>px; left: <%= clip_left %>px;" ></div><div id="handler_<%= id %>" class="handler"><a class="right_handler " ></a><a class="left_handler " ></a></div><p class="count_timer"><span class="clip_name"><%= clip_name %>: </span><span class = ""> <a href="#" class="delete_track" data-target="<%= id %>">??? </a></span><span class="left_time"><%= clip_start %></span><span> - </span><span class="right_time"><%= clip_end %></span></p></div>' ); // The actual plugin constructor function Plugin(element, options) { this.element = $(element); wrapper = this.element; this.options = $.extend({}, defaults, options); playerAPI = this.options.playerAPI; // playerAPI.seekTo(time,fn) this.cuepoints = this.options.cuepoints; this._name = pluginName; this.trackers = []; this.init(); this.cuepoints = this.getCuepointsList(); playerAPI.bind('progress', function (e, api, pos) { $('#play_progress').width(pos * $('#panel_cues').width() / api.video.duration); }) } Plugin.prototype.init = function() { // Place initialization logic here // You already have access to the DOM element and // the options via the instance, e.g. this.element // and this.options $(this.element).contents().remove(); $(this.element).append($(contorl_panel_template({}))); //var start_clip = this.addTrack('???'), // end_clip = this.addTrack('???'), var init_one = this.addTrack(), that = this; // control panel intrativities $("#add_track").click(function(e) { e.preventDefault(); var new_one = that.addTrack(); }); $("#finish_button").click(function(e) { e.preventDefault(); var trackers = that.trackers.slice(0), output_string = ''; trackers = reOrder(trackers, "startTime"); output_string += "0B,"; for (var x = 0; x <= trackers.length - 1; x++) { output_string += Math.round(trackers[x].startTime) + "-" + Math.round(trackers[x].endTime) + ","; } output_string += "0A"; $(".output_codeline").html(output_string); $("input[name='Cutout']").val(output_string); }) // playerAPI.on // $(document).on('click','.add_track_by_cue',function(e){ e.preventDefault(); var name = $(e.target).parent().attr('title'); var start = $(e.target).parent().attr('data-cue-start'); var end = $(e.target).parent().attr('data-cue-end'); var new_one = that.addTrack(name, start, end); }); var that = this; $(document).on('click','.delete_track',function(e){ e.preventDefault(); //$(wrapper).contents.remove($($(this).attr('data-target'))); var target_id = $(e.target).attr('data-target'); $("#panel_" + target_id).remove(); that.trackers.splice(target_id-1, 1); }); } function reOrder(arr, option) { for (var i = 0; i <= arr.length - 1; i++) { for (var j = i; j < arr.length; j++) { if (arr[i][option] > arr[j][option]) { var temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } return arr } function randomColor() { var bg_colour = Math.floor(Math.random() * 16777215).toString(16) bg_colour = "#" + ("000000" + bg_colour).slice(-6) return bg_colour; } Plugin.prototype.renderCuePoints = function() { cuepoints = this.options.cuepoints; cuepoints = reOrder(cuepoints, "seekTime"); for (var i=cuepoints.length-1; i>=0 ; i--) { var totalLen = _getDuration(); if (totalLen > 0) { cuepoints[i].position = cuepoints[i].seekTime * $(".rails").width() / totalLen; } else { cuepoints[i].position = 0; } cuepoints[i].color = randomColor(); cuepoints[i].start = cuepoints[i].seekTime; if(i===cuepoints.length-1 ){ cuepoints[i].end = totalLen; }else{ cuepoints[i].end = cuepoints[i+1].start; } } $(this.element).find("#rail_cues").contents().remove(); $(this.element).find("#rail_cues").append( $(cuepoints_templeate({ cuepoints: cuepoints }))); $(this.element).find("#add_track_cuepoints_content").append( $(cuepoints_list_template({ cuepoints: cuepoints }))); } Plugin.prototype.addTrack = function(name,start,end) { var trackers = this.trackers, trackers_sum = this.trackers.length; if (!name) name = '??? ' + trackers_sum; var new_one = new tracker(trackers_sum, this, name,start, end); currentTracker = new_one; trackers.push(new_one); $(this.element).children("#content_panel").children("#trackers").prepend(new_one.html()); new_one.genneratEvent(); return new_one; } function tracker(id, root, name, start, end) { this.id = id; this.startTime = start ? start : 0; this.endTime = end ? end : _getDuration(); this.root = root; this.name = name; } tracker.prototype.duration = function() { return { startTime: this.startTime, endTime: this.endTime }; } tracker.prototype.html = function() { var width = $('.rails').width(); var left =0; if(this.startTime){ left = (this.startTime)*width/_getDuration(); width = (this.endTime-this.startTime)*width/_getDuration(); } return $(track_template({ 'id': this.id, 'clip_name': this.name, 'clip_width': width, 'clip_left': left, 'clip_start': this.startTime.toString().toHHMMSS(), 'clip_end': this.endTime.toString().toHHMMSS() })); } tracker.prototype.genneratEvent = function() { var id = this.id, that = this, trackers = this.root.trackers, trackers_sum = this.root.trackers.length; var left_handler = $("#handler_" + id + " .left_handler"), right_handler = $("#handler_" + id + " .right_handler"), handlers = $("#handler_" + id), tracer = $("#tracer_" + id), //delete_track = $("#handler_" + id + " .delete_track"), startTime = 0, endTime = 0; handlers.width(tracer.parent().width()) .height(tracer.height()) .css("position", "absolute") .css("z-index", "1002"); var orgin_stat_right = right_handler.offset().left; left_handler.draggable({ cursor: "col-resize", containment: 'parent', axis: "x", refreshPositions: true }); right_handler.draggable({ cursor: "col-resize", containment: 'parent', axis: "x", refreshPositions: true }); left_handler.offset(tracer.offset()); var r = left_handler.offset().left+tracer.width()-right_handler.width(); right_handler.offset({top: null, left:r}); // handlers.width(tracer.width()) // .offset(tracer.offset()) //right_handler.on("mouseenter", function (event) { // //$("#panels_line").offset({ left: tracer.offset().left + tracer.width() }); // $("#panels_line").fadeIn(); //}) right_handler.on("mouseleave", function(event) { $("#panels_line").fadeOut(); }) right_handler.on("drag", { currentTracker: this }, function(event, ui) { if (ui.position.left < left_handler.position().left - $(this).width()) return false; var new_width = Math.round(ui.position.left - left_handler.position().left + left_handler.width()); if (new_width > handlers.width()) { tracer.width(handlers.width()); } else { tracer.width(new_width); } $("#panels_line").show(); $("#panels_line").offset({ left: tracer.offset().left + tracer.width() }); _jumpTo((ui.offset.left - handlers.offset().left + $(this).width()) / handlers.width() * 10, currentTracker, function() { // var time = playerAPI.ready ? playerAPI.getTime() : playerAPI.getClip().duration; // if (!time) time = 0; var time = _getCurrentTime(); handlers.siblings('.count_timer').find("span.right_time").html((time).toString().toHHMMSS()); that.endTime = time; } ); }); //left_handler.on("mouseenter", function (event) { // // $("#panels_line").fadeIn(); // //$("#panels_line").offset({ left: tracer.offset().left }); // $("#panels_line").fadeIn(); //}) left_handler.on("mouseleave", function(event) { $("#panels_line").fadeOut(); }) left_handler.on("drag", function(event, ui) { if (ui.position.left > right_handler.position().left + $(this).width()) return false; tracer.width(Math.round(right_handler.position().left - ui.position.left + $(this).width())); tracer.offset({ top: null, left: Math.round(ui.offset.left + 0.5) }); $("#panels_line").show(); $("#panels_line").offset({ left: tracer.offset().left }); _jumpTo((ui.offset.left - handlers.offset().left) / handlers.width() * 10, currentTracker, function() { // var time = playerAPI.ready ? playerAPI.video.time : 0; //if (!time) time = 0; var time = _getCurrentTime(); if (time != null) { handlers.siblings('.count_timer').find("span.left_time").html((time).toString().toHHMMSS()); that.startTime = time; } } ); }); } function _jumpTo(persence, currentTracker, callback) { if (playerAPI.seekTo == undefined) { playerAPI.seek(persence * _getDuration()); callback.call(currentTracker); } else { playerAPI.seekTo(persence, callback); } } function _getCurrentTime() { // @TODO playerAPI.video??? with class flowplayer //return playerAPI.getTime()|| -1; return playerAPI.ready ? playerAPI.video.time : playerAPI.video.duration; //return playerAPI.getTime(); } function _getDuration() { if (playerAPI) { return playerAPI.ready ? playerAPI.video.duration : -1; //return playerAPI ? playerAPI.getClip().duration : 0; } return -1; } Plugin.prototype.getCuepointsList = function() { var that = this; if (this.options.url.constructor.name == "Array") { $(this.options.url).each(function(index) { $.ajax({ type: "GET", url: that.options.url[index], data: that.paramsData, // crossDomain:true, //dataType: "json", dataType: "xml", jsonp: false }).done(function(results) { var cps = $(results).find("item"); cps.each(function(index, el) { that.options.cuepoints.push({ title: $(el).children("title").text(), seekTime: $(el).children("seekTime").text() / 1000 }); }) that.renderCuePoints(); }).fail(function(jqXHR, textStatus, errorThrown) { }); }); } else { $.ajax({ type: "GET", url: this.options.url, data: this.paramsData, // crossDomain:true, //dataType: "json", dataType: "xml", jsonp: false }).done(function(results) { var cps = $(results).find("item"); cps.each(function(index, el) { that.options.cuepoints.push({ title: $(el).children("title").text(), seekTime: $(el).children("seekTime").text() / 1000 }); }) that.renderCuePoints(); }).fail(function(jqXHR, textStatus, errorThrown) { }); } }; (function() { String.prototype.toHHMMSS = function() { var sec_num = parseInt(this, 10); // don't forget the second parm var hours = Math.floor(sec_num / 3600); var minutes = Math.floor((sec_num - (hours * 3600)) / 60); var seconds = sec_num - (hours * 3600) - (minutes * 60); var minseconds = Math.round((this - sec_num) * 10); if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } //var time = hours+':'+minutes+':'+seconds; var time = minutes + ':' + seconds + ':' + minseconds; return time; } })(); // Closure (function() { /** * Decimal adjustment of a number. * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adjusted value. */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } // Shift value = value.toString().split('e'); value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); // Shift back value = value.toString().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); } // Decimal round if (!Math.round10) { Math.round10 = function(value, exp) { return decimalAdjust('round', value, exp); }; } // Decimal floor if (!Math.floor10) { Math.floor10 = function(value, exp) { return decimalAdjust('floor', value, exp); }; } // Decimal ceil if (!Math.ceil10) { Math.ceil10 = function(value, exp) { return decimalAdjust('ceil', value, exp); }; } })(); $.fn[pluginName] = function(options) { return this.each(function() { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); } }); } }(jQuery)); /** * * Color picker * Author: Stefan Petre www.eyecon.ro * * Dual licensed under the MIT and GPL licenses * */ (function ($) { var ColorPicker = function () { var ids = {}, inAction, charMin = 65, visible, tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>', defaults = { eventName: 'click', onShow: function () {}, onBeforeShow: function(){}, onHide: function () {}, onChange: function () {}, onSubmit: function () {}, color: 'ff0000', livePreview: true, flat: false }, fillRGBFields = function (hsb, cal) { var rgb = HSBToRGB(hsb); $(cal).data('colorpicker').fields .eq(1).val(rgb.r).end() .eq(2).val(rgb.g).end() .eq(3).val(rgb.b).end(); }, fillHSBFields = function (hsb, cal) { $(cal).data('colorpicker').fields .eq(4).val(hsb.h).end() .eq(5).val(hsb.s).end() .eq(6).val(hsb.b).end(); }, fillHexFields = function (hsb, cal) { $(cal).data('colorpicker').fields .eq(0).val(HSBToHex(hsb)).end(); }, setSelector = function (hsb, cal) { $(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100})); $(cal).data('colorpicker').selectorIndic.css({ left: parseInt(150 * hsb.s/100, 10), top: parseInt(150 * (100-hsb.b)/100, 10) }); }, setHue = function (hsb, cal) { $(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10)); }, setCurrentColor = function (hsb, cal) { $(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb)); }, setNewColor = function (hsb, cal) { $(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb)); }, keyDown = function (ev) { var pressedKey = ev.charCode || ev.keyCode || -1; if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) { return false; } var cal = $(this).parent().parent(); if (cal.data('colorpicker').livePreview === true) { change.apply(this); } }, change = function (ev) { var cal = $(this).parent().parent(), col; if (this.parentNode.className.indexOf('_hex') > 0) { cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value)); } else if (this.parentNode.className.indexOf('_hsb') > 0) { cal.data('colorpicker').color = col = fixHSB({ h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10), s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10), b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10) }); } else { cal.data('colorpicker').color = col = RGBToHSB(fixRGB({ r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10), g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10), b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10) })); } if (ev) { fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); } setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]); }, blur = function (ev) { var cal = $(this).parent().parent(); cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus'); }, focus = function () { charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65; $(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus'); $(this).parent().addClass('colorpicker_focus'); }, downIncrement = function (ev) { var field = $(this).parent().find('input').focus(); var current = { el: $(this).parent().addClass('colorpicker_slider'), max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255), y: ev.pageY, field: field, val: parseInt(field.val(), 10), preview: $(this).parent().parent().data('colorpicker').livePreview }; $(document).bind('mouseup', current, upIncrement); $(document).bind('mousemove', current, moveIncrement); }, moveIncrement = function (ev) { ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10)))); if (ev.data.preview) { change.apply(ev.data.field.get(0), [true]); } return false; }, upIncrement = function (ev) { change.apply(ev.data.field.get(0), [true]); ev.data.el.removeClass('colorpicker_slider').find('input').focus(); $(document).unbind('mouseup', upIncrement); $(document).unbind('mousemove', moveIncrement); return false; }, downHue = function (ev) { var current = { cal: $(this).parent(), y: $(this).offset().top }; current.preview = current.cal.data('colorpicker').livePreview; $(document).bind('mouseup', current, upHue); $(document).bind('mousemove', current, moveHue); }, moveHue = function (ev) { change.apply( ev.data.cal.data('colorpicker') .fields .eq(4) .val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10)) .get(0), [ev.data.preview] ); return false; }, upHue = function (ev) { fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); $(document).unbind('mouseup', upHue); $(document).unbind('mousemove', moveHue); return false; }, downSelector = function (ev) { var current = { cal: $(this).parent(), pos: $(this).offset() }; current.preview = current.cal.data('colorpicker').livePreview; $(document).bind('mouseup', current, upSelector); $(document).bind('mousemove', current, moveSelector); }, moveSelector = function (ev) { change.apply( ev.data.cal.data('colorpicker') .fields .eq(6) .val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10)) .end() .eq(5) .val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10)) .get(0), [ev.data.preview] ); return false; }, upSelector = function (ev) { fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); $(document).unbind('mouseup', upSelector); $(document).unbind('mousemove', moveSelector); return false; }, enterSubmit = function (ev) { $(this).addClass('colorpicker_focus'); }, leaveSubmit = function (ev) { $(this).removeClass('colorpicker_focus'); }, clickSubmit = function (ev) { var cal = $(this).parent(); var col = cal.data('colorpicker').color; cal.data('colorpicker').origColor = col; setCurrentColor(col, cal.get(0)); cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el); }, show = function (ev) { var cal = $('#' + $(this).data('colorpickerId')); cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]); var pos = $(this).offset(); var viewPort = getViewport(); var top = pos.top + this.offsetHeight; var left = pos.left; if (top + 176 > viewPort.t + viewPort.h) { top -= this.offsetHeight + 176; } if (left + 356 > viewPort.l + viewPort.w) { left -= 356; } cal.css({left: left + 'px', top: top + 'px'}); if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) { cal.show(); } $(document).bind('mousedown', {cal: cal}, hide); return false; }, hide = function (ev) { if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) { if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) { ev.data.cal.hide(); } $(document).unbind('mousedown', hide); } }, isChildOf = function(parentEl, el, container) { if (parentEl == el) { return true; } if (parentEl.contains) { return parentEl.contains(el); } if ( parentEl.compareDocumentPosition ) { return !!(parentEl.compareDocumentPosition(el) & 16); } var prEl = el.parentNode; while(prEl && prEl != container) { if (prEl == parentEl) return true; prEl = prEl.parentNode; } return false; }, getViewport = function () { var m = document.compatMode == 'CSS1Compat'; return { l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft), t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop), w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth), h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight) }; }, fixHSB = function (hsb) { return { h: Math.min(360, Math.max(0, hsb.h)), s: Math.min(100, Math.max(0, hsb.s)), b: Math.min(100, Math.max(0, hsb.b)) }; }, fixRGB = function (rgb) { return { r: Math.min(255, Math.max(0, rgb.r)), g: Math.min(255, Math.max(0, rgb.g)), b: Math.min(255, Math.max(0, rgb.b)) }; }, fixHex = function (hex) { var len = 6 - hex.length; if (len > 0) { var o = []; for (var i=0; i<len; i++) { o.push('0'); } o.push(hex); hex = o.join(''); } return hex; }, HexToRGB = function (hex) { var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)}; }, HexToHSB = function (hex) { return RGBToHSB(HexToRGB(hex)); }, RGBToHSB = function (rgb) { var hsb = { h: 0, s: 0, b: 0 }; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; if (max != 0) { } hsb.s = max != 0 ? 255 * delta / max : 0; if (hsb.s != 0) { if (rgb.r == max) { hsb.h = (rgb.g - rgb.b) / delta; } else if (rgb.g == max) { hsb.h = 2 + (rgb.b - rgb.r) / delta; } else { hsb.h = 4 + (rgb.r - rgb.g) / delta; } } else { hsb.h = -1; } hsb.h *= 60; if (hsb.h < 0) { hsb.h += 360; } hsb.s *= 100/255; hsb.b *= 100/255; return hsb; }, HSBToRGB = function (hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s*255/100); var v = Math.round(hsb.b*255/100); if(s == 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255-s)*v/255; var t3 = (t1-t2)*(h%60)/60; if(h==360) h = 0; if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3} else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3} else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3} else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3} else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3} else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3} else {rgb.r=0; rgb.g=0; rgb.b=0} } return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)}; }, RGBToHex = function (rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function (nr, val) { if (val.length == 1) { hex[nr] = '0' + val; } }); return hex.join(''); }, HSBToHex = function (hsb) { return RGBToHex(HSBToRGB(hsb)); }, restoreOriginal = function () { var cal = $(this).parent(); var col = cal.data('colorpicker').origColor; cal.data('colorpicker').color = col; fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); }; return { init: function (opt) { opt = $.extend({}, defaults, opt||{}); if (typeof opt.color == 'string') { opt.color = HexToHSB(opt.color); } else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) { opt.color = RGBToHSB(opt.color); } else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) { opt.color = fixHSB(opt.color); } else { return this; } return this.each(function () { if (!$(this).data('colorpickerId')) { var options = $.extend({}, opt); options.origColor = opt.color; var id = 'collorpicker_' + parseInt(Math.random() * 1000); $(this).data('colorpickerId', id); var cal = $(tpl).attr('id', id); if (options.flat) { cal.appendTo(this).show(); } else { cal.appendTo(document.body); } options.fields = cal .find('input') .bind('keyup', keyDown) .bind('change', change) .bind('blur', blur) .bind('focus', focus); cal .find('span').bind('mousedown', downIncrement).end() .find('>div.colorpicker_current_color').bind('click', restoreOriginal); options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector); options.selectorIndic = options.selector.find('div div'); options.el = this; options.hue = cal.find('div.colorpicker_hue div'); cal.find('div.colorpicker_hue').bind('mousedown', downHue); options.newColor = cal.find('div.colorpicker_new_color'); options.currentColor = cal.find('div.colorpicker_current_color'); cal.data('colorpicker', options); cal.find('div.colorpicker_submit') .bind('mouseenter', enterSubmit) .bind('mouseleave', leaveSubmit) .bind('click', clickSubmit); fillRGBFields(options.color, cal.get(0)); fillHSBFields(options.color, cal.get(0)); fillHexFields(options.color, cal.get(0)); setHue(options.color, cal.get(0)); setSelector(options.color, cal.get(0)); setCurrentColor(options.color, cal.get(0)); setNewColor(options.color, cal.get(0)); if (options.flat) { cal.css({ position: 'relative', display: 'block' }); } else { $(this).bind(options.eventName, show); } } }); }, showPicker: function() { return this.each( function () { if ($(this).data('colorpickerId')) { show.apply(this); } }); }, hidePicker: function() { return this.each( function () { if ($(this).data('colorpickerId')) { $('#' + $(this).data('colorpickerId')).hide(); } }); }, setColor: function(col) { if (typeof col == 'string') { col = HexToHSB(col); } else if (col.r != undefined && col.g != undefined && col.b != undefined) { col = RGBToHSB(col); } else if (col.h != undefined && col.s != undefined && col.b != undefined) { col = fixHSB(col); } else { return this; } return this.each(function(){ if ($(this).data('colorpickerId')) { var cal = $('#' + $(this).data('colorpickerId')); cal.data('colorpicker').color = col; cal.data('colorpicker').origColor = col; fillRGBFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); setHue(col, cal.get(0)); setSelector(col, cal.get(0)); setCurrentColor(col, cal.get(0)); setNewColor(col, cal.get(0)); } }); } }; }(); $.fn.extend({ ColorPicker: ColorPicker.init, ColorPickerHide: ColorPicker.hidePicker, ColorPickerShow: ColorPicker.showPicker, ColorPickerSetColor: ColorPicker.setColor }); })(jQuery) /*! DataTables 1.10.4 * ?2008-2014 SpryMedia Ltd - datatables.net/license */ /** * @summary DataTables * @description Paginate, search and order HTML tables * @version 1.10.4 * @file jquery.dataTables.js * @author SpryMedia Ltd (www.sprymedia.co.uk) * @contact www.sprymedia.co.uk/contact * @copyright Copyright 2008-2014 SpryMedia Ltd. * * This source file is free software, available under the following license: * MIT license - http://datatables.net/license * * This source file is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details. * * For details please refer to: http://www.datatables.net */ /*jslint evil: true, undef: true, browser: true */ /*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnScrollBarWidth,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/ (/** @lends <global> */function( window, document, undefined ) { (function( factory ) { "use strict"; if ( typeof define === 'function' && define.amd ) { // Define as an AMD module if possible define( 'datatables', ['jquery'], factory ); } else if ( typeof exports === 'object' ) { // Node/CommonJS factory( require( 'jquery' ) ); } else if ( jQuery && !jQuery.fn.dataTable ) { // Define using browser globals otherwise // Prevent multiple instantiations if the script is loaded twice factory( jQuery ); } } (/** @lends <global> */function( $ ) { "use strict"; /** * DataTables is a plug-in for the jQuery Javascript library. It is a highly * flexible tool, based upon the foundations of progressive enhancement, * which will add advanced interaction controls to any HTML table. For a * full list of features please refer to * [DataTables.net](href="http://datatables.net). * * Note that the `DataTable` object is not a global variable but is aliased * to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may * be accessed. * * @class * @param {object} [init={}] Configuration object for DataTables. Options * are defined by {@link DataTable.defaults} * @requires jQuery 1.7+ * * @example * // Basic initialisation * $(document).ready( function { * $('#example').dataTable(); * } ); * * @example * // Initialisation with configuration options - in this case, disable * // pagination and sorting. * $(document).ready( function { * $('#example').dataTable( { * "paginate": false, * "sort": false * } ); * } ); */ var DataTable; /* * It is useful to have variables which are scoped locally so only the * DataTables functions can access them and they don't leak into global space. * At the same time these functions are often useful over multiple files in the * core and API, so we list, or at least document, all variables which are used * by DataTables as private variables here. This also ensures that there is no * clashing of variable names and that they can easily referenced for reuse. */ // Defined else where // _selector_run // _selector_opts // _selector_first // _selector_row_indexes var _ext; // DataTable.ext var _Api; // DataTable.Api var _api_register; // DataTable.Api.register var _api_registerPlural; // DataTable.Api.registerPlural var _re_dic = {}; var _re_new_lines = /[\r\n]/g; var _re_html = /<.*?>/g; var _re_date_start = /^[\w\+\-]/; var _re_date_end = /[\w\+\-]$/; // Escape regular expression special characters var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' ); // U+2009 is thin space and U+202F is narrow no-break space, both used in many // standards as thousands separators var _re_formatted_numeric = /[',$????%\u2009\u202F]/g; var _empty = function ( d ) { return !d || d === true || d === '-' ? true : false; }; var _intVal = function ( s ) { var integer = parseInt( s, 10 ); return !isNaN(integer) && isFinite(s) ? integer : null; }; // Convert from a formatted number with characters other than `.` as the // decimal place, to a Javascript number var _numToDecimal = function ( num, decimalPoint ) { // Cache created regular expressions for speed as this function is called often if ( ! _re_dic[ decimalPoint ] ) { _re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' ); } return typeof num === 'string' && decimalPoint !== '.' ? num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) : num; }; var _isNumber = function ( d, decimalPoint, formatted ) { var strType = typeof d === 'string'; if ( decimalPoint && strType ) { d = _numToDecimal( d, decimalPoint ); } if ( formatted && strType ) { d = d.replace( _re_formatted_numeric, '' ); } return _empty( d ) || (!isNaN( parseFloat(d) ) && isFinite( d )); }; // A string without HTML in it can be considered to be HTML still var _isHtml = function ( d ) { return _empty( d ) || typeof d === 'string'; }; var _htmlNumeric = function ( d, decimalPoint, formatted ) { if ( _empty( d ) ) { return true; } var html = _isHtml( d ); return ! html ? null : _isNumber( _stripHtml( d ), decimalPoint, formatted ) ? true : null; }; var _pluck = function ( a, prop, prop2 ) { var out = []; var i=0, ien=a.length; // Could have the test in the loop for slightly smaller code, but speed // is essential here if ( prop2 !== undefined ) { for ( ; i<ien ; i++ ) { if ( a[i] && a[i][ prop ] ) { out.push( a[i][ prop ][ prop2 ] ); } } } else { for ( ; i<ien ; i++ ) { if ( a[i] ) { out.push( a[i][ prop ] ); } } } return out; }; // Basically the same as _pluck, but rather than looping over `a` we use `order` // as the indexes to pick from `a` var _pluck_order = function ( a, order, prop, prop2 ) { var out = []; var i=0, ien=order.length; // Could have the test in the loop for slightly smaller code, but speed // is essential here if ( prop2 !== undefined ) { for ( ; i<ien ; i++ ) { if ( a[ order[i] ][ prop ] ) { out.push( a[ order[i] ][ prop ][ prop2 ] ); } } } else { for ( ; i<ien ; i++ ) { out.push( a[ order[i] ][ prop ] ); } } return out; }; var _range = function ( len, start ) { var out = []; var end; if ( start === undefined ) { start = 0; end = len; } else { end = start; start = len; } for ( var i=start ; i<end ; i++ ) { out.push( i ); } return out; }; var _removeEmpty = function ( a ) { var out = []; for ( var i=0, ien=a.length ; i<ien ; i++ ) { if ( a[i] ) { // careful - will remove all falsy values! out.push( a[i] ); } } return out; }; var _stripHtml = function ( d ) { return d.replace( _re_html, '' ); }; /** * Find the unique elements in a source array. * * @param {array} src Source array * @return {array} Array of unique items * @ignore */ var _unique = function ( src ) { // A faster unique method is to use object keys to identify used values, // but this doesn't work with arrays or objects, which we must also // consider. See jsperf.com/compare-array-unique-versions/4 for more // information. var out = [], val, i, ien=src.length, j, k=0; again: for ( i=0 ; i<ien ; i++ ) { val = src[i]; for ( j=0 ; j<k ; j++ ) { if ( out[j] === val ) { continue again; } } out.push( val ); k++; } return out; }; /** * Create a mapping object that allows camel case parameters to be looked up * for their Hungarian counterparts. The mapping is stored in a private * parameter called `_hungarianMap` which can be accessed on the source object. * @param {object} o * @memberof DataTable#oApi */ function _fnHungarianMap ( o ) { var hungarian = 'a aa ai ao as b fn i m o s ', match, newKey, map = {}; $.each( o, function (key, val) { match = key.match(/^([^A-Z]+?)([A-Z])/); if ( match && hungarian.indexOf(match[1]+' ') !== -1 ) { newKey = key.replace( match[0], match[2].toLowerCase() ); map[ newKey ] = key; if ( match[1] === 'o' ) { _fnHungarianMap( o[key] ); } } } ); o._hungarianMap = map; } /** * Convert from camel case parameters to Hungarian, based on a Hungarian map * created by _fnHungarianMap. * @param {object} src The model object which holds all parameters that can be * mapped. * @param {object} user The object to convert from camel case to Hungarian. * @param {boolean} force When set to `true`, properties which already have a * Hungarian value in the `user` object will be overwritten. Otherwise they * won't be. * @memberof DataTable#oApi */ function _fnCamelToHungarian ( src, user, force ) { if ( ! src._hungarianMap ) { _fnHungarianMap( src ); } var hungarianKey; $.each( user, function (key, val) { hungarianKey = src._hungarianMap[ key ]; if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) ) { // For objects, we need to buzz down into the object to copy parameters if ( hungarianKey.charAt(0) === 'o' ) { // Copy the camelCase options over to the hungarian if ( ! user[ hungarianKey ] ) { user[ hungarianKey ] = {}; } $.extend( true, user[hungarianKey], user[key] ); _fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force ); } else { user[hungarianKey] = user[ key ]; } } } ); } /** * Language compatibility - when certain options are given, and others aren't, we * need to duplicate the values over, in order to provide backwards compatibility * with older language files. * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnLanguageCompat( lang ) { var defaults = DataTable.defaults.oLanguage; var zeroRecords = lang.sZeroRecords; /* Backwards compatibility - if there is no sEmptyTable given, then use the same as * sZeroRecords - assuming that is given. */ if ( ! lang.sEmptyTable && zeroRecords && defaults.sEmptyTable === "No data available in table" ) { _fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' ); } /* Likewise with loading records */ if ( ! lang.sLoadingRecords && zeroRecords && defaults.sLoadingRecords === "Loading..." ) { _fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' ); } // Old parameter name of the thousands separator mapped onto the new if ( lang.sInfoThousands ) { lang.sThousands = lang.sInfoThousands; } var decimal = lang.sDecimal; if ( decimal ) { _addNumericSort( decimal ); } } /** * Map one parameter onto another * @param {object} o Object to map * @param {*} knew The new parameter name * @param {*} old The old parameter name */ var _fnCompatMap = function ( o, knew, old ) { if ( o[ knew ] !== undefined ) { o[ old ] = o[ knew ]; } }; /** * Provide backwards compatibility for the main DT options. Note that the new * options are mapped onto the old parameters, so this is an external interface * change only. * @param {object} init Object to map */ function _fnCompatOpts ( init ) { _fnCompatMap( init, 'ordering', 'bSort' ); _fnCompatMap( init, 'orderMulti', 'bSortMulti' ); _fnCompatMap( init, 'orderClasses', 'bSortClasses' ); _fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' ); _fnCompatMap( init, 'order', 'aaSorting' ); _fnCompatMap( init, 'orderFixed', 'aaSortingFixed' ); _fnCompatMap( init, 'paging', 'bPaginate' ); _fnCompatMap( init, 'pagingType', 'sPaginationType' ); _fnCompatMap( init, 'pageLength', 'iDisplayLength' ); _fnCompatMap( init, 'searching', 'bFilter' ); // Column search objects are in an array, so it needs to be converted // element by element var searchCols = init.aoSearchCols; if ( searchCols ) { for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) { if ( searchCols[i] ) { _fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] ); } } } } /** * Provide backwards compatibility for column options. Note that the new options * are mapped onto the old parameters, so this is an external interface change * only. * @param {object} init Object to map */ function _fnCompatCols ( init ) { _fnCompatMap( init, 'orderable', 'bSortable' ); _fnCompatMap( init, 'orderData', 'aDataSort' ); _fnCompatMap( init, 'orderSequence', 'asSorting' ); _fnCompatMap( init, 'orderDataType', 'sortDataType' ); } /** * Browser feature detection for capabilities, quirks * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnBrowserDetect( settings ) { var browser = settings.oBrowser; // Scrolling feature / quirks detection var n = $('<div/>') .css( { position: 'absolute', top: 0, left: 0, height: 1, width: 1, overflow: 'hidden' } ) .append( $('<div/>') .css( { position: 'absolute', top: 1, left: 1, width: 100, overflow: 'scroll' } ) .append( $('<div class="test"/>') .css( { width: '100%', height: 10 } ) ) ) .appendTo( 'body' ); var test = n.find('.test'); // IE6/7 will oversize a width 100% element inside a scrolling element, to // include the width of the scrollbar, while other browsers ensure the inner // element is contained without forcing scrolling browser.bScrollOversize = test[0].offsetWidth === 100; // In rtl text layout, some browsers (most, but not all) will place the // scrollbar on the left, rather than the right. browser.bScrollbarLeft = test.offset().left !== 1; n.remove(); } /** * Array.prototype reduce[Right] method, used for browsers which don't support * JS 1.6. Done this way to reduce code size, since we iterate either way * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnReduce ( that, fn, init, start, end, inc ) { var i = start, value, isSet = false; if ( init !== undefined ) { value = init; isSet = true; } while ( i !== end ) { if ( ! that.hasOwnProperty(i) ) { continue; } value = isSet ? fn( value, that[i], i, that ) : that[i]; isSet = true; i += inc; } return value; } /** * Add a column to the list used for the table with default values * @param {object} oSettings dataTables settings object * @param {node} nTh The th element for this column * @memberof DataTable#oApi */ function _fnAddColumn( oSettings, nTh ) { // Add column to aoColumns array var oDefaults = DataTable.defaults.column; var iCol = oSettings.aoColumns.length; var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, { "nTh": nTh ? nTh : document.createElement('th'), "sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '', "aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol], "mData": oDefaults.mData ? oDefaults.mData : iCol, idx: iCol } ); oSettings.aoColumns.push( oCol ); // Add search object for column specific search. Note that the `searchCols[ iCol ]` // passed into extend can be undefined. This allows the user to give a default // with only some of the parameters defined, and also not give a default var searchCols = oSettings.aoPreSearchCols; searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] ); // Use the default column options function to initialise classes etc _fnColumnOptions( oSettings, iCol, null ); } /** * Apply options for a column * @param {object} oSettings dataTables settings object * @param {int} iCol column index to consider * @param {object} oOptions object with sType, bVisible and bSearchable etc * @memberof DataTable#oApi */ function _fnColumnOptions( oSettings, iCol, oOptions ) { var oCol = oSettings.aoColumns[ iCol ]; var oClasses = oSettings.oClasses; var th = $(oCol.nTh); // Try to get width information from the DOM. We can't get it from CSS // as we'd need to parse the CSS stylesheet. `width` option can override if ( ! oCol.sWidthOrig ) { // Width attribute oCol.sWidthOrig = th.attr('width') || null; // Style attribute var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%]+)/); if ( t ) { oCol.sWidthOrig = t[1]; } } /* User specified column options */ if ( oOptions !== undefined && oOptions !== null ) { // Backwards compatibility _fnCompatCols( oOptions ); // Map camel case parameters to their Hungarian counterparts _fnCamelToHungarian( DataTable.defaults.column, oOptions ); /* Backwards compatibility for mDataProp */ if ( oOptions.mDataProp !== undefined && !oOptions.mData ) { oOptions.mData = oOptions.mDataProp; } if ( oOptions.sType ) { oCol._sManualType = oOptions.sType; } // `class` is a reserved word in Javascript, so we need to provide // the ability to use a valid name for the camel case input if ( oOptions.className && ! oOptions.sClass ) { oOptions.sClass = oOptions.className; } $.extend( oCol, oOptions ); _fnMap( oCol, oOptions, "sWidth", "sWidthOrig" ); /* iDataSort to be applied (backwards compatibility), but aDataSort will take * priority if defined */ if ( typeof oOptions.iDataSort === 'number' ) { oCol.aDataSort = [ oOptions.iDataSort ]; } _fnMap( oCol, oOptions, "aDataSort" ); } /* Cache the data get and set functions for speed */ var mDataSrc = oCol.mData; var mData = _fnGetObjectDataFn( mDataSrc ); var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null; var attrTest = function( src ) { return typeof src === 'string' && src.indexOf('@') !== -1; }; oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && ( attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter) ); oCol.fnGetData = function (rowData, type, meta) { var innerData = mData( rowData, type, undefined, meta ); return mRender && type ? mRender( innerData, type, rowData, meta ) : innerData; }; oCol.fnSetData = function ( rowData, val, meta ) { return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta ); }; // Indicate if DataTables should read DOM data as an object or array // Used in _fnGetRowElements if ( typeof mDataSrc !== 'number' ) { oSettings._rowReadObject = true; } /* Feature sorting overrides column specific when off */ if ( !oSettings.oFeatures.bSort ) { oCol.bSortable = false; th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called } /* Check that the class assignment is correct for sorting */ var bAsc = $.inArray('asc', oCol.asSorting) !== -1; var bDesc = $.inArray('desc', oCol.asSorting) !== -1; if ( !oCol.bSortable || (!bAsc && !bDesc) ) { oCol.sSortingClass = oClasses.sSortableNone; oCol.sSortingClassJUI = ""; } else if ( bAsc && !bDesc ) { oCol.sSortingClass = oClasses.sSortableAsc; oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed; } else if ( !bAsc && bDesc ) { oCol.sSortingClass = oClasses.sSortableDesc; oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed; } else { oCol.sSortingClass = oClasses.sSortable; oCol.sSortingClassJUI = oClasses.sSortJUI; } } /** * Adjust the table column widths for new data. Note: you would probably want to * do a redraw after calling this function! * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnAdjustColumnSizing ( settings ) { /* Not interested in doing column width calculation if auto-width is disabled */ if ( settings.oFeatures.bAutoWidth !== false ) { var columns = settings.aoColumns; _fnCalculateColumnWidths( settings ); for ( var i=0 , iLen=columns.length ; i<iLen ; i++ ) { columns[i].nTh.style.width = columns[i].sWidth; } } var scroll = settings.oScroll; if ( scroll.sY !== '' || scroll.sX !== '') { _fnScrollDraw( settings ); } _fnCallbackFire( settings, null, 'column-sizing', [settings] ); } /** * Covert the index of a visible column to the index in the data array (take account * of hidden columns) * @param {object} oSettings dataTables settings object * @param {int} iMatch Visible column index to lookup * @returns {int} i the data index * @memberof DataTable#oApi */ function _fnVisibleToColumnIndex( oSettings, iMatch ) { var aiVis = _fnGetColumns( oSettings, 'bVisible' ); return typeof aiVis[iMatch] === 'number' ? aiVis[iMatch] : null; } /** * Covert the index of an index in the data array and convert it to the visible * column index (take account of hidden columns) * @param {int} iMatch Column index to lookup * @param {object} oSettings dataTables settings object * @returns {int} i the data index * @memberof DataTable#oApi */ function _fnColumnIndexToVisible( oSettings, iMatch ) { var aiVis = _fnGetColumns( oSettings, 'bVisible' ); var iPos = $.inArray( iMatch, aiVis ); return iPos !== -1 ? iPos : null; } /** * Get the number of visible columns * @param {object} oSettings dataTables settings object * @returns {int} i the number of visible columns * @memberof DataTable#oApi */ function _fnVisbleColumns( oSettings ) { return _fnGetColumns( oSettings, 'bVisible' ).length; } /** * Get an array of column indexes that match a given property * @param {object} oSettings dataTables settings object * @param {string} sParam Parameter in aoColumns to look for - typically * bVisible or bSearchable * @returns {array} Array of indexes with matched properties * @memberof DataTable#oApi */ function _fnGetColumns( oSettings, sParam ) { var a = []; $.map( oSettings.aoColumns, function(val, i) { if ( val[sParam] ) { a.push( i ); } } ); return a; } /** * Calculate the 'type' of a column * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnColumnTypes ( settings ) { var columns = settings.aoColumns; var data = settings.aoData; var types = DataTable.ext.type.detect; var i, ien, j, jen, k, ken; var col, cell, detectedType, cache; // For each column, spin over the for ( i=0, ien=columns.length ; i<ien ; i++ ) { col = columns[i]; cache = []; if ( ! col.sType && col._sManualType ) { col.sType = col._sManualType; } else if ( ! col.sType ) { for ( j=0, jen=types.length ; j<jen ; j++ ) { for ( k=0, ken=data.length ; k<ken ; k++ ) { // Use a cache array so we only need to get the type data // from the formatter once (when using multiple detectors) if ( cache[k] === undefined ) { cache[k] = _fnGetCellData( settings, k, i, 'type' ); } detectedType = types[j]( cache[k], settings ); // If null, then this type can't apply to this column, so // rather than testing all cells, break out. There is an // exception for the last type which is `html`. We need to // scan all rows since it is possible to mix string and HTML // types if ( ! detectedType && j !== types.length-1 ) { break; } // Only a single match is needed for html type since it is // bottom of the pile and very similar to string if ( detectedType === 'html' ) { break; } } // Type is valid for all data points in the column - use this // type if ( detectedType ) { col.sType = detectedType; break; } } // Fall back - if no type was detected, always use string if ( ! col.sType ) { col.sType = 'string'; } } } } /** * Take the column definitions and static columns arrays and calculate how * they relate to column indexes. The callback function will then apply the * definition found for a column to a suitable configuration object. * @param {object} oSettings dataTables settings object * @param {array} aoColDefs The aoColumnDefs array that is to be applied * @param {array} aoCols The aoColumns array that defines columns individually * @param {function} fn Callback function - takes two parameters, the calculated * column index and the definition for that column. * @memberof DataTable#oApi */ function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn ) { var i, iLen, j, jLen, k, kLen, def; var columns = oSettings.aoColumns; // Column definitions with aTargets if ( aoColDefs ) { /* Loop over the definitions array - loop in reverse so first instance has priority */ for ( i=aoColDefs.length-1 ; i>=0 ; i-- ) { def = aoColDefs[i]; /* Each definition can target multiple columns, as it is an array */ var aTargets = def.targets !== undefined ? def.targets : def.aTargets; if ( ! $.isArray( aTargets ) ) { aTargets = [ aTargets ]; } for ( j=0, jLen=aTargets.length ; j<jLen ; j++ ) { if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 ) { /* Add columns that we don't yet know about */ while( columns.length <= aTargets[j] ) { _fnAddColumn( oSettings ); } /* Integer, basic index */ fn( aTargets[j], def ); } else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 ) { /* Negative integer, right to left column counting */ fn( columns.length+aTargets[j], def ); } else if ( typeof aTargets[j] === 'string' ) { /* Class name matching on TH element */ for ( k=0, kLen=columns.length ; k<kLen ; k++ ) { if ( aTargets[j] == "_all" || $(columns[k].nTh).hasClass( aTargets[j] ) ) { fn( k, def ); } } } } } } // Statically defined columns array if ( aoCols ) { for ( i=0, iLen=aoCols.length ; i<iLen ; i++ ) { fn( i, aoCols[i] ); } } } /** * Add a data array to the table, creating DOM node etc. This is the parallel to * _fnGatherData, but for adding rows from a Javascript source, rather than a * DOM source. * @param {object} oSettings dataTables settings object * @param {array} aData data array to be added * @param {node} [nTr] TR element to add to the table - optional. If not given, * DataTables will create a row automatically * @param {array} [anTds] Array of TD|TH elements for the row - must be given * if nTr is. * @returns {int} >=0 if successful (index of new aoData entry), -1 if failed * @memberof DataTable#oApi */ function _fnAddData ( oSettings, aDataIn, nTr, anTds ) { /* Create the object for storing information about this new row */ var iRow = oSettings.aoData.length; var oData = $.extend( true, {}, DataTable.models.oRow, { src: nTr ? 'dom' : 'data' } ); oData._aData = aDataIn; oSettings.aoData.push( oData ); /* Create the cells */ var nTd, sThisType; var columns = oSettings.aoColumns; for ( var i=0, iLen=columns.length ; i<iLen ; i++ ) { // When working with a row, the data source object must be populated. In // all other cases, the data source object is already populated, so we // don't overwrite it, which might break bindings etc if ( nTr ) { _fnSetCellData( oSettings, iRow, i, _fnGetCellData( oSettings, iRow, i ) ); } columns[i].sType = null; } /* Add to the display array */ oSettings.aiDisplayMaster.push( iRow ); /* Create the DOM information, or register it if already present */ if ( nTr || ! oSettings.oFeatures.bDeferRender ) { _fnCreateTr( oSettings, iRow, nTr, anTds ); } return iRow; } /** * Add one or more TR elements to the table. Generally we'd expect to * use this for reading data from a DOM sourced table, but it could be * used for an TR element. Note that if a TR is given, it is used (i.e. * it is not cloned). * @param {object} settings dataTables settings object * @param {array|node|jQuery} trs The TR element(s) to add to the table * @returns {array} Array of indexes for the added rows * @memberof DataTable#oApi */ function _fnAddTr( settings, trs ) { var row; // Allow an individual node to be passed in if ( ! (trs instanceof $) ) { trs = $(trs); } return trs.map( function (i, el) { row = _fnGetRowElements( settings, el ); return _fnAddData( settings, row.data, el, row.cells ); } ); } /** * Take a TR element and convert it to an index in aoData * @param {object} oSettings dataTables settings object * @param {node} n the TR element to find * @returns {int} index if the node is found, null if not * @memberof DataTable#oApi */ function _fnNodeToDataIndex( oSettings, n ) { return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null; } /** * Take a TD element and convert it into a column data index (not the visible index) * @param {object} oSettings dataTables settings object * @param {int} iRow The row number the TD/TH can be found in * @param {node} n The TD/TH element to find * @returns {int} index if the node is found, -1 if not * @memberof DataTable#oApi */ function _fnNodeToColumnIndex( oSettings, iRow, n ) { return $.inArray( n, oSettings.aoData[ iRow ].anCells ); } /** * Get the data for a given cell from the internal cache, taking into account data mapping * @param {object} settings dataTables settings object * @param {int} rowIdx aoData row id * @param {int} colIdx Column index * @param {string} type data get type ('display', 'type' 'filter' 'sort') * @returns {*} Cell data * @memberof DataTable#oApi */ function _fnGetCellData( settings, rowIdx, colIdx, type ) { var draw = settings.iDraw; var col = settings.aoColumns[colIdx]; var rowData = settings.aoData[rowIdx]._aData; var defaultContent = col.sDefaultContent; var cellData = col.fnGetData( rowData, type, { settings: settings, row: rowIdx, col: colIdx } ); if ( cellData === undefined ) { if ( settings.iDrawError != draw && defaultContent === null ) { _fnLog( settings, 0, "Requested unknown parameter "+ (typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+ " for row "+rowIdx, 4 ); settings.iDrawError = draw; } return defaultContent; } /* When the data source is null, we can use default column data */ if ( (cellData === rowData || cellData === null) && defaultContent !== null ) { cellData = defaultContent; } else if ( typeof cellData === 'function' ) { // If the data source is a function, then we run it and use the return, // executing in the scope of the data object (for instances) return cellData.call( rowData ); } if ( cellData === null && type == 'display' ) { return ''; } return cellData; } /** * Set the value for a specific cell, into the internal data cache * @param {object} settings dataTables settings object * @param {int} rowIdx aoData row id * @param {int} colIdx Column index * @param {*} val Value to set * @memberof DataTable#oApi */ function _fnSetCellData( settings, rowIdx, colIdx, val ) { var col = settings.aoColumns[colIdx]; var rowData = settings.aoData[rowIdx]._aData; col.fnSetData( rowData, val, { settings: settings, row: rowIdx, col: colIdx } ); } // Private variable that is used to match action syntax in the data property object var __reArray = /\[.*?\]$/; var __reFn = /\(\)$/; /** * Split string on periods, taking into account escaped periods * @param {string} str String to split * @return {array} Split string */ function _fnSplitObjNotation( str ) { return $.map( str.match(/(\\.|[^\.])+/g), function ( s ) { return s.replace(/\\./g, '.'); } ); } /** * Return a function that can be used to get data from a source object, taking * into account the ability to use nested objects as a source * @param {string|int|function} mSource The data source for the object * @returns {function} Data get function * @memberof DataTable#oApi */ function _fnGetObjectDataFn( mSource ) { if ( $.isPlainObject( mSource ) ) { /* Build an object of get functions, and wrap them in a single call */ var o = {}; $.each( mSource, function (key, val) { if ( val ) { o[key] = _fnGetObjectDataFn( val ); } } ); return function (data, type, row, meta) { var t = o[type] || o._; return t !== undefined ? t(data, type, row, meta) : data; }; } else if ( mSource === null ) { /* Give an empty string for rendering / sorting etc */ return function (data) { // type, row and meta also passed, but not used return data; }; } else if ( typeof mSource === 'function' ) { return function (data, type, row, meta) { return mSource( data, type, row, meta ); }; } else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) ) { /* If there is a . in the source string then the data source is in a * nested object so we loop over the data for each level to get the next * level down. On each loop we test for undefined, and if found immediately * return. This allows entire objects to be missing and sDefaultContent to * be used if defined, rather than throwing an error */ var fetchData = function (data, type, src) { var arrayNotation, funcNotation, out, innerSrc; if ( src !== "" ) { var a = _fnSplitObjNotation( src ); for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { // Check if we are dealing with special notation arrayNotation = a[i].match(__reArray); funcNotation = a[i].match(__reFn); if ( arrayNotation ) { // Array notation a[i] = a[i].replace(__reArray, ''); // Condition allows simply [] to be passed in if ( a[i] !== "" ) { data = data[ a[i] ]; } out = []; // Get the remainder of the nested object to get a.splice( 0, i+1 ); innerSrc = a.join('.'); // Traverse each entry in the array getting the properties requested for ( var j=0, jLen=data.length ; j<jLen ; j++ ) { out.push( fetchData( data[j], type, innerSrc ) ); } // If a string is given in between the array notation indicators, that // is used to join the strings together, otherwise an array is returned var join = arrayNotation[0].substring(1, arrayNotation[0].length-1); data = (join==="") ? out : out.join(join); // The inner call to fetchData has already traversed through the remainder // of the source requested, so we exit from the loop break; } else if ( funcNotation ) { // Function call a[i] = a[i].replace(__reFn, ''); data = data[ a[i] ](); continue; } if ( data === null || data[ a[i] ] === undefined ) { return undefined; } data = data[ a[i] ]; } } return data; }; return function (data, type) { // row and meta also passed, but not used return fetchData( data, type, mSource ); }; } else { /* Array or flat object mapping */ return function (data, type) { // row and meta also passed, but not used return data[mSource]; }; } } /** * Return a function that can be used to set data from a source object, taking * into account the ability to use nested objects as a source * @param {string|int|function} mSource The data source for the object * @returns {function} Data set function * @memberof DataTable#oApi */ function _fnSetObjectDataFn( mSource ) { if ( $.isPlainObject( mSource ) ) { /* Unlike get, only the underscore (global) option is used for for * setting data since we don't know the type here. This is why an object * option is not documented for `mData` (which is read/write), but it is * for `mRender` which is read only. */ return _fnSetObjectDataFn( mSource._ ); } else if ( mSource === null ) { /* Nothing to do when the data source is null */ return function () {}; } else if ( typeof mSource === 'function' ) { return function (data, val, meta) { mSource( data, 'set', val, meta ); }; } else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 || mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) ) { /* Like the get, we need to get data from a nested object */ var setData = function (data, val, src) { var a = _fnSplitObjNotation( src ), b; var aLast = a[a.length-1]; var arrayNotation, funcNotation, o, innerSrc; for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ ) { // Check if we are dealing with an array notation request arrayNotation = a[i].match(__reArray); funcNotation = a[i].match(__reFn); if ( arrayNotation ) { a[i] = a[i].replace(__reArray, ''); data[ a[i] ] = []; // Get the remainder of the nested object to set so we can recurse b = a.slice(); b.splice( 0, i+1 ); innerSrc = b.join('.'); // Traverse each entry in the array setting the properties requested for ( var j=0, jLen=val.length ; j<jLen ; j++ ) { o = {}; setData( o, val[j], innerSrc ); data[ a[i] ].push( o ); } // The inner call to setData has already traversed through the remainder // of the source and has set the data, thus we can exit here return; } else if ( funcNotation ) { // Function call a[i] = a[i].replace(__reFn, ''); data = data[ a[i] ]( val ); } // If the nested object doesn't currently exist - since we are // trying to set the value - create it if ( data[ a[i] ] === null || data[ a[i] ] === undefined ) { data[ a[i] ] = {}; } data = data[ a[i] ]; } // Last item in the input - i.e, the actual set if ( aLast.match(__reFn ) ) { // Function call data = data[ aLast.replace(__reFn, '') ]( val ); } else { // If array notation is used, we just want to strip it and use the property name // and assign the value. If it isn't used, then we get the result we want anyway data[ aLast.replace(__reArray, '') ] = val; } }; return function (data, val) { // meta is also passed in, but not used return setData( data, val, mSource ); }; } else { /* Array or flat object mapping */ return function (data, val) { // meta is also passed in, but not used data[mSource] = val; }; } } /** * Return an array with the full table data * @param {object} oSettings dataTables settings object * @returns array {array} aData Master data array * @memberof DataTable#oApi */ function _fnGetDataMaster ( settings ) { return _pluck( settings.aoData, '_aData' ); } /** * Nuke the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnClearTable( settings ) { settings.aoData.length = 0; settings.aiDisplayMaster.length = 0; settings.aiDisplay.length = 0; } /** * Take an array of integers (index array) and remove a target integer (value - not * the key!) * @param {array} a Index array to target * @param {int} iTarget value to find * @memberof DataTable#oApi */ function _fnDeleteIndex( a, iTarget, splice ) { var iTargetIndex = -1; for ( var i=0, iLen=a.length ; i<iLen ; i++ ) { if ( a[i] == iTarget ) { iTargetIndex = i; } else if ( a[i] > iTarget ) { a[i]--; } } if ( iTargetIndex != -1 && splice === undefined ) { a.splice( iTargetIndex, 1 ); } } /** * Mark cached data as invalid such that a re-read of the data will occur when * the cached data is next requested. Also update from the data source object. * * @param {object} settings DataTables settings object * @param {int} rowIdx Row index to invalidate * @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom' * or 'data' * @param {int} [colIdx] Column index to invalidate. If undefined the whole * row will be invalidated * @memberof DataTable#oApi * * @todo For the modularisation of v1.11 this will need to become a callback, so * the sort and filter methods can subscribe to it. That will required * initialisation options for sorting, which is why it is not already baked in */ function _fnInvalidate( settings, rowIdx, src, colIdx ) { var row = settings.aoData[ rowIdx ]; var i, ien; var cellWrite = function ( cell, col ) { // This is very frustrating, but in IE if you just write directly // to innerHTML, and elements that are overwritten are GC'ed, // even if there is a reference to them elsewhere while ( cell.childNodes.length ) { cell.removeChild( cell.firstChild ); } cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' ); }; // Are we reading last data from DOM or the data object? if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) { // Read the data from the DOM row._aData = _fnGetRowElements( settings, row, colIdx, colIdx === undefined ? undefined : row._aData ) .data; } else { // Reading from data object, update the DOM var cells = row.anCells; if ( cells ) { if ( colIdx !== undefined ) { cellWrite( cells[colIdx], colIdx ); } else { for ( i=0, ien=cells.length ; i<ien ; i++ ) { cellWrite( cells[i], i ); } } } } // For both row and cell invalidation, the cached data for sorting and // filtering is nulled out row._aSortData = null; row._aFilterData = null; // Invalidate the type for a specific column (if given) or all columns since // the data might have changed var cols = settings.aoColumns; if ( colIdx !== undefined ) { cols[ colIdx ].sType = null; } else { for ( i=0, ien=cols.length ; i<ien ; i++ ) { cols[i].sType = null; } // Update DataTables special `DT_*` attributes for the row _fnRowAttributes( row ); } } /** * Build a data source object from an HTML row, reading the contents of the * cells that are in the row. * * @param {object} settings DataTables settings object * @param {node|object} TR element from which to read data or existing row * object from which to re-read the data from the cells * @param {int} [colIdx] Optional column index * @param {array|object} [d] Data source object. If `colIdx` is given then this * parameter should also be given and will be used to write the data into. * Only the column in question will be written * @returns {object} Object with two parameters: `data` the data read, in * document order, and `cells` and array of nodes (they can be useful to the * caller, so rather than needing a second traversal to get them, just return * them from here). * @memberof DataTable#oApi */ function _fnGetRowElements( settings, row, colIdx, d ) { var tds = [], td = row.firstChild, name, col, o, i=0, contents, columns = settings.aoColumns, objectRead = settings._rowReadObject; // Allow the data object to be passed in, or construct d = d || objectRead ? {} : []; var attr = function ( str, td ) { if ( typeof str === 'string' ) { var idx = str.indexOf('@'); if ( idx !== -1 ) { var attr = str.substring( idx+1 ); var setter = _fnSetObjectDataFn( str ); setter( d, td.getAttribute( attr ) ); } } }; // Read data from a cell and store into the data object var cellProcess = function ( cell ) { if ( colIdx === undefined || colIdx === i ) { col = columns[i]; contents = $.trim(cell.innerHTML); if ( col && col._bAttrSrc ) { var setter = _fnSetObjectDataFn( col.mData._ ); setter( d, contents ); attr( col.mData.sort, cell ); attr( col.mData.type, cell ); attr( col.mData.filter, cell ); } else { // Depending on the `data` option for the columns the data can // be read to either an object or an array. if ( objectRead ) { if ( ! col._setter ) { // Cache the setter function col._setter = _fnSetObjectDataFn( col.mData ); } col._setter( d, contents ); } else { d[i] = contents; } } } i++; }; if ( td ) { // `tr` element was passed in while ( td ) { name = td.nodeName.toUpperCase(); if ( name == "TD" || name == "TH" ) { cellProcess( td ); tds.push( td ); } td = td.nextSibling; } } else { // Existing row object passed in tds = row.anCells; for ( var j=0, jen=tds.length ; j<jen ; j++ ) { cellProcess( tds[j] ); } } return { data: d, cells: tds }; } /** * Create a new TR element (and it's TD children) for a row * @param {object} oSettings dataTables settings object * @param {int} iRow Row to consider * @param {node} [nTrIn] TR element to add to the table - optional. If not given, * DataTables will create a row automatically * @param {array} [anTds] Array of TD|TH elements for the row - must be given * if nTr is. * @memberof DataTable#oApi */ function _fnCreateTr ( oSettings, iRow, nTrIn, anTds ) { var row = oSettings.aoData[iRow], rowData = row._aData, cells = [], nTr, nTd, oCol, i, iLen; if ( row.nTr === null ) { nTr = nTrIn || document.createElement('tr'); row.nTr = nTr; row.anCells = cells; /* Use a private property on the node to allow reserve mapping from the node * to the aoData array for fast look up */ nTr._DT_RowIndex = iRow; /* Special parameters can be given by the data source to be used on the row */ _fnRowAttributes( row ); /* Process each column */ for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ ) { oCol = oSettings.aoColumns[i]; nTd = nTrIn ? anTds[i] : document.createElement( oCol.sCellType ); cells.push( nTd ); // Need to create the HTML if new, or if a rendering function is defined if ( !nTrIn || oCol.mRender || oCol.mData !== i ) { nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' ); } /* Add user defined class */ if ( oCol.sClass ) { nTd.className += ' '+oCol.sClass; } // Visibility - add or remove as required if ( oCol.bVisible && ! nTrIn ) { nTr.appendChild( nTd ); } else if ( ! oCol.bVisible && nTrIn ) { nTd.parentNode.removeChild( nTd ); } if ( oCol.fnCreatedCell ) { oCol.fnCreatedCell.call( oSettings.oInstance, nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i ); } } _fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow] ); } // Remove once webkit bug 131819 and Chromium bug 365619 have been resolved // and deployed row.nTr.setAttribute( 'role', 'row' ); } /** * Add attributes to a row based on the special `DT_*` parameters in a data * source object. * @param {object} DataTables row object for the row to be modified * @memberof DataTable#oApi */ function _fnRowAttributes( row ) { var tr = row.nTr; var data = row._aData; if ( tr ) { if ( data.DT_RowId ) { tr.id = data.DT_RowId; } if ( data.DT_RowClass ) { // Remove any classes added by DT_RowClass before var a = data.DT_RowClass.split(' '); row.__rowc = row.__rowc ? _unique( row.__rowc.concat( a ) ) : a; $(tr) .removeClass( row.__rowc.join(' ') ) .addClass( data.DT_RowClass ); } if ( data.DT_RowData ) { $(tr).data( data.DT_RowData ); } } } /** * Create the HTML header for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnBuildHead( oSettings ) { var i, ien, cell, row, column; var thead = oSettings.nTHead; var tfoot = oSettings.nTFoot; var createHeader = $('th, td', thead).length === 0; var classes = oSettings.oClasses; var columns = oSettings.aoColumns; if ( createHeader ) { row = $('<tr/>').appendTo( thead ); } for ( i=0, ien=columns.length ; i<ien ; i++ ) { column = columns[i]; cell = $( column.nTh ).addClass( column.sClass ); if ( createHeader ) { cell.appendTo( row ); } // 1.11 move into sorting if ( oSettings.oFeatures.bSort ) { cell.addClass( column.sSortingClass ); if ( column.bSortable !== false ) { cell .attr( 'tabindex', oSettings.iTabIndex ) .attr( 'aria-controls', oSettings.sTableId ); _fnSortAttachListener( oSettings, column.nTh, i ); } } if ( column.sTitle != cell.html() ) { cell.html( column.sTitle ); } _fnRenderer( oSettings, 'header' )( oSettings, cell, column, classes ); } if ( createHeader ) { _fnDetectHeader( oSettings.aoHeader, thead ); } /* ARIA role for the rows */ $(thead).find('>tr').attr('role', 'row'); /* Deal with the footer - add classes if required */ $(thead).find('>tr>th, >tr>td').addClass( classes.sHeaderTH ); $(tfoot).find('>tr>th, >tr>td').addClass( classes.sFooterTH ); // Cache the footer cells. Note that we only take the cells from the first // row in the footer. If there is more than one row the user wants to // interact with, they need to use the table().foot() method. Note also this // allows cells to be used for multiple columns using colspan if ( tfoot !== null ) { var cells = oSettings.aoFooter[0]; for ( i=0, ien=cells.length ; i<ien ; i++ ) { column = columns[i]; column.nTf = cells[i].cell; if ( column.sClass ) { $(column.nTf).addClass( column.sClass ); } } } } /** * Draw the header (or footer) element based on the column visibility states. The * methodology here is to use the layout array from _fnDetectHeader, modified for * the instantaneous column visibility, to construct the new layout. The grid is * traversed over cell at a time in a rows x columns grid fashion, although each * cell insert can cover multiple elements in the grid - which is tracks using the * aApplied array. Cell inserts in the grid will only occur where there isn't * already a cell in that position. * @param {object} oSettings dataTables settings object * @param array {objects} aoSource Layout array from _fnDetectHeader * @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc, * @memberof DataTable#oApi */ function _fnDrawHead( oSettings, aoSource, bIncludeHidden ) { var i, iLen, j, jLen, k, kLen, n, nLocalTr; var aoLocal = []; var aApplied = []; var iColumns = oSettings.aoColumns.length; var iRowspan, iColspan; if ( ! aoSource ) { return; } if ( bIncludeHidden === undefined ) { bIncludeHidden = false; } /* Make a copy of the master layout array, but without the visible columns in it */ for ( i=0, iLen=aoSource.length ; i<iLen ; i++ ) { aoLocal[i] = aoSource[i].slice(); aoLocal[i].nTr = aoSource[i].nTr; /* Remove any columns which are currently hidden */ for ( j=iColumns-1 ; j>=0 ; j-- ) { if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden ) { aoLocal[i].splice( j, 1 ); } } /* Prep the applied array - it needs an element for each row */ aApplied.push( [] ); } for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ ) { nLocalTr = aoLocal[i].nTr; /* All cells are going to be replaced, so empty out the row */ if ( nLocalTr ) { while( (n = nLocalTr.firstChild) ) { nLocalTr.removeChild( n ); } } for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ ) { iRowspan = 1; iColspan = 1; /* Check to see if there is already a cell (row/colspan) covering our target * insert point. If there is, then there is nothing to do. */ if ( aApplied[i][j] === undefined ) { nLocalTr.appendChild( aoLocal[i][j].cell ); aApplied[i][j] = 1; /* Expand the cell to cover as many rows as needed */ while ( aoLocal[i+iRowspan] !== undefined && aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell ) { aApplied[i+iRowspan][j] = 1; iRowspan++; } /* Expand the cell to cover as many columns as needed */ while ( aoLocal[i][j+iColspan] !== undefined && aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell ) { /* Must update the applied array over the rows for the columns */ for ( k=0 ; k<iRowspan ; k++ ) { aApplied[i+k][j+iColspan] = 1; } iColspan++; } /* Do the actual expansion in the DOM */ $(aoLocal[i][j].cell) .attr('rowspan', iRowspan) .attr('colspan', iColspan); } } } } /** * Insert the required TR nodes into the table for display * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnDraw( oSettings ) { /* Provide a pre-callback function which can be used to cancel the draw is false is returned */ var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] ); if ( $.inArray( false, aPreDraw ) !== -1 ) { _fnProcessingDisplay( oSettings, false ); return; } var i, iLen, n; var anRows = []; var iRowCount = 0; var asStripeClasses = oSettings.asStripeClasses; var iStripes = asStripeClasses.length; var iOpenRows = oSettings.aoOpenRows.length; var oLang = oSettings.oLanguage; var iInitDisplayStart = oSettings.iInitDisplayStart; var bServerSide = _fnDataSource( oSettings ) == 'ssp'; var aiDisplay = oSettings.aiDisplay; oSettings.bDrawing = true; /* Check and see if we have an initial draw position from state saving */ if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 ) { oSettings._iDisplayStart = bServerSide ? iInitDisplayStart : iInitDisplayStart >= oSettings.fnRecordsDisplay() ? 0 : iInitDisplayStart; oSettings.iInitDisplayStart = -1; } var iDisplayStart = oSettings._iDisplayStart; var iDisplayEnd = oSettings.fnDisplayEnd(); /* Server-side processing draw intercept */ if ( oSettings.bDeferLoading ) { oSettings.bDeferLoading = false; oSettings.iDraw++; _fnProcessingDisplay( oSettings, false ); } else if ( !bServerSide ) { oSettings.iDraw++; } else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) ) { return; } if ( aiDisplay.length !== 0 ) { var iStart = bServerSide ? 0 : iDisplayStart; var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd; for ( var j=iStart ; j<iEnd ; j++ ) { var iDataIndex = aiDisplay[j]; var aoData = oSettings.aoData[ iDataIndex ]; if ( aoData.nTr === null ) { _fnCreateTr( oSettings, iDataIndex ); } var nRow = aoData.nTr; /* Remove the old striping classes and then add the new one */ if ( iStripes !== 0 ) { var sStripe = asStripeClasses[ iRowCount % iStripes ]; if ( aoData._sRowStripe != sStripe ) { $(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe ); aoData._sRowStripe = sStripe; } } // Row callback functions - might want to manipulate the row // iRowCount and j are not currently documented. Are they at all // useful? _fnCallbackFire( oSettings, 'aoRowCallback', null, [nRow, aoData._aData, iRowCount, j] ); anRows.push( nRow ); iRowCount++; } } else { /* Table is empty - create a row with an empty message in it */ var sZero = oLang.sZeroRecords; if ( oSettings.iDraw == 1 && _fnDataSource( oSettings ) == 'ajax' ) { sZero = oLang.sLoadingRecords; } else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 ) { sZero = oLang.sEmptyTable; } anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } ) .append( $('<td />', { 'valign': 'top', 'colSpan': _fnVisbleColumns( oSettings ), 'class': oSettings.oClasses.sRowEmpty } ).html( sZero ) )[0]; } /* Header and footer callbacks */ _fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0], _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] ); _fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0], _fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] ); var body = $(oSettings.nTBody); body.children().detach(); body.append( $(anRows) ); /* Call all required callback functions for the end of a draw */ _fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] ); /* Draw is complete, sorting and filtering must be as well */ oSettings.bSorted = false; oSettings.bFiltered = false; oSettings.bDrawing = false; } /** * Redraw the table - taking account of the various features which are enabled * @param {object} oSettings dataTables settings object * @param {boolean} [holdPosition] Keep the current paging position. By default * the paging is reset to the first page * @memberof DataTable#oApi */ function _fnReDraw( settings, holdPosition ) { var features = settings.oFeatures, sort = features.bSort, filter = features.bFilter; if ( sort ) { _fnSort( settings ); } if ( filter ) { _fnFilterComplete( settings, settings.oPreviousSearch ); } else { // No filtering, so we want to just use the display master settings.aiDisplay = settings.aiDisplayMaster.slice(); } if ( holdPosition !== true ) { settings._iDisplayStart = 0; } // Let any modules know about the draw hold position state (used by // scrolling internally) settings._drawHold = holdPosition; _fnDraw( settings ); settings._drawHold = false; } /** * Add the options to the page HTML for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnAddOptionsHtml ( oSettings ) { var classes = oSettings.oClasses; var table = $(oSettings.nTable); var holding = $('<div/>').insertBefore( table ); // Holding element for speed var features = oSettings.oFeatures; // All DataTables are wrapped in a div var insert = $('<div/>', { id: oSettings.sTableId+'_wrapper', 'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter) } ); oSettings.nHolding = holding[0]; oSettings.nTableWrapper = insert[0]; oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling; /* Loop over the user set positioning and place the elements as needed */ var aDom = oSettings.sDom.split(''); var featureNode, cOption, nNewNode, cNext, sAttr, j; for ( var i=0 ; i<aDom.length ; i++ ) { featureNode = null; cOption = aDom[i]; if ( cOption == '<' ) { /* New container div */ nNewNode = $('<div/>')[0]; /* Check to see if we should append an id and/or a class name to the container */ cNext = aDom[i+1]; if ( cNext == "'" || cNext == '"' ) { sAttr = ""; j = 2; while ( aDom[i+j] != cNext ) { sAttr += aDom[i+j]; j++; } /* Replace jQuery UI constants @todo depreciated */ if ( sAttr == "H" ) { sAttr = classes.sJUIHeader; } else if ( sAttr == "F" ) { sAttr = classes.sJUIFooter; } /* The attribute can be in the format of "#id.class", "#id" or "class" This logic * breaks the string into parts and applies them as needed */ if ( sAttr.indexOf('.') != -1 ) { var aSplit = sAttr.split('.'); nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1); nNewNode.className = aSplit[1]; } else if ( sAttr.charAt(0) == "#" ) { nNewNode.id = sAttr.substr(1, sAttr.length-1); } else { nNewNode.className = sAttr; } i += j; /* Move along the position array */ } insert.append( nNewNode ); insert = $(nNewNode); } else if ( cOption == '>' ) { /* End container div */ insert = insert.parent(); } // @todo Move options into their own plugins? else if ( cOption == 'l' && features.bPaginate && features.bLengthChange ) { /* Length */ featureNode = _fnFeatureHtmlLength( oSettings ); } else if ( cOption == 'f' && features.bFilter ) { /* Filter */ featureNode = _fnFeatureHtmlFilter( oSettings ); } else if ( cOption == 'r' && features.bProcessing ) { /* pRocessing */ featureNode = _fnFeatureHtmlProcessing( oSettings ); } else if ( cOption == 't' ) { /* Table */ featureNode = _fnFeatureHtmlTable( oSettings ); } else if ( cOption == 'i' && features.bInfo ) { /* Info */ featureNode = _fnFeatureHtmlInfo( oSettings ); } else if ( cOption == 'p' && features.bPaginate ) { /* Pagination */ featureNode = _fnFeatureHtmlPaginate( oSettings ); } else if ( DataTable.ext.feature.length !== 0 ) { /* Plug-in features */ var aoFeatures = DataTable.ext.feature; for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ ) { if ( cOption == aoFeatures[k].cFeature ) { featureNode = aoFeatures[k].fnInit( oSettings ); break; } } } /* Add to the 2D features array */ if ( featureNode ) { var aanFeatures = oSettings.aanFeatures; if ( ! aanFeatures[cOption] ) { aanFeatures[cOption] = []; } aanFeatures[cOption].push( featureNode ); insert.append( featureNode ); } } /* Built our DOM structure - replace the holding div with what we want */ holding.replaceWith( insert ); } /** * Use the DOM source to create up an array of header cells. The idea here is to * create a layout grid (array) of rows x columns, which contains a reference * to the cell that that point in the grid (regardless of col/rowspan), such that * any column / row could be removed and the new grid constructed * @param array {object} aLayout Array to store the calculated layout in * @param {node} nThead The header/footer element for the table * @memberof DataTable#oApi */ function _fnDetectHeader ( aLayout, nThead ) { var nTrs = $(nThead).children('tr'); var nTr, nCell; var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan; var bUnique; var fnShiftCol = function ( a, i, j ) { var k = a[i]; while ( k[j] ) { j++; } return j; }; aLayout.splice( 0, aLayout.length ); /* We know how many rows there are in the layout - so prep it */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { aLayout.push( [] ); } /* Calculate a layout array */ for ( i=0, iLen=nTrs.length ; i<iLen ; i++ ) { nTr = nTrs[i]; iColumn = 0; /* For every cell in the row... */ nCell = nTr.firstChild; while ( nCell ) { if ( nCell.nodeName.toUpperCase() == "TD" || nCell.nodeName.toUpperCase() == "TH" ) { /* Get the col and rowspan attributes from the DOM and sanitise them */ iColspan = nCell.getAttribute('colspan') * 1; iRowspan = nCell.getAttribute('rowspan') * 1; iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan; iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan; /* There might be colspan cells already in this row, so shift our target * accordingly */ iColShifted = fnShiftCol( aLayout, i, iColumn ); /* Cache calculation for unique columns */ bUnique = iColspan === 1 ? true : false; /* If there is col / rowspan, copy the information into the layout grid */ for ( l=0 ; l<iColspan ; l++ ) { for ( k=0 ; k<iRowspan ; k++ ) { aLayout[i+k][iColShifted+l] = { "cell": nCell, "unique": bUnique }; aLayout[i+k].nTr = nTr; } } } nCell = nCell.nextSibling; } } } /** * Get an array of unique th elements, one for each column * @param {object} oSettings dataTables settings object * @param {node} nHeader automatically detect the layout from this node - optional * @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional * @returns array {node} aReturn list of unique th's * @memberof DataTable#oApi */ function _fnGetUniqueThs ( oSettings, nHeader, aLayout ) { var aReturn = []; if ( !aLayout ) { aLayout = oSettings.aoHeader; if ( nHeader ) { aLayout = []; _fnDetectHeader( aLayout, nHeader ); } } for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ ) { for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ ) { if ( aLayout[i][j].unique && (!aReturn[j] || !oSettings.bSortCellsTop) ) { aReturn[j] = aLayout[i][j].cell; } } } return aReturn; } /** * Create an Ajax call based on the table's settings, taking into account that * parameters can have multiple forms, and backwards compatibility. * * @param {object} oSettings dataTables settings object * @param {array} data Data to send to the server, required by * DataTables - may be augmented by developer callbacks * @param {function} fn Callback function to run when data is obtained */ function _fnBuildAjax( oSettings, data, fn ) { // Compatibility with 1.9-, allow fnServerData and event to manipulate _fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] ); // Convert to object based for 1.10+ if using the old array scheme which can // come from server-side processing or serverParams if ( data && $.isArray(data) ) { var tmp = {}; var rbracket = /(.*?)\[\]$/; $.each( data, function (key, val) { var match = val.name.match(rbracket); if ( match ) { // Support for arrays var name = match[0]; if ( ! tmp[ name ] ) { tmp[ name ] = []; } tmp[ name ].push( val.value ); } else { tmp[val.name] = val.value; } } ); data = tmp; } var ajaxData; var ajax = oSettings.ajax; var instance = oSettings.oInstance; if ( $.isPlainObject( ajax ) && ajax.data ) { ajaxData = ajax.data; var newData = $.isFunction( ajaxData ) ? ajaxData( data ) : // fn can manipulate data or return an object ajaxData; // object or array to merge // If the function returned an object, use that alone data = $.isFunction( ajaxData ) && newData ? newData : $.extend( true, data, newData ); // Remove the data property as we've resolved it already and don't want // jQuery to do it again (it is restored at the end of the function) delete ajax.data; } var baseAjax = { "data": data, "success": function (json) { var error = json.error || json.sError; if ( error ) { oSettings.oApi._fnLog( oSettings, 0, error ); } oSettings.json = json; _fnCallbackFire( oSettings, null, 'xhr', [oSettings, json] ); fn( json ); }, "dataType": "json", "cache": false, "type": oSettings.sServerMethod, "error": function (xhr, error, thrown) { var log = oSettings.oApi._fnLog; if ( error == "parsererror" ) { log( oSettings, 0, 'Invalid JSON response', 1 ); } else if ( xhr.readyState === 4 ) { log( oSettings, 0, 'Ajax error', 7 ); } _fnProcessingDisplay( oSettings, false ); } }; // Store the data submitted for the API oSettings.oAjaxData = data; // Allow plug-ins and external processes to modify the data _fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] ); if ( oSettings.fnServerData ) { // DataTables 1.9- compatibility oSettings.fnServerData.call( instance, oSettings.sAjaxSource, $.map( data, function (val, key) { // Need to convert back to 1.9 trad format return { name: key, value: val }; } ), fn, oSettings ); } else if ( oSettings.sAjaxSource || typeof ajax === 'string' ) { // DataTables 1.9- compatibility oSettings.jqXHR = $.ajax( $.extend( baseAjax, { url: ajax || oSettings.sAjaxSource } ) ); } else if ( $.isFunction( ajax ) ) { // Is a function - let the caller define what needs to be done oSettings.jqXHR = ajax.call( instance, data, fn, oSettings ); } else { // Object to extend the base settings oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) ); // Restore for next time around ajax.data = ajaxData; } } /** * Update the table using an Ajax call * @param {object} settings dataTables settings object * @returns {boolean} Block the table drawing or not * @memberof DataTable#oApi */ function _fnAjaxUpdate( settings ) { if ( settings.bAjaxDataGet ) { settings.iDraw++; _fnProcessingDisplay( settings, true ); _fnBuildAjax( settings, _fnAjaxParameters( settings ), function(json) { _fnAjaxUpdateDraw( settings, json ); } ); return false; } return true; } /** * Build up the parameters in an object needed for a server-side processing * request. Note that this is basically done twice, is different ways - a modern * method which is used by default in DataTables 1.10 which uses objects and * arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if * the sAjaxSource option is used in the initialisation, or the legacyAjax * option is set. * @param {object} oSettings dataTables settings object * @returns {bool} block the table drawing or not * @memberof DataTable#oApi */ function _fnAjaxParameters( settings ) { var columns = settings.aoColumns, columnCount = columns.length, features = settings.oFeatures, preSearch = settings.oPreviousSearch, preColSearch = settings.aoPreSearchCols, i, data = [], dataProp, column, columnSearch, sort = _fnSortFlatten( settings ), displayStart = settings._iDisplayStart, displayLength = features.bPaginate !== false ? settings._iDisplayLength : -1; var param = function ( name, value ) { data.push( { 'name': name, 'value': value } ); }; // DataTables 1.9- compatible method param( 'sEcho', settings.iDraw ); param( 'iColumns', columnCount ); param( 'sColumns', _pluck( columns, 'sName' ).join(',') ); param( 'iDisplayStart', displayStart ); param( 'iDisplayLength', displayLength ); // DataTables 1.10+ method var d = { draw: settings.iDraw, columns: [], order: [], start: displayStart, length: displayLength, search: { value: preSearch.sSearch, regex: preSearch.bRegex } }; for ( i=0 ; i<columnCount ; i++ ) { column = columns[i]; columnSearch = preColSearch[i]; dataProp = typeof column.mData=="function" ? 'function' : column.mData ; d.columns.push( { data: dataProp, name: column.sName, searchable: column.bSearchable, orderable: column.bSortable, search: { value: columnSearch.sSearch, regex: columnSearch.bRegex } } ); param( "mDataProp_"+i, dataProp ); if ( features.bFilter ) { param( 'sSearch_'+i, columnSearch.sSearch ); param( 'bRegex_'+i, columnSearch.bRegex ); param( 'bSearchable_'+i, column.bSearchable ); } if ( features.bSort ) { param( 'bSortable_'+i, column.bSortable ); } } if ( features.bFilter ) { param( 'sSearch', preSearch.sSearch ); param( 'bRegex', preSearch.bRegex ); } if ( features.bSort ) { $.each( sort, function ( i, val ) { d.order.push( { column: val.col, dir: val.dir } ); param( 'iSortCol_'+i, val.col ); param( 'sSortDir_'+i, val.dir ); } ); param( 'iSortingCols', sort.length ); } // If the legacy.ajax parameter is null, then we automatically decide which // form to use, based on sAjaxSource var legacy = DataTable.ext.legacy.ajax; if ( legacy === null ) { return settings.sAjaxSource ? data : d; } // Otherwise, if legacy has been specified then we use that to decide on the // form return legacy ? data : d; } /** * Data the data from the server (nuking the old) and redraw the table * @param {object} oSettings dataTables settings object * @param {object} json json data return from the server. * @param {string} json.sEcho Tracking flag for DataTables to match requests * @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering * @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering * @param {array} json.aaData The data to display on this page * @param {string} [json.sColumns] Column ordering (sName, comma separated) * @memberof DataTable#oApi */ function _fnAjaxUpdateDraw ( settings, json ) { // v1.10 uses camelCase variables, while 1.9 uses Hungarian notation. // Support both var compat = function ( old, modern ) { return json[old] !== undefined ? json[old] : json[modern]; }; var draw = compat( 'sEcho', 'draw' ); var recordsTotal = compat( 'iTotalRecords', 'recordsTotal' ); var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' ); if ( draw ) { // Protect against out of sequence returns if ( draw*1 < settings.iDraw ) { return; } settings.iDraw = draw * 1; } _fnClearTable( settings ); settings._iRecordsTotal = parseInt(recordsTotal, 10); settings._iRecordsDisplay = parseInt(recordsFiltered, 10); var data = _fnAjaxDataSrc( settings, json ); for ( var i=0, ien=data.length ; i<ien ; i++ ) { _fnAddData( settings, data[i] ); } settings.aiDisplay = settings.aiDisplayMaster.slice(); settings.bAjaxDataGet = false; _fnDraw( settings ); if ( ! settings._bInitComplete ) { _fnInitComplete( settings, json ); } settings.bAjaxDataGet = true; _fnProcessingDisplay( settings, false ); } /** * Get the data from the JSON data source to use for drawing a table. Using * `_fnGetObjectDataFn` allows the data to be sourced from a property of the * source object, or from a processing function. * @param {object} oSettings dataTables settings object * @param {object} json Data source object / array from the server * @return {array} Array of data to use */ function _fnAjaxDataSrc ( oSettings, json ) { var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ? oSettings.ajax.dataSrc : oSettings.sAjaxDataProp; // Compatibility with 1.9-. // Compatibility with 1.9-. In order to read from aaData, check if the // default has been changed, if not, check for aaData if ( dataSrc === 'data' ) { return json.aaData || json[dataSrc]; } return dataSrc !== "" ? _fnGetObjectDataFn( dataSrc )( json ) : json; } /** * Generate the node required for filtering text * @returns {node} Filter control element * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFeatureHtmlFilter ( settings ) { var classes = settings.oClasses; var tableId = settings.sTableId; var language = settings.oLanguage; var previousSearch = settings.oPreviousSearch; var features = settings.aanFeatures; var input = '<input type="search" class="'+classes.sFilterInput+'"/>'; var str = language.sSearch; str = str.match(/_INPUT_/) ? str.replace('_INPUT_', input) : str+input; var filter = $('<div/>', { 'id': ! features.f ? tableId+'_filter' : null, 'class': classes.sFilter } ) .append( $('<label/>' ).append( str ) ); var searchFn = function() { /* Update all other filter input elements for the new display */ var n = features.f; var val = !this.value ? "" : this.value; // mental IE8 fix :-( /* Now do the filter */ if ( val != previousSearch.sSearch ) { _fnFilterComplete( settings, { "sSearch": val, "bRegex": previousSearch.bRegex, "bSmart": previousSearch.bSmart , "bCaseInsensitive": previousSearch.bCaseInsensitive } ); // Need to redraw, without resorting settings._iDisplayStart = 0; _fnDraw( settings ); } }; var searchDelay = settings.searchDelay !== null ? settings.searchDelay : _fnDataSource( settings ) === 'ssp' ? 400 : 0; var jqFilter = $('input', filter) .val( previousSearch.sSearch ) .attr( 'placeholder', language.sSearchPlaceholder ) .bind( 'keyup.DT search.DT input.DT paste.DT cut.DT', searchDelay ? _fnThrottle( searchFn, searchDelay ) : searchFn ) .bind( 'keypress.DT', function(e) { /* Prevent form submission */ if ( e.keyCode == 13 ) { return false; } } ) .attr('aria-controls', tableId); // Update the input elements whenever the table is filtered $(settings.nTable).on( 'search.dt.DT', function ( ev, s ) { if ( settings === s ) { // IE9 throws an 'unknown error' if document.activeElement is used // inside an iframe or frame... try { if ( jqFilter[0] !== document.activeElement ) { jqFilter.val( previousSearch.sSearch ); } } catch ( e ) {} } } ); return filter[0]; } /** * Filter the table using both the global filter and column based filtering * @param {object} oSettings dataTables settings object * @param {object} oSearch search information * @param {int} [iForce] force a research of the master array (1) or not (undefined or 0) * @memberof DataTable#oApi */ function _fnFilterComplete ( oSettings, oInput, iForce ) { var oPrevSearch = oSettings.oPreviousSearch; var aoPrevSearch = oSettings.aoPreSearchCols; var fnSaveFilter = function ( oFilter ) { /* Save the filtering values */ oPrevSearch.sSearch = oFilter.sSearch; oPrevSearch.bRegex = oFilter.bRegex; oPrevSearch.bSmart = oFilter.bSmart; oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive; }; var fnRegex = function ( o ) { // Backwards compatibility with the bEscapeRegex option return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex; }; // Resolve any column types that are unknown due to addition or invalidation // @todo As per sort - can this be moved into an event handler? _fnColumnTypes( oSettings ); /* In server-side processing all filtering is done by the server, so no point hanging around here */ if ( _fnDataSource( oSettings ) != 'ssp' ) { /* Global filter */ _fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive ); fnSaveFilter( oInput ); /* Now do the individual column filter */ for ( var i=0 ; i<aoPrevSearch.length ; i++ ) { _fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]), aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive ); } /* Custom filtering */ _fnFilterCustom( oSettings ); } else { fnSaveFilter( oInput ); } /* Tell the draw function we have been filtering */ oSettings.bFiltered = true; _fnCallbackFire( oSettings, null, 'search', [oSettings] ); } /** * Apply custom filtering functions * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnFilterCustom( settings ) { var filters = DataTable.ext.search; var displayRows = settings.aiDisplay; var row, rowIdx; for ( var i=0, ien=filters.length ; i<ien ; i++ ) { var rows = []; // Loop over each row and see if it should be included for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) { rowIdx = displayRows[ j ]; row = settings.aoData[ rowIdx ]; if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) { rows.push( rowIdx ); } } // So the array reference doesn't break set the results into the // existing array displayRows.length = 0; displayRows.push.apply( displayRows, rows ); } } /** * Filter the table on a per-column basis * @param {object} oSettings dataTables settings object * @param {string} sInput string to filter on * @param {int} iColumn column to filter * @param {bool} bRegex treat search string as a regular expression or not * @param {bool} bSmart use smart filtering or not * @param {bool} bCaseInsensitive Do case insenstive matching or not * @memberof DataTable#oApi */ function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive ) { if ( searchStr === '' ) { return; } var data; var display = settings.aiDisplay; var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive ); for ( var i=display.length-1 ; i>=0 ; i-- ) { data = settings.aoData[ display[i] ]._aFilterData[ colIdx ]; if ( ! rpSearch.test( data ) ) { display.splice( i, 1 ); } } } /** * Filter the data table based on user input and draw the table * @param {object} settings dataTables settings object * @param {string} input string to filter on * @param {int} force optional - force a research of the master array (1) or not (undefined or 0) * @param {bool} regex treat as a regular expression or not * @param {bool} smart perform smart filtering or not * @param {bool} caseInsensitive Do case insenstive matching or not * @memberof DataTable#oApi */ function _fnFilter( settings, input, force, regex, smart, caseInsensitive ) { var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive ); var prevSearch = settings.oPreviousSearch.sSearch; var displayMaster = settings.aiDisplayMaster; var display, invalidated, i; // Need to take account of custom filtering functions - always filter if ( DataTable.ext.search.length !== 0 ) { force = true; } // Check if any of the rows were invalidated invalidated = _fnFilterData( settings ); // If the input is blank - we just want the full data set if ( input.length <= 0 ) { settings.aiDisplay = displayMaster.slice(); } else { // New search - start from the master array if ( invalidated || force || prevSearch.length > input.length || input.indexOf(prevSearch) !== 0 || settings.bSorted // On resort, the display master needs to be // re-filtered since indexes will have changed ) { settings.aiDisplay = displayMaster.slice(); } // Search the display array display = settings.aiDisplay; for ( i=display.length-1 ; i>=0 ; i-- ) { if ( ! rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) { display.splice( i, 1 ); } } } } /** * Build a regular expression object suitable for searching a table * @param {string} sSearch string to search for * @param {bool} bRegex treat as a regular expression or not * @param {bool} bSmart perform smart filtering or not * @param {bool} bCaseInsensitive Do case insensitive matching or not * @returns {RegExp} constructed object * @memberof DataTable#oApi */ function _fnFilterCreateSearch( search, regex, smart, caseInsensitive ) { search = regex ? search : _fnEscapeRegex( search ); if ( smart ) { /* For smart filtering we want to allow the search to work regardless of * word order. We also want double quoted text to be preserved, so word * order is important - a la google. So this is what we want to * generate: * * ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$ */ var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || '', function ( word ) { if ( word.charAt(0) === '"' ) { var m = word.match( /^"(.*)"$/ ); word = m ? m[1] : word; } return word.replace('"', ''); } ); search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$'; } return new RegExp( search, caseInsensitive ? 'i' : '' ); } /** * Escape a string such that it can be used in a regular expression * @param {string} sVal string to escape * @returns {string} escaped string * @memberof DataTable#oApi */ function _fnEscapeRegex ( sVal ) { return sVal.replace( _re_escape_regex, '\\$1' ); } var __filter_div = $('<div>')[0]; var __filter_div_textContent = __filter_div.textContent !== undefined; // Update the filtering data for each row if needed (by invalidation or first run) function _fnFilterData ( settings ) { var columns = settings.aoColumns; var column; var i, j, ien, jen, filterData, cellData, row; var fomatters = DataTable.ext.type.search; var wasInvalidated = false; for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) { row = settings.aoData[i]; if ( ! row._aFilterData ) { filterData = []; for ( j=0, jen=columns.length ; j<jen ; j++ ) { column = columns[j]; if ( column.bSearchable ) { cellData = _fnGetCellData( settings, i, j, 'filter' ); if ( fomatters[ column.sType ] ) { cellData = fomatters[ column.sType ]( cellData ); } // Search in DataTables 1.10 is string based. In 1.11 this // should be altered to also allow strict type checking. if ( cellData === null ) { cellData = ''; } if ( typeof cellData !== 'string' && cellData.toString ) { cellData = cellData.toString(); } } else { cellData = ''; } // If it looks like there is an HTML entity in the string, // attempt to decode it so sorting works as expected. Note that // we could use a single line of jQuery to do this, but the DOM // method used here is much faster http://jsperf.com/html-decode if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) { __filter_div.innerHTML = cellData; cellData = __filter_div_textContent ? __filter_div.textContent : __filter_div.innerText; } if ( cellData.replace ) { cellData = cellData.replace(/[\r\n]/g, ''); } filterData.push( cellData ); } row._aFilterData = filterData; row._sFilterRow = filterData.join(' '); wasInvalidated = true; } } return wasInvalidated; } /** * Convert from the internal Hungarian notation to camelCase for external * interaction * @param {object} obj Object to convert * @returns {object} Inverted object * @memberof DataTable#oApi */ function _fnSearchToCamel ( obj ) { return { search: obj.sSearch, smart: obj.bSmart, regex: obj.bRegex, caseInsensitive: obj.bCaseInsensitive }; } /** * Convert from camelCase notation to the internal Hungarian. We could use the * Hungarian convert function here, but this is cleaner * @param {object} obj Object to convert * @returns {object} Inverted object * @memberof DataTable#oApi */ function _fnSearchToHung ( obj ) { return { sSearch: obj.search, bSmart: obj.smart, bRegex: obj.regex, bCaseInsensitive: obj.caseInsensitive }; } /** * Generate the node required for the info display * @param {object} oSettings dataTables settings object * @returns {node} Information element * @memberof DataTable#oApi */ function _fnFeatureHtmlInfo ( settings ) { var tid = settings.sTableId, nodes = settings.aanFeatures.i, n = $('<div/>', { 'class': settings.oClasses.sInfo, 'id': ! nodes ? tid+'_info' : null } ); if ( ! nodes ) { // Update display on each draw settings.aoDrawCallback.push( { "fn": _fnUpdateInfo, "sName": "information" } ); n .attr( 'role', 'status' ) .attr( 'aria-live', 'polite' ); // Table is described by our info div $(settings.nTable).attr( 'aria-describedby', tid+'_info' ); } return n[0]; } /** * Update the information elements in the display * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnUpdateInfo ( settings ) { /* Show information about the table */ var nodes = settings.aanFeatures.i; if ( nodes.length === 0 ) { return; } var lang = settings.oLanguage, start = settings._iDisplayStart+1, end = settings.fnDisplayEnd(), max = settings.fnRecordsTotal(), total = settings.fnRecordsDisplay(), out = total ? lang.sInfo : lang.sInfoEmpty; if ( total !== max ) { /* Record set after filtering */ out += ' ' + lang.sInfoFiltered; } // Convert the macros out += lang.sInfoPostFix; out = _fnInfoMacros( settings, out ); var callback = lang.fnInfoCallback; if ( callback !== null ) { out = callback.call( settings.oInstance, settings, start, end, max, total, out ); } $(nodes).html( out ); } function _fnInfoMacros ( settings, str ) { // When infinite scrolling, we are always starting at 1. _iDisplayStart is used only // internally var formatter = settings.fnFormatNumber, start = settings._iDisplayStart+1, len = settings._iDisplayLength, vis = settings.fnRecordsDisplay(), all = len === -1; return str. replace(/_START_/g, formatter.call( settings, start ) ). replace(/_END_/g, formatter.call( settings, settings.fnDisplayEnd() ) ). replace(/_MAX_/g, formatter.call( settings, settings.fnRecordsTotal() ) ). replace(/_TOTAL_/g, formatter.call( settings, vis ) ). replace(/_PAGE_/g, formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ). replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) ); } /** * Draw the table for the first time, adding all required features * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnInitialise ( settings ) { var i, iLen, iAjaxStart=settings.iInitDisplayStart; var columns = settings.aoColumns, column; var features = settings.oFeatures; /* Ensure that the table data is fully initialised */ if ( ! settings.bInitialised ) { setTimeout( function(){ _fnInitialise( settings ); }, 200 ); return; } /* Show the display HTML options */ _fnAddOptionsHtml( settings ); /* Build and draw the header / footer for the table */ _fnBuildHead( settings ); _fnDrawHead( settings, settings.aoHeader ); _fnDrawHead( settings, settings.aoFooter ); /* Okay to show that something is going on now */ _fnProcessingDisplay( settings, true ); /* Calculate sizes for columns */ if ( features.bAutoWidth ) { _fnCalculateColumnWidths( settings ); } for ( i=0, iLen=columns.length ; i<iLen ; i++ ) { column = columns[i]; if ( column.sWidth ) { column.nTh.style.width = _fnStringToCss( column.sWidth ); } } // If there is default sorting required - let's do it. The sort function // will do the drawing for us. Otherwise we draw the table regardless of the // Ajax source - this allows the table to look initialised for Ajax sourcing // data (show 'loading' message possibly) _fnReDraw( settings ); // Server-side processing init complete is done by _fnAjaxUpdateDraw var dataSrc = _fnDataSource( settings ); if ( dataSrc != 'ssp' ) { // if there is an ajax source load the data if ( dataSrc == 'ajax' ) { _fnBuildAjax( settings, [], function(json) { var aData = _fnAjaxDataSrc( settings, json ); // Got the data - add it to the table for ( i=0 ; i<aData.length ; i++ ) { _fnAddData( settings, aData[i] ); } // Reset the init display for cookie saving. We've already done // a filter, and therefore cleared it before. So we need to make // it appear 'fresh' settings.iInitDisplayStart = iAjaxStart; _fnReDraw( settings ); _fnProcessingDisplay( settings, false ); _fnInitComplete( settings, json ); }, settings ); } else { _fnProcessingDisplay( settings, false ); _fnInitComplete( settings ); } } } /** * Draw the table for the first time, adding all required features * @param {object} oSettings dataTables settings object * @param {object} [json] JSON from the server that completed the table, if using Ajax source * with client-side processing (optional) * @memberof DataTable#oApi */ function _fnInitComplete ( settings, json ) { settings._bInitComplete = true; // On an Ajax load we now have data and therefore want to apply the column // sizing if ( json ) { _fnAdjustColumnSizing( settings ); } _fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] ); } function _fnLengthChange ( settings, val ) { var len = parseInt( val, 10 ); settings._iDisplayLength = len; _fnLengthOverflow( settings ); // Fire length change event _fnCallbackFire( settings, null, 'length', [settings, len] ); } /** * Generate the node required for user display length changing * @param {object} settings dataTables settings object * @returns {node} Display length feature node * @memberof DataTable#oApi */ function _fnFeatureHtmlLength ( settings ) { var classes = settings.oClasses, tableId = settings.sTableId, menu = settings.aLengthMenu, d2 = $.isArray( menu[0] ), lengths = d2 ? menu[0] : menu, language = d2 ? menu[1] : menu; var select = $('<select/>', { 'name': tableId+'_length', 'aria-controls': tableId, 'class': classes.sLengthSelect } ); for ( var i=0, ien=lengths.length ; i<ien ; i++ ) { select[0][ i ] = new Option( language[i], lengths[i] ); } var div = $('<div><label/></div>').addClass( classes.sLength ); if ( ! settings.aanFeatures.l ) { div[0].id = tableId+'_length'; } div.children().append( settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML ) ); // Can't use `select` variable as user might provide their own and the // reference is broken by the use of outerHTML $('select', div) .val( settings._iDisplayLength ) .bind( 'change.DT', function(e) { _fnLengthChange( settings, $(this).val() ); _fnDraw( settings ); } ); // Update node value whenever anything changes the table's length $(settings.nTable).bind( 'length.dt.DT', function (e, s, len) { if ( settings === s ) { $('select', div).val( len ); } } ); return div[0]; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Note that most of the paging logic is done in * DataTable.ext.pager */ /** * Generate the node required for default pagination * @param {object} oSettings dataTables settings object * @returns {node} Pagination feature node * @memberof DataTable#oApi */ function _fnFeatureHtmlPaginate ( settings ) { var type = settings.sPaginationType, plugin = DataTable.ext.pager[ type ], modern = typeof plugin === 'function', redraw = function( settings ) { _fnDraw( settings ); }, node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0], features = settings.aanFeatures; if ( ! modern ) { plugin.fnInit( settings, node, redraw ); } /* Add a draw callback for the pagination on first instance, to update the paging display */ if ( ! features.p ) { node.id = settings.sTableId+'_paginate'; settings.aoDrawCallback.push( { "fn": function( settings ) { if ( modern ) { var start = settings._iDisplayStart, len = settings._iDisplayLength, visRecords = settings.fnRecordsDisplay(), all = len === -1, page = all ? 0 : Math.ceil( start / len ), pages = all ? 1 : Math.ceil( visRecords / len ), buttons = plugin(page, pages), i, ien; for ( i=0, ien=features.p.length ; i<ien ; i++ ) { _fnRenderer( settings, 'pageButton' )( settings, features.p[i], i, buttons, page, pages ); } } else { plugin.fnUpdate( settings, redraw ); } }, "sName": "pagination" } ); } return node; } /** * Alter the display settings to change the page * @param {object} settings DataTables settings object * @param {string|int} action Paging action to take: "first", "previous", * "next" or "last" or page number to jump to (integer) * @param [bool] redraw Automatically draw the update or not * @returns {bool} true page has changed, false - no change * @memberof DataTable#oApi */ function _fnPageChange ( settings, action, redraw ) { var start = settings._iDisplayStart, len = settings._iDisplayLength, records = settings.fnRecordsDisplay(); if ( records === 0 || len === -1 ) { start = 0; } else if ( typeof action === "number" ) { start = action * len; if ( start > records ) { start = 0; } } else if ( action == "first" ) { start = 0; } else if ( action == "previous" ) { start = len >= 0 ? start - len : 0; if ( start < 0 ) { start = 0; } } else if ( action == "next" ) { if ( start + len < records ) { start += len; } } else if ( action == "last" ) { start = Math.floor( (records-1) / len) * len; } else { _fnLog( settings, 0, "Unknown paging action: "+action, 5 ); } var changed = settings._iDisplayStart !== start; settings._iDisplayStart = start; if ( changed ) { _fnCallbackFire( settings, null, 'page', [settings] ); if ( redraw ) { _fnDraw( settings ); } } return changed; } /** * Generate the node required for the processing node * @param {object} settings dataTables settings object * @returns {node} Processing element * @memberof DataTable#oApi */ function _fnFeatureHtmlProcessing ( settings ) { return $('<div/>', { 'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null, 'class': settings.oClasses.sProcessing } ) .html( settings.oLanguage.sProcessing ) .insertBefore( settings.nTable )[0]; } /** * Display or hide the processing indicator * @param {object} settings dataTables settings object * @param {bool} show Show the processing indicator (true) or not (false) * @memberof DataTable#oApi */ function _fnProcessingDisplay ( settings, show ) { if ( settings.oFeatures.bProcessing ) { $(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' ); } _fnCallbackFire( settings, null, 'processing', [settings, show] ); } /** * Add any control elements for the table - specifically scrolling * @param {object} settings dataTables settings object * @returns {node} Node to add to the DOM * @memberof DataTable#oApi */ function _fnFeatureHtmlTable ( settings ) { var table = $(settings.nTable); // Add the ARIA grid role to the table table.attr( 'role', 'grid' ); // Scrolling from here on in var scroll = settings.oScroll; if ( scroll.sX === '' && scroll.sY === '' ) { return settings.nTable; } var scrollX = scroll.sX; var scrollY = scroll.sY; var classes = settings.oClasses; var caption = table.children('caption'); var captionSide = caption.length ? caption[0]._captionSide : null; var headerClone = $( table[0].cloneNode(false) ); var footerClone = $( table[0].cloneNode(false) ); var footer = table.children('tfoot'); var _div = '<div/>'; var size = function ( s ) { return !s ? null : _fnStringToCss( s ); }; // This is fairly messy, but with x scrolling enabled, if the table has a // width attribute, regardless of any width applied using the column width // options, the browser will shrink or grow the table as needed to fit into // that 100%. That would make the width options useless. So we remove it. // This is okay, under the assumption that width:100% is applied to the // table in CSS (it is in the default stylesheet) which will set the table // width as appropriate (the attribute and css behave differently...) if ( scroll.sX && table.attr('width') === '100%' ) { table.removeAttr('width'); } if ( ! footer.length ) { footer = null; } /* * The HTML structure that we want to generate in this function is: * div - scroller * div - scroll head * div - scroll head inner * table - scroll head table * thead - thead * div - scroll body * table - table (master table) * thead - thead clone for sizing * tbody - tbody * div - scroll foot * div - scroll foot inner * table - scroll foot table * tfoot - tfoot */ var scroller = $( _div, { 'class': classes.sScrollWrapper } ) .append( $(_div, { 'class': classes.sScrollHead } ) .css( { overflow: 'hidden', position: 'relative', border: 0, width: scrollX ? size(scrollX) : '100%' } ) .append( $(_div, { 'class': classes.sScrollHeadInner } ) .css( { 'box-sizing': 'content-box', width: scroll.sXInner || '100%' } ) .append( headerClone .removeAttr('id') .css( 'margin-left', 0 ) .append( captionSide === 'top' ? caption : null ) .append( table.children('thead') ) ) ) ) .append( $(_div, { 'class': classes.sScrollBody } ) .css( { overflow: 'auto', height: size( scrollY ), width: size( scrollX ) } ) .append( table ) ); if ( footer ) { scroller.append( $(_div, { 'class': classes.sScrollFoot } ) .css( { overflow: 'hidden', border: 0, width: scrollX ? size(scrollX) : '100%' } ) .append( $(_div, { 'class': classes.sScrollFootInner } ) .append( footerClone .removeAttr('id') .css( 'margin-left', 0 ) .append( captionSide === 'bottom' ? caption : null ) .append( table.children('tfoot') ) ) ) ); } var children = scroller.children(); var scrollHead = children[0]; var scrollBody = children[1]; var scrollFoot = footer ? children[2] : null; // When the body is scrolled, then we also want to scroll the headers if ( scrollX ) { $(scrollBody).scroll( function (e) { var scrollLeft = this.scrollLeft; scrollHead.scrollLeft = scrollLeft; if ( footer ) { scrollFoot.scrollLeft = scrollLeft; } } ); } settings.nScrollHead = scrollHead; settings.nScrollBody = scrollBody; settings.nScrollFoot = scrollFoot; // On redraw - align columns settings.aoDrawCallback.push( { "fn": _fnScrollDraw, "sName": "scrolling" } ); return scroller[0]; } /** * Update the header, footer and body tables for resizing - i.e. column * alignment. * * Welcome to the most horrible function DataTables. The process that this * function follows is basically: * 1. Re-create the table inside the scrolling div * 2. Take live measurements from the DOM * 3. Apply the measurements to align the columns * 4. Clean up * * @param {object} settings dataTables settings object * @memberof DataTable#oApi */ function _fnScrollDraw ( settings ) { // Given that this is such a monster function, a lot of variables are use // to try and keep the minimised size as small as possible var scroll = settings.oScroll, scrollX = scroll.sX, scrollXInner = scroll.sXInner, scrollY = scroll.sY, barWidth = scroll.iBarWidth, divHeader = $(settings.nScrollHead), divHeaderStyle = divHeader[0].style, divHeaderInner = divHeader.children('div'), divHeaderInnerStyle = divHeaderInner[0].style, divHeaderTable = divHeaderInner.children('table'), divBodyEl = settings.nScrollBody, divBody = $(divBodyEl), divBodyStyle = divBodyEl.style, divFooter = $(settings.nScrollFoot), divFooterInner = divFooter.children('div'), divFooterTable = divFooterInner.children('table'), header = $(settings.nTHead), table = $(settings.nTable), tableEl = table[0], tableStyle = tableEl.style, footer = settings.nTFoot ? $(settings.nTFoot) : null, browser = settings.oBrowser, ie67 = browser.bScrollOversize, headerTrgEls, footerTrgEls, headerSrcEls, footerSrcEls, headerCopy, footerCopy, headerWidths=[], footerWidths=[], headerContent=[], idx, correction, sanityWidth, zeroOut = function(nSizer) { var style = nSizer.style; style.paddingTop = "0"; style.paddingBottom = "0"; style.borderTopWidth = "0"; style.borderBottomWidth = "0"; style.height = 0; }; /* * 1. Re-create the table inside the scrolling div */ // Remove the old minimised thead and tfoot elements in the inner table table.children('thead, tfoot').remove(); // Clone the current header and footer elements and then place it into the inner table headerCopy = header.clone().prependTo( table ); headerTrgEls = header.find('tr'); // original header is in its own table headerSrcEls = headerCopy.find('tr'); headerCopy.find('th, td').removeAttr('tabindex'); if ( footer ) { footerCopy = footer.clone().prependTo( table ); footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized footerSrcEls = footerCopy.find('tr'); } /* * 2. Take live measurements from the DOM - do not alter the DOM itself! */ // Remove old sizing and apply the calculated column widths // Get the unique column headers in the newly created (cloned) header. We want to apply the // calculated sizes to this header if ( ! scrollX ) { divBodyStyle.width = '100%'; divHeader[0].style.width = '100%'; } $.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) { idx = _fnVisibleToColumnIndex( settings, i ); el.style.width = settings.aoColumns[idx].sWidth; } ); if ( footer ) { _fnApplyToChildren( function(n) { n.style.width = ""; }, footerSrcEls ); } // If scroll collapse is enabled, when we put the headers back into the body for sizing, we // will end up forcing the scrollbar to appear, making our measurements wrong for when we // then hide it (end of this function), so add the header height to the body scroller. if ( scroll.bCollapse && scrollY !== "" ) { divBodyStyle.height = (divBody[0].offsetHeight + header[0].offsetHeight)+"px"; } // Size the table as a whole sanityWidth = table.outerWidth(); if ( scrollX === "" ) { // No x scrolling tableStyle.width = "100%"; // IE7 will make the width of the table when 100% include the scrollbar // - which is shouldn't. When there is a scrollbar we need to take this // into account. if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll") ) { tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth); } } else { // x scrolling if ( scrollXInner !== "" ) { // x scroll inner has been given - use it tableStyle.width = _fnStringToCss(scrollXInner); } else if ( sanityWidth == divBody.width() && divBody.height() < table.height() ) { // There is y-scrolling - try to take account of the y scroll bar tableStyle.width = _fnStringToCss( sanityWidth-barWidth ); if ( table.outerWidth() > sanityWidth-barWidth ) { // Not possible to take account of it tableStyle.width = _fnStringToCss( sanityWidth ); } } else { // When all else fails tableStyle.width = _fnStringToCss( sanityWidth ); } } // Recalculate the sanity width - now that we've applied the required width, // before it was a temporary variable. This is required because the column // width calculation is done before this table DOM is created. sanityWidth = table.outerWidth(); // Hidden header should have zero height, so remove padding and borders. Then // set the width based on the real headers // Apply all styles in one pass _fnApplyToChildren( zeroOut, headerSrcEls ); // Read all widths in next pass _fnApplyToChildren( function(nSizer) { headerContent.push( nSizer.innerHTML ); headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) ); }, headerSrcEls ); // Apply all widths in final pass _fnApplyToChildren( function(nToSize, i) { nToSize.style.width = headerWidths[i]; }, headerTrgEls ); $(headerSrcEls).height(0); /* Same again with the footer if we have one */ if ( footer ) { _fnApplyToChildren( zeroOut, footerSrcEls ); _fnApplyToChildren( function(nSizer) { footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) ); }, footerSrcEls ); _fnApplyToChildren( function(nToSize, i) { nToSize.style.width = footerWidths[i]; }, footerTrgEls ); $(footerSrcEls).height(0); } /* * 3. Apply the measurements */ // "Hide" the header and footer that we used for the sizing. We need to keep // the content of the cell so that the width applied to the header and body // both match, but we want to hide it completely. We want to also fix their // width to what they currently are _fnApplyToChildren( function(nSizer, i) { nSizer.innerHTML = '<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+headerContent[i]+'</div>'; nSizer.style.width = headerWidths[i]; }, headerSrcEls ); if ( footer ) { _fnApplyToChildren( function(nSizer, i) { nSizer.innerHTML = ""; nSizer.style.width = footerWidths[i]; }, footerSrcEls ); } // Sanity check that the table is of a sensible width. If not then we are going to get // misalignment - try to prevent this by not allowing the table to shrink below its min width if ( table.outerWidth() < sanityWidth ) { // The min width depends upon if we have a vertical scrollbar visible or not */ correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")) ? sanityWidth+barWidth : sanityWidth; // IE6/7 are a law unto themselves... if ( ie67 && (divBodyEl.scrollHeight > divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll") ) { tableStyle.width = _fnStringToCss( correction-barWidth ); } // And give the user a warning that we've stopped the table getting too small if ( scrollX === "" || scrollXInner !== "" ) { _fnLog( settings, 1, 'Possible column misalignment', 6 ); } } else { correction = '100%'; } // Apply to the container elements divBodyStyle.width = _fnStringToCss( correction ); divHeaderStyle.width = _fnStringToCss( correction ); if ( footer ) { settings.nScrollFoot.style.width = _fnStringToCss( correction ); } /* * 4. Clean up */ if ( ! scrollY ) { /* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting * the scrollbar height from the visible display, rather than adding it on. We need to * set the height in order to sort this. Don't want to do it in any other browsers. */ if ( ie67 ) { divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth ); } } if ( scrollY && scroll.bCollapse ) { divBodyStyle.height = _fnStringToCss( scrollY ); var iExtra = (scrollX && tableEl.offsetWidth > divBodyEl.offsetWidth) ? barWidth : 0; if ( tableEl.offsetHeight < divBodyEl.offsetHeight ) { divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+iExtra ); } } /* Finally set the width's of the header and footer tables */ var iOuterWidth = table.outerWidth(); divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth ); divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth ); // Figure out if there are scrollbar present - if so then we need a the header and footer to // provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar) var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll"; var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' ); divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px"; if ( footer ) { divFooterTable[0].style.width = _fnStringToCss( iOuterWidth ); divFooterInner[0].style.width = _fnStringToCss( iOuterWidth ); divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px"; } /* Adjust the position of the header in case we loose the y-scrollbar */ divBody.scroll(); // If sorting or filtering has occurred, jump the scrolling back to the top // only if we aren't holding the position if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) { divBodyEl.scrollTop = 0; } } /** * Apply a given function to the display child nodes of an element array (typically * TD children of TR rows * @param {function} fn Method to apply to the objects * @param array {nodes} an1 List of elements to look through for display children * @param array {nodes} an2 Another list (identical structure to the first) - optional * @memberof DataTable#oApi */ function _fnApplyToChildren( fn, an1, an2 ) { var index=0, i=0, iLen=an1.length; var nNode1, nNode2; while ( i < iLen ) { nNode1 = an1[i].firstChild; nNode2 = an2 ? an2[i].firstChild : null; while ( nNode1 ) { if ( nNode1.nodeType === 1 ) { if ( an2 ) { fn( nNode1, nNode2, index ); } else { fn( nNode1, index ); } index++; } nNode1 = nNode1.nextSibling; nNode2 = an2 ? nNode2.nextSibling : null; } i++; } } var __re_html_remove = /<.*?>/g; /** * Calculate the width of columns for the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnCalculateColumnWidths ( oSettings ) { var table = oSettings.nTable, columns = oSettings.aoColumns, scroll = oSettings.oScroll, scrollY = scroll.sY, scrollX = scroll.sX, scrollXInner = scroll.sXInner, columnCount = columns.length, visibleColumns = _fnGetColumns( oSettings, 'bVisible' ), headerCells = $('th', oSettings.nTHead), tableWidthAttr = table.getAttribute('width'), tableContainer = table.parentNode, userInputs = false, i, column, columnIdx, width, outerWidth; /* Convert any user input sizes into pixel sizes */ for ( i=0 ; i<visibleColumns.length ; i++ ) { column = columns[ visibleColumns[i] ]; if ( column.sWidth !== null ) { column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer ); userInputs = true; } } /* If the number of columns in the DOM equals the number that we have to * process in DataTables, then we can use the offsets that are created by * the web- browser. No custom sizes can be set in order for this to happen, * nor scrolling used */ if ( ! userInputs && ! scrollX && ! scrollY && columnCount == _fnVisbleColumns( oSettings ) && columnCount == headerCells.length ) { for ( i=0 ; i<columnCount ; i++ ) { columns[i].sWidth = _fnStringToCss( headerCells.eq(i).width() ); } } else { // Otherwise construct a single row table with the widest node in the // data, assign any user defined widths, then insert it into the DOM and // allow the browser to do all the hard work of calculating table widths var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table .empty() .css( 'visibility', 'hidden' ) .removeAttr( 'id' ) .append( $(oSettings.nTHead).clone( false ) ) .append( $(oSettings.nTFoot).clone( false ) ) .append( $('<tbody><tr/></tbody>') ); // Remove any assigned widths from the footer (from scrolling) tmpTable.find('tfoot th, tfoot td').css('width', ''); var tr = tmpTable.find( 'tbody tr' ); // Apply custom sizing to the cloned header headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] ); for ( i=0 ; i<visibleColumns.length ; i++ ) { column = columns[ visibleColumns[i] ]; headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ? _fnStringToCss( column.sWidthOrig ) : ''; } // Find the widest cell for each column and put it into the table if ( oSettings.aoData.length ) { for ( i=0 ; i<visibleColumns.length ; i++ ) { columnIdx = visibleColumns[i]; column = columns[ columnIdx ]; $( _fnGetWidestNode( oSettings, columnIdx ) ) .clone( false ) .append( column.sContentPadding ) .appendTo( tr ); } } // Table has been built, attach to the document so we can work with it tmpTable.appendTo( tableContainer ); // When scrolling (X or Y) we want to set the width of the table as // appropriate. However, when not scrolling leave the table width as it // is. This results in slightly different, but I think correct behaviour if ( scrollX && scrollXInner ) { tmpTable.width( scrollXInner ); } else if ( scrollX ) { tmpTable.css( 'width', 'auto' ); if ( tmpTable.width() < tableContainer.offsetWidth ) { tmpTable.width( tableContainer.offsetWidth ); } } else if ( scrollY ) { tmpTable.width( tableContainer.offsetWidth ); } else if ( tableWidthAttr ) { tmpTable.width( tableWidthAttr ); } // Take into account the y scrollbar _fnScrollingWidthAdjust( oSettings, tmpTable[0] ); // Browsers need a bit of a hand when a width is assigned to any columns // when x-scrolling as they tend to collapse the table to the min-width, // even if we sent the column widths. So we need to keep track of what // the table width should be by summing the user given values, and the // automatic values if ( scrollX ) { var total = 0; for ( i=0 ; i<visibleColumns.length ; i++ ) { column = columns[ visibleColumns[i] ]; outerWidth = $(headerCells[i]).outerWidth(); total += column.sWidthOrig === null ? outerWidth : parseInt( column.sWidth, 10 ) + outerWidth - $(headerCells[i]).width(); } tmpTable.width( _fnStringToCss( total ) ); table.style.width = _fnStringToCss( total ); } // Get the width of each column in the constructed table for ( i=0 ; i<visibleColumns.length ; i++ ) { column = columns[ visibleColumns[i] ]; width = $(headerCells[i]).width(); if ( width ) { column.sWidth = _fnStringToCss( width ); } } table.style.width = _fnStringToCss( tmpTable.css('width') ); // Finished with the table - ditch it tmpTable.remove(); } // If there is a width attr, we want to attach an event listener which // allows the table sizing to automatically adjust when the window is // resized. Use the width attr rather than CSS, since we can't know if the // CSS is a relative value or absolute - DOM read is always px. if ( tableWidthAttr ) { table.style.width = _fnStringToCss( tableWidthAttr ); } if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) { $(window).bind('resize.DT-'+oSettings.sInstance, _fnThrottle( function () { _fnAdjustColumnSizing( oSettings ); } ) ); oSettings._reszEvt = true; } } /** * Throttle the calls to a function. Arguments and context are maintained for * the throttled function * @param {function} fn Function to be called * @param {int} [freq=200] call frequency in mS * @returns {function} wrapped function * @memberof DataTable#oApi */ function _fnThrottle( fn, freq ) { var frequency = freq !== undefined ? freq : 200, last, timer; return function () { var that = this, now = +new Date(), args = arguments; if ( last && now < last + frequency ) { clearTimeout( timer ); timer = setTimeout( function () { last = undefined; fn.apply( that, args ); }, frequency ); } else if ( last ) { last = now; fn.apply( that, args ); } else { last = now; } }; } /** * Convert a CSS unit width to pixels (e.g. 2em) * @param {string} width width to be converted * @param {node} parent parent to get the with for (required for relative widths) - optional * @returns {int} width in pixels * @memberof DataTable#oApi */ function _fnConvertToWidth ( width, parent ) { if ( ! width ) { return 0; } var n = $('<div/>') .css( 'width', _fnStringToCss( width ) ) .appendTo( parent || document.body ); var val = n[0].offsetWidth; n.remove(); return val; } /** * Adjust a table's width to take account of vertical scroll bar * @param {object} oSettings dataTables settings object * @param {node} n table node * @memberof DataTable#oApi */ function _fnScrollingWidthAdjust ( settings, n ) { var scroll = settings.oScroll; if ( scroll.sX || scroll.sY ) { // When y-scrolling only, we want to remove the width of the scroll bar // so the table + scroll bar will fit into the area available, otherwise // we fix the table at its current size with no adjustment var correction = ! scroll.sX ? scroll.iBarWidth : 0; n.style.width = _fnStringToCss( $(n).outerWidth() - correction ); } } /** * Get the widest node * @param {object} settings dataTables settings object * @param {int} colIdx column of interest * @returns {node} widest table node * @memberof DataTable#oApi */ function _fnGetWidestNode( settings, colIdx ) { var idx = _fnGetMaxLenString( settings, colIdx ); if ( idx < 0 ) { return null; } var data = settings.aoData[ idx ]; return ! data.nTr ? // Might not have been created when deferred rendering $('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] : data.anCells[ colIdx ]; } /** * Get the maximum strlen for each data column * @param {object} settings dataTables settings object * @param {int} colIdx column of interest * @returns {string} max string length for each column * @memberof DataTable#oApi */ function _fnGetMaxLenString( settings, colIdx ) { var s, max=-1, maxIdx = -1; for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) { s = _fnGetCellData( settings, i, colIdx, 'display' )+''; s = s.replace( __re_html_remove, '' ); if ( s.length > max ) { max = s.length; maxIdx = i; } } return maxIdx; } /** * Append a CSS unit (only if required) to a string * @param {string} value to css-ify * @returns {string} value with css unit * @memberof DataTable#oApi */ function _fnStringToCss( s ) { if ( s === null ) { return '0px'; } if ( typeof s == 'number' ) { return s < 0 ? '0px' : s+'px'; } // Check it has a unit character already return s.match(/\d$/) ? s+'px' : s; } /** * Get the width of a scroll bar in this browser being used * @returns {int} width in pixels * @memberof DataTable#oApi */ function _fnScrollBarWidth () { // On first run a static variable is set, since this is only needed once. // Subsequent runs will just use the previously calculated value if ( ! DataTable.__scrollbarWidth ) { var inner = $('<p/>').css( { width: '100%', height: 200, padding: 0 } )[0]; var outer = $('<div/>') .css( { position: 'absolute', top: 0, left: 0, width: 200, height: 150, padding: 0, overflow: 'hidden', visibility: 'hidden' } ) .append( inner ) .appendTo( 'body' ); var w1 = inner.offsetWidth; outer.css( 'overflow', 'scroll' ); var w2 = inner.offsetWidth; if ( w1 === w2 ) { w2 = outer[0].clientWidth; } outer.remove(); DataTable.__scrollbarWidth = w1 - w2; } return DataTable.__scrollbarWidth; } function _fnSortFlatten ( settings ) { var i, iLen, k, kLen, aSort = [], aiOrig = [], aoColumns = settings.aoColumns, aDataSort, iCol, sType, srcCol, fixed = settings.aaSortingFixed, fixedObj = $.isPlainObject( fixed ), nestedSort = [], add = function ( a ) { if ( a.length && ! $.isArray( a[0] ) ) { // 1D array nestedSort.push( a ); } else { // 2D array nestedSort.push.apply( nestedSort, a ); } }; // Build the sort array, with pre-fix and post-fix options if they have been // specified if ( $.isArray( fixed ) ) { add( fixed ); } if ( fixedObj && fixed.pre ) { add( fixed.pre ); } add( settings.aaSorting ); if (fixedObj && fixed.post ) { add( fixed.post ); } for ( i=0 ; i<nestedSort.length ; i++ ) { srcCol = nestedSort[i][0]; aDataSort = aoColumns[ srcCol ].aDataSort; for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ ) { iCol = aDataSort[k]; sType = aoColumns[ iCol ].sType || 'string'; if ( nestedSort[i]._idx === undefined ) { nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting ); } aSort.push( { src: srcCol, col: iCol, dir: nestedSort[i][1], index: nestedSort[i]._idx, type: sType, formatter: DataTable.ext.type.order[ sType+"-pre" ] } ); } } return aSort; } /** * Change the order of the table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi * @todo This really needs split up! */ function _fnSort ( oSettings ) { var i, ien, iLen, j, jLen, k, kLen, sDataType, nTh, aiOrig = [], oExtSort = DataTable.ext.type.order, aoData = oSettings.aoData, aoColumns = oSettings.aoColumns, aDataSort, data, iCol, sType, oSort, formatters = 0, sortCol, displayMaster = oSettings.aiDisplayMaster, aSort; // Resolve any column types that are unknown due to addition or invalidation // @todo Can this be moved into a 'data-ready' handler which is called when // data is going to be used in the table? _fnColumnTypes( oSettings ); aSort = _fnSortFlatten( oSettings ); for ( i=0, ien=aSort.length ; i<ien ; i++ ) { sortCol = aSort[i]; // Track if we can use the fast sort algorithm if ( sortCol.formatter ) { formatters++; } // Load the data needed for the sort, for each cell _fnSortData( oSettings, sortCol.col ); } /* No sorting required if server-side or no sorting array */ if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 ) { // Create a value - key array of the current row positions such that we can use their // current position during the sort, if values match, in order to perform stable sorting for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) { aiOrig[ displayMaster[i] ] = i; } /* Do the sort - here we want multi-column sorting based on a given data source (column) * and sorting function (from oSort) in a certain direction. It's reasonably complex to * follow on it's own, but this is what we want (example two column sorting): * fnLocalSorting = function(a,b){ * var iTest; * iTest = oSort['string-asc']('data11', 'data12'); * if (iTest !== 0) * return iTest; * iTest = oSort['numeric-desc']('data21', 'data22'); * if (iTest !== 0) * return iTest; * return oSort['numeric-asc']( aiOrig[a], aiOrig[b] ); * } * Basically we have a test for each sorting column, if the data in that column is equal, * test the next column. If all columns match, then we use a numeric sort on the row * positions in the original data array to provide a stable sort. * * Note - I know it seems excessive to have two sorting methods, but the first is around * 15% faster, so the second is only maintained for backwards compatibility with sorting * methods which do not have a pre-sort formatting function. */ if ( formatters === aSort.length ) { // All sort types have formatting functions displayMaster.sort( function ( a, b ) { var x, y, k, test, sort, len=aSort.length, dataA = aoData[a]._aSortData, dataB = aoData[b]._aSortData; for ( k=0 ; k<len ; k++ ) { sort = aSort[k]; x = dataA[ sort.col ]; y = dataB[ sort.col ]; test = x<y ? -1 : x>y ? 1 : 0; if ( test !== 0 ) { return sort.dir === 'asc' ? test : -test; } } x = aiOrig[a]; y = aiOrig[b]; return x<y ? -1 : x>y ? 1 : 0; } ); } else { // Depreciated - remove in 1.11 (providing a plug-in option) // Not all sort types have formatting methods, so we have to call their sorting // methods. displayMaster.sort( function ( a, b ) { var x, y, k, l, test, sort, fn, len=aSort.length, dataA = aoData[a]._aSortData, dataB = aoData[b]._aSortData; for ( k=0 ; k<len ; k++ ) { sort = aSort[k]; x = dataA[ sort.col ]; y = dataB[ sort.col ]; fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ]; test = fn( x, y ); if ( test !== 0 ) { return test; } } x = aiOrig[a]; y = aiOrig[b]; return x<y ? -1 : x>y ? 1 : 0; } ); } } /* Tell the draw function that we have sorted the data */ oSettings.bSorted = true; } function _fnSortAria ( settings ) { var label; var nextSort; var columns = settings.aoColumns; var aSort = _fnSortFlatten( settings ); var oAria = settings.oLanguage.oAria; // ARIA attributes - need to loop all columns, to update all (removing old // attributes as needed) for ( var i=0, iLen=columns.length ; i<iLen ; i++ ) { var col = columns[i]; var asSorting = col.asSorting; var sTitle = col.sTitle.replace( /<.*?>/g, "" ); var th = col.nTh; // IE7 is throwing an error when setting these properties with jQuery's // attr() and removeAttr() methods... th.removeAttribute('aria-sort'); /* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */ if ( col.bSortable ) { if ( aSort.length > 0 && aSort[0].col == i ) { th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" ); nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0]; } else { nextSort = asSorting[0]; } label = sTitle + ( nextSort === "asc" ? oAria.sSortAscending : oAria.sSortDescending ); } else { label = sTitle; } th.setAttribute('aria-label', label); } } /** * Function to run on user sort request * @param {object} settings dataTables settings object * @param {node} attachTo node to attach the handler to * @param {int} colIdx column sorting index * @param {boolean} [append=false] Append the requested sort to the existing * sort if true (i.e. multi-column sort) * @param {function} [callback] callback function * @memberof DataTable#oApi */ function _fnSortListener ( settings, colIdx, append, callback ) { var col = settings.aoColumns[ colIdx ]; var sorting = settings.aaSorting; var asSorting = col.asSorting; var nextSortIdx; var next = function ( a, overflow ) { var idx = a._idx; if ( idx === undefined ) { idx = $.inArray( a[1], asSorting ); } return idx+1 < asSorting.length ? idx+1 : overflow ? null : 0; }; // Convert to 2D array if needed if ( typeof sorting[0] === 'number' ) { sorting = settings.aaSorting = [ sorting ]; } // If appending the sort then we are multi-column sorting if ( append && settings.oFeatures.bSortMulti ) { // Are we already doing some kind of sort on this column? var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') ); if ( sortIdx !== -1 ) { // Yes, modify the sort nextSortIdx = next( sorting[sortIdx], true ); if ( nextSortIdx === null ) { sorting.splice( sortIdx, 1 ); } else { sorting[sortIdx][1] = asSorting[ nextSortIdx ]; sorting[sortIdx]._idx = nextSortIdx; } } else { // No sort on this column yet sorting.push( [ colIdx, asSorting[0], 0 ] ); sorting[sorting.length-1]._idx = 0; } } else if ( sorting.length && sorting[0][0] == colIdx ) { // Single column - already sorting on this column, modify the sort nextSortIdx = next( sorting[0] ); sorting.length = 1; sorting[0][1] = asSorting[ nextSortIdx ]; sorting[0]._idx = nextSortIdx; } else { // Single column - sort only on this column sorting.length = 0; sorting.push( [ colIdx, asSorting[0] ] ); sorting[0]._idx = 0; } // Run the sort by calling a full redraw _fnReDraw( settings ); // callback used for async user interaction if ( typeof callback == 'function' ) { callback( settings ); } } /** * Attach a sort handler (click) to a node * @param {object} settings dataTables settings object * @param {node} attachTo node to attach the handler to * @param {int} colIdx column sorting index * @param {function} [callback] callback function * @memberof DataTable#oApi */ function _fnSortAttachListener ( settings, attachTo, colIdx, callback ) { var col = settings.aoColumns[ colIdx ]; _fnBindAction( attachTo, {}, function (e) { /* If the column is not sortable - don't to anything */ if ( col.bSortable === false ) { return; } // If processing is enabled use a timeout to allow the processing // display to be shown - otherwise to it synchronously if ( settings.oFeatures.bProcessing ) { _fnProcessingDisplay( settings, true ); setTimeout( function() { _fnSortListener( settings, colIdx, e.shiftKey, callback ); // In server-side processing, the draw callback will remove the // processing display if ( _fnDataSource( settings ) !== 'ssp' ) { _fnProcessingDisplay( settings, false ); } }, 0 ); } else { _fnSortListener( settings, colIdx, e.shiftKey, callback ); } } ); } /** * Set the sorting classes on table's body, Note: it is safe to call this function * when bSort and bSortClasses are false * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnSortingClasses( settings ) { var oldSort = settings.aLastSort; var sortClass = settings.oClasses.sSortColumn; var sort = _fnSortFlatten( settings ); var features = settings.oFeatures; var i, ien, colIdx; if ( features.bSort && features.bSortClasses ) { // Remove old sorting classes for ( i=0, ien=oldSort.length ; i<ien ; i++ ) { colIdx = oldSort[i].src; // Remove column sorting $( _pluck( settings.aoData, 'anCells', colIdx ) ) .removeClass( sortClass + (i<2 ? i+1 : 3) ); } // Add new column sorting for ( i=0, ien=sort.length ; i<ien ; i++ ) { colIdx = sort[i].src; $( _pluck( settings.aoData, 'anCells', colIdx ) ) .addClass( sortClass + (i<2 ? i+1 : 3) ); } } settings.aLastSort = sort; } // Get the data to sort a column, be it from cache, fresh (populating the // cache), or from a sort formatter function _fnSortData( settings, idx ) { // Custom sorting function - provided by the sort data type var column = settings.aoColumns[ idx ]; var customSort = DataTable.ext.order[ column.sSortDataType ]; var customData; if ( customSort ) { customData = customSort.call( settings.oInstance, settings, idx, _fnColumnIndexToVisible( settings, idx ) ); } // Use / populate cache var row, cellData; var formatter = DataTable.ext.type.order[ column.sType+"-pre" ]; for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) { row = settings.aoData[i]; if ( ! row._aSortData ) { row._aSortData = []; } if ( ! row._aSortData[idx] || customSort ) { cellData = customSort ? customData[i] : // If there was a custom sort function, use data from there _fnGetCellData( settings, i, idx, 'sort' ); row._aSortData[ idx ] = formatter ? formatter( cellData ) : cellData; } } } /** * Save the state of a table * @param {object} oSettings dataTables settings object * @memberof DataTable#oApi */ function _fnSaveState ( settings ) { if ( !settings.oFeatures.bStateSave || settings.bDestroying ) { return; } /* Store the interesting variables */ var state = { time: +new Date(), start: settings._iDisplayStart, length: settings._iDisplayLength, order: $.extend( true, [], settings.aaSorting ), search: _fnSearchToCamel( settings.oPreviousSearch ), columns: $.map( settings.aoColumns, function ( col, i ) { return { visible: col.bVisible, search: _fnSearchToCamel( settings.aoPreSearchCols[i] ) }; } ) }; _fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] ); settings.oSavedState = state; settings.fnStateSaveCallback.call( settings.oInstance, settings, state ); } /** * Attempt to load a saved table state * @param {object} oSettings dataTables settings object * @param {object} oInit DataTables init object so we can override settings * @memberof DataTable#oApi */ function _fnLoadState ( settings, oInit ) { var i, ien; var columns = settings.aoColumns; if ( ! settings.oFeatures.bStateSave ) { return; } var state = settings.fnStateLoadCallback.call( settings.oInstance, settings ); if ( ! state || ! state.time ) { return; } /* Allow custom and plug-in manipulation functions to alter the saved data set and * cancelling of loading by returning false */ var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, state] ); if ( $.inArray( false, abStateLoad ) !== -1 ) { return; } /* Reject old data */ var duration = settings.iStateDuration; if ( duration > 0 && state.time < +new Date() - (duration*1000) ) { return; } // Number of columns have changed - all bets are off, no restore of settings if ( columns.length !== state.columns.length ) { return; } // Store the saved state so it might be accessed at any time settings.oLoadedState = $.extend( true, {}, state ); // Restore key features - todo - for 1.11 this needs to be done by // subscribed events settings._iDisplayStart = state.start; settings.iInitDisplayStart = state.start; settings._iDisplayLength = state.length; settings.aaSorting = []; // Order $.each( state.order, function ( i, col ) { settings.aaSorting.push( col[0] >= columns.length ? [ 0, col[1] ] : col ); } ); // Search $.extend( settings.oPreviousSearch, _fnSearchToHung( state.search ) ); // Columns for ( i=0, ien=state.columns.length ; i<ien ; i++ ) { var col = state.columns[i]; // Visibility columns[i].bVisible = col.visible; // Search $.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) ); } _fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, state] ); } /** * Return the settings object for a particular table * @param {node} table table we are using as a dataTable * @returns {object} Settings object - or null if not found * @memberof DataTable#oApi */ function _fnSettingsFromNode ( table ) { var settings = DataTable.settings; var idx = $.inArray( table, _pluck( settings, 'nTable' ) ); return idx !== -1 ? settings[ idx ] : null; } /** * Log an error message * @param {object} settings dataTables settings object * @param {int} level log error messages, or display them to the user * @param {string} msg error message * @param {int} tn Technical note id to get more information about the error. * @memberof DataTable#oApi */ function _fnLog( settings, level, msg, tn ) { msg = 'DataTables warning: '+ (settings!==null ? 'table id='+settings.sTableId+' - ' : '')+msg; if ( tn ) { msg += '. For more information about this error, please see '+ 'http://datatables.net/tn/'+tn; } if ( ! level ) { // Backwards compatibility pre 1.10 var ext = DataTable.ext; var type = ext.sErrMode || ext.errMode; if ( type == 'alert' ) { alert( msg ); } else { throw new Error(msg); } } else if ( window.console && console.log ) { console.log( msg ); } } /** * See if a property is defined on one object, if so assign it to the other object * @param {object} ret target object * @param {object} src source object * @param {string} name property * @param {string} [mappedName] name to map too - optional, name used if not given * @memberof DataTable#oApi */ function _fnMap( ret, src, name, mappedName ) { if ( $.isArray( name ) ) { $.each( name, function (i, val) { if ( $.isArray( val ) ) { _fnMap( ret, src, val[0], val[1] ); } else { _fnMap( ret, src, val ); } } ); return; } if ( mappedName === undefined ) { mappedName = name; } if ( src[name] !== undefined ) { ret[mappedName] = src[name]; } } /** * Extend objects - very similar to jQuery.extend, but deep copy objects, and * shallow copy arrays. The reason we need to do this, is that we don't want to * deep copy array init values (such as aaSorting) since the dev wouldn't be * able to override them, but we do want to deep copy arrays. * @param {object} out Object to extend * @param {object} extender Object from which the properties will be applied to * out * @param {boolean} breakRefs If true, then arrays will be sliced to take an * independent copy with the exception of the `data` or `aaData` parameters * if they are present. This is so you can pass in a collection to * DataTables and have that used as your data source without breaking the * references * @returns {object} out Reference, just for convenience - out === the return. * @memberof DataTable#oApi * @todo This doesn't take account of arrays inside the deep copied objects. */ function _fnExtend( out, extender, breakRefs ) { var val; for ( var prop in extender ) { if ( extender.hasOwnProperty(prop) ) { val = extender[prop]; if ( $.isPlainObject( val ) ) { if ( ! $.isPlainObject( out[prop] ) ) { out[prop] = {}; } $.extend( true, out[prop], val ); } else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val) ) { out[prop] = val.slice(); } else { out[prop] = val; } } } return out; } /** * Bind an event handers to allow a click or return key to activate the callback. * This is good for accessibility since a return on the keyboard will have the * same effect as a click, if the element has focus. * @param {element} n Element to bind the action to * @param {object} oData Data object to pass to the triggered function * @param {function} fn Callback function for when the event is triggered * @memberof DataTable#oApi */ function _fnBindAction( n, oData, fn ) { $(n) .bind( 'click.DT', oData, function (e) { n.blur(); // Remove focus outline for mouse users fn(e); } ) .bind( 'keypress.DT', oData, function (e){ if ( e.which === 13 ) { e.preventDefault(); fn(e); } } ) .bind( 'selectstart.DT', function () { /* Take the brutal approach to cancelling text selection */ return false; } ); } /** * Register a callback function. Easily allows a callback function to be added to * an array store of callback functions that can then all be called together. * @param {object} oSettings dataTables settings object * @param {string} sStore Name of the array storage for the callbacks in oSettings * @param {function} fn Function to be called back * @param {string} sName Identifying name for the callback (i.e. a label) * @memberof DataTable#oApi */ function _fnCallbackReg( oSettings, sStore, fn, sName ) { if ( fn ) { oSettings[sStore].push( { "fn": fn, "sName": sName } ); } } /** * Fire callback functions and trigger events. Note that the loop over the * callback array store is done backwards! Further note that you do not want to * fire off triggers in time sensitive applications (for example cell creation) * as its slow. * @param {object} settings dataTables settings object * @param {string} callbackArr Name of the array storage for the callbacks in * oSettings * @param {string} event Name of the jQuery custom event to trigger. If null no * trigger is fired * @param {array} args Array of arguments to pass to the callback function / * trigger * @memberof DataTable#oApi */ function _fnCallbackFire( settings, callbackArr, e, args ) { var ret = []; if ( callbackArr ) { ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) { return val.fn.apply( settings.oInstance, args ); } ); } if ( e !== null ) { $(settings.nTable).trigger( e+'.dt', args ); } return ret; } function _fnLengthOverflow ( settings ) { var start = settings._iDisplayStart, end = settings.fnDisplayEnd(), len = settings._iDisplayLength; /* If we have space to show extra rows (backing up from the end point - then do so */ if ( start >= end ) { start = end - len; } // Keep the start record on the current page start -= (start % len); if ( len === -1 || start < 0 ) { start = 0; } settings._iDisplayStart = start; } function _fnRenderer( settings, type ) { var renderer = settings.renderer; var host = DataTable.ext.renderer[type]; if ( $.isPlainObject( renderer ) && renderer[type] ) { // Specific renderer for this type. If available use it, otherwise use // the default. return host[renderer[type]] || host._; } else if ( typeof renderer === 'string' ) { // Common renderer - if there is one available for this type use it, // otherwise use the default return host[renderer] || host._; } // Use the default return host._; } /** * Detect the data source being used for the table. Used to simplify the code * a little (ajax) and to make it compress a little smaller. * * @param {object} settings dataTables settings object * @returns {string} Data source * @memberof DataTable#oApi */ function _fnDataSource ( settings ) { if ( settings.oFeatures.bServerSide ) { return 'ssp'; } else if ( settings.ajax || settings.sAjaxSource ) { return 'ajax'; } return 'dom'; } DataTable = function( options ) { /** * Perform a jQuery selector action on the table's TR elements (from the tbody) and * return the resulting jQuery object. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select TR elements that meet the current filter * criterion ("applied") or all TR elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the TR elements in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {object} jQuery object, filtered by the given selector. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Highlight every second row * oTable.$('tr:odd').css('backgroundColor', 'blue'); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to rows with 'Webkit' in them, add a background colour and then * // remove the filter, thus highlighting the 'Webkit' rows only. * oTable.fnFilter('Webkit'); * oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue'); * oTable.fnFilter(''); * } ); */ this.$ = function ( sSelector, oOpts ) { return this.api(true).$( sSelector, oOpts ); }; /** * Almost identical to $ in operation, but in this case returns the data for the matched * rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes * rather than any descendants, so the data can be obtained for the row/cell. If matching * rows are found, the data returned is the original data array/object that was used to * create the row (or a generated array if from a DOM source). * * This method is often useful in-combination with $ where both functions are given the * same parameters and the array indexes will match identically. * @param {string|node|jQuery} sSelector jQuery selector or node collection to act on * @param {object} [oOpts] Optional parameters for modifying the rows to be included * @param {string} [oOpts.filter=none] Select elements that meet the current filter * criterion ("applied") or all elements (i.e. no filter). * @param {string} [oOpts.order=current] Order of the data in the processed array. * Can be either 'current', whereby the current sorting of the table is used, or * 'original' whereby the original order the data was read into the table is used. * @param {string} [oOpts.page=all] Limit the selection to the currently displayed page * ("current") or not ("all"). If 'current' is given, then order is assumed to be * 'current' and filter is 'applied', regardless of what they might be given as. * @returns {array} Data for the matched elements. If any elements, as a result of the * selector, were not TR, TD or TH elements in the DataTable, they will have a null * entry in the array. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the data from the first row in the table * var data = oTable._('tr:first'); * * // Do something useful with the data * alert( "First cell is: "+data[0] ); * } ); * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Filter to 'Webkit' and get all data for * oTable.fnFilter('Webkit'); * var data = oTable._('tr', {"search": "applied"}); * * // Do something with the data * alert( data.length+" rows matched the search" ); * } ); */ this._ = function ( sSelector, oOpts ) { return this.api(true).rows( sSelector, oOpts ).data(); }; /** * Create a DataTables Api instance, with the currently selected tables for * the Api's context. * @param {boolean} [traditional=false] Set the API instance's context to be * only the table referred to by the `DataTable.ext.iApiIndex` option, as was * used in the API presented by DataTables 1.9- (i.e. the traditional mode), * or if all tables captured in the jQuery object should be used. * @return {DataTables.Api} */ this.api = function ( traditional ) { return traditional ? new _Api( _fnSettingsFromNode( this[ _ext.iApiIndex ] ) ) : new _Api( this ); }; /** * Add a single new row or multiple rows of data to the table. Please note * that this is suitable for client-side processing only - if you are using * server-side processing (i.e. "bServerSide": true), then to add data, you * must add it to the data source, i.e. the server-side, through an Ajax call. * @param {array|object} data The data to be added to the table. This can be: * <ul> * <li>1D array of data - add a single row with the data provided</li> * <li>2D array of arrays - add multiple rows in a single call</li> * <li>object - data object when using <i>mData</i></li> * <li>array of objects - multiple data objects when using <i>mData</i></li> * </ul> * @param {bool} [redraw=true] redraw the table or not * @returns {array} An array of integers, representing the list of indexes in * <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to * the table. * @dtopt API * @deprecated Since v1.10 * * @example * // Global var for counter * var giCount = 2; * * $(document).ready(function() { * $('#example').dataTable(); * } ); * * function fnClickAddRow() { * $('#example').dataTable().fnAddData( [ * giCount+".1", * giCount+".2", * giCount+".3", * giCount+".4" ] * ); * * giCount++; * } */ this.fnAddData = function( data, redraw ) { var api = this.api( true ); /* Check if we want to add multiple rows or not */ var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ? api.rows.add( data ) : api.row.add( data ); if ( redraw === undefined || redraw ) { api.draw(); } return rows.flatten().toArray(); }; /** * This function will make DataTables recalculate the column sizes, based on the data * contained in the table and the sizes applied to the columns (in the DOM, CSS or * through the sWidth parameter). This can be useful when the width of the table's * parent element changes (for example a window resize). * @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable( { * "sScrollY": "200px", * "bPaginate": false * } ); * * $(window).bind('resize', function () { * oTable.fnAdjustColumnSizing(); * } ); * } ); */ this.fnAdjustColumnSizing = function ( bRedraw ) { var api = this.api( true ).columns.adjust(); var settings = api.settings()[0]; var scroll = settings.oScroll; if ( bRedraw === undefined || bRedraw ) { api.draw( false ); } else if ( scroll.sX !== "" || scroll.sY !== "" ) { /* If not redrawing, but scrolling, we want to apply the new column sizes anyway */ _fnScrollDraw( settings ); } }; /** * Quickly and simply clear a table * @param {bool} [bRedraw=true] redraw the table or not * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...) * oTable.fnClearTable(); * } ); */ this.fnClearTable = function( bRedraw ) { var api = this.api( true ).clear(); if ( bRedraw === undefined || bRedraw ) { api.draw(); } }; /** * The exact opposite of 'opening' a row, this function will close any rows which * are currently 'open'. * @param {node} nTr the table row to 'close' * @returns {int} 0 on success, or 1 if failed (can't find the row) * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnClose = function( nTr ) { this.api( true ).row( nTr ).child.hide(); }; /** * Remove a row for the table * @param {mixed} target The index of the row from aoData to be deleted, or * the TR element you want to delete * @param {function|null} [callBack] Callback function * @param {bool} [redraw=true] Redraw the table or not * @returns {array} The row that was deleted * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Immediately remove the first row * oTable.fnDeleteRow( 0 ); * } ); */ this.fnDeleteRow = function( target, callback, redraw ) { var api = this.api( true ); var rows = api.rows( target ); var settings = rows.settings()[0]; var data = settings.aoData[ rows[0][0] ]; rows.remove(); if ( callback ) { callback.call( this, settings, data ); } if ( redraw === undefined || redraw ) { api.draw(); } return data; }; /** * Restore the table to it's original state in the DOM by removing all of DataTables * enhancements, alterations to the DOM structure of the table and event listeners. * @param {boolean} [remove=false] Completely remove the table from the DOM * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * // This example is fairly pointless in reality, but shows how fnDestroy can be used * var oTable = $('#example').dataTable(); * oTable.fnDestroy(); * } ); */ this.fnDestroy = function ( remove ) { this.api( true ).destroy( remove ); }; /** * Redraw the table * @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Re-draw the table - you wouldn't want to do it here, but it's an example :-) * oTable.fnDraw(); * } ); */ this.fnDraw = function( complete ) { // Note that this isn't an exact match to the old call to _fnDraw - it takes // into account the new data, but can old position. this.api( true ).draw( ! complete ); }; /** * Filter the input based on data * @param {string} sInput String to filter the table on * @param {int|null} [iColumn] Column to limit filtering to * @param {bool} [bRegex=false] Treat as regular expression or not * @param {bool} [bSmart=true] Perform smart filtering or not * @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es) * @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false) * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sometime later - filter... * oTable.fnFilter( 'test string' ); * } ); */ this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive ) { var api = this.api( true ); if ( iColumn === null || iColumn === undefined ) { api.search( sInput, bRegex, bSmart, bCaseInsensitive ); } else { api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive ); } api.draw(); }; /** * Get the data for the whole table, an individual row or an individual cell based on the * provided parameters. * @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as * a TR node then the data source for the whole row will be returned. If given as a * TD/TH cell node then iCol will be automatically calculated and the data for the * cell returned. If given as an integer, then this is treated as the aoData internal * data index for the row (see fnGetPosition) and the data for that row used. * @param {int} [col] Optional column index that you want the data of. * @returns {array|object|string} If mRow is undefined, then the data for all rows is * returned. If mRow is defined, just data for that row, and is iCol is * defined, only data for the designated cell is returned. * @dtopt API * @deprecated Since v1.10 * * @example * // Row data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('tr').click( function () { * var data = oTable.fnGetData( this ); * // ... do something with the array / object of data for the row * } ); * } ); * * @example * // Individual cell data * $(document).ready(function() { * oTable = $('#example').dataTable(); * * oTable.$('td').click( function () { * var sData = oTable.fnGetData( this ); * alert( 'The cell clicked on had the value of '+sData ); * } ); * } ); */ this.fnGetData = function( src, col ) { var api = this.api( true ); if ( src !== undefined ) { var type = src.nodeName ? src.nodeName.toLowerCase() : ''; return col !== undefined || type == 'td' || type == 'th' ? api.cell( src, col ).data() : api.row( src ).data() || null; } return api.data().toArray(); }; /** * Get an array of the TR nodes that are used in the table's body. Note that you will * typically want to use the '$' API method in preference to this as it is more * flexible. * @param {int} [iRow] Optional row index for the TR element you want * @returns {array|node} If iRow is undefined, returns an array of all TR elements * in the table's body, or iRow is defined, just the TR element requested. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Get the nodes from the table * var nNodes = oTable.fnGetNodes( ); * } ); */ this.fnGetNodes = function( iRow ) { var api = this.api( true ); return iRow !== undefined ? api.row( iRow ).node() : api.rows().nodes().flatten().toArray(); }; /** * Get the array indexes of a particular cell from it's DOM element * and column index including hidden columns * @param {node} node this can either be a TR, TD or TH in the table's body * @returns {int} If nNode is given as a TR, then a single index is returned, or * if given as a cell, an array of [row index, column index (visible), * column index (all)] is given. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * $('#example tbody td').click( function () { * // Get the position of the current data from the node * var aPos = oTable.fnGetPosition( this ); * * // Get the data array for this row * var aData = oTable.fnGetData( aPos[0] ); * * // Update the data array and return the value * aData[ aPos[1] ] = 'clicked'; * this.innerHTML = 'clicked'; * } ); * * // Init DataTables * oTable = $('#example').dataTable(); * } ); */ this.fnGetPosition = function( node ) { var api = this.api( true ); var nodeName = node.nodeName.toUpperCase(); if ( nodeName == 'TR' ) { return api.row( node ).index(); } else if ( nodeName == 'TD' || nodeName == 'TH' ) { var cell = api.cell( node ).index(); return [ cell.row, cell.columnVisible, cell.column ]; } return null; }; /** * Check to see if a row is 'open' or not. * @param {node} nTr the table row to check * @returns {boolean} true if the row is currently open, false otherwise * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnIsOpen = function( nTr ) { return this.api( true ).row( nTr ).child.isShown(); }; /** * This function will place a new row directly after a row which is currently * on display on the page, with the HTML contents that is passed into the * function. This can be used, for example, to ask for confirmation that a * particular record should be deleted. * @param {node} nTr The table row to 'open' * @param {string|node|jQuery} mHtml The HTML to put into the row * @param {string} sClass Class to give the new TD cell * @returns {node} The row opened. Note that if the table row passed in as the * first parameter, is not found in the table, this method will silently * return. * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable; * * // 'open' an information row when a row is clicked on * $('#example tbody tr').click( function () { * if ( oTable.fnIsOpen(this) ) { * oTable.fnClose( this ); * } else { * oTable.fnOpen( this, "Temporary row opened", "info_row" ); * } * } ); * * oTable = $('#example').dataTable(); * } ); */ this.fnOpen = function( nTr, mHtml, sClass ) { return this.api( true ) .row( nTr ) .child( mHtml, sClass ) .show() .child()[0]; }; /** * Change the pagination - provides the internal logic for pagination in a simple API * function. With this function you can have a DataTables table go to the next, * previous, first or last pages. * @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last" * or page number to jump to (integer), note that page 0 is the first page. * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnPageChange( 'next' ); * } ); */ this.fnPageChange = function ( mAction, bRedraw ) { var api = this.api( true ).page( mAction ); if ( bRedraw === undefined || bRedraw ) { api.draw(false); } }; /** * Show a particular column * @param {int} iCol The column whose display should be changed * @param {bool} bShow Show (true) or hide (false) the column * @param {bool} [bRedraw=true] Redraw the table or not * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Hide the second column after initialisation * oTable.fnSetColumnVis( 1, false ); * } ); */ this.fnSetColumnVis = function ( iCol, bShow, bRedraw ) { var api = this.api( true ).column( iCol ).visible( bShow ); if ( bRedraw === undefined || bRedraw ) { api.columns.adjust().draw(); } }; /** * Get the settings for a particular table for external manipulation * @returns {object} DataTables settings object. See * {@link DataTable.models.oSettings} * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * var oSettings = oTable.fnSettings(); * * // Show an example parameter from the settings * alert( oSettings._iDisplayStart ); * } ); */ this.fnSettings = function() { return _fnSettingsFromNode( this[_ext.iApiIndex] ); }; /** * Sort the table by a particular column * @param {int} iCol the data index to sort on. Note that this will not match the * 'display index' if you have hidden data entries * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort immediately with columns 0 and 1 * oTable.fnSort( [ [0,'asc'], [1,'asc'] ] ); * } ); */ this.fnSort = function( aaSort ) { this.api( true ).order( aaSort ).draw(); }; /** * Attach a sort listener to an element for a given column * @param {node} nNode the element to attach the sort listener to * @param {int} iColumn the column that a click on this node will sort on * @param {function} [fnCallback] callback function when sort is run * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * * // Sort on column 1, when 'sorter' is clicked on * oTable.fnSortListener( document.getElementById('sorter'), 1 ); * } ); */ this.fnSortListener = function( nNode, iColumn, fnCallback ) { this.api( true ).order.listener( nNode, iColumn, fnCallback ); }; /** * Update a table cell or row - this method will accept either a single value to * update the cell with, an array of values with one element for each column or * an object in the same format as the original data source. The function is * self-referencing in order to make the multi column updates easier. * @param {object|array|string} mData Data to update the cell/row with * @param {node|int} mRow TR element you want to update or the aoData index * @param {int} [iColumn] The column to update, give as null or undefined to * update a whole row. * @param {bool} [bRedraw=true] Redraw the table or not * @param {bool} [bAction=true] Perform pre-draw actions or not * @returns {int} 0 on success, 1 on error * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell * oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row * } ); */ this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction ) { var api = this.api( true ); if ( iColumn === undefined || iColumn === null ) { api.row( mRow ).data( mData ); } else { api.cell( mRow, iColumn ).data( mData ); } if ( bAction === undefined || bAction ) { api.columns.adjust(); } if ( bRedraw === undefined || bRedraw ) { api.draw(); } return 0; }; /** * Provide a common method for plug-ins to check the version of DataTables being used, in order * to ensure compatibility. * @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the * formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to the required * version, or false if this version of DataTales is not suitable * @method * @dtopt API * @deprecated Since v1.10 * * @example * $(document).ready(function() { * var oTable = $('#example').dataTable(); * alert( oTable.fnVersionCheck( '1.9.0' ) ); * } ); */ this.fnVersionCheck = _ext.fnVersionCheck; var _that = this; var emptyInit = options === undefined; var len = this.length; if ( emptyInit ) { options = {}; } this.oApi = this.internal = _ext.internal; // Extend with old style plug-in API methods for ( var fn in DataTable.ext.internal ) { if ( fn ) { this[fn] = _fnExternApiFunc(fn); } } this.each(function() { // For each initialisation we want to give it a clean initialisation // object that can be bashed around var o = {}; var oInit = len > 1 ? // optimisation for single table case _fnExtend( o, options, true ) : options; /*global oInit,_that,emptyInit*/ var i=0, iLen, j, jLen, k, kLen; var sId = this.getAttribute( 'id' ); var bInitHandedOff = false; var defaults = DataTable.defaults; /* Sanity check */ if ( this.nodeName.toLowerCase() != 'table' ) { _fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 ); return; } /* Backwards compatibility for the defaults */ _fnCompatOpts( defaults ); _fnCompatCols( defaults.column ); /* Convert the camel-case defaults to Hungarian */ _fnCamelToHungarian( defaults, defaults, true ); _fnCamelToHungarian( defaults.column, defaults.column, true ); /* Setting up the initialisation object */ _fnCamelToHungarian( defaults, oInit ); /* Check to see if we are re-initialising a table */ var allSettings = DataTable.settings; for ( i=0, iLen=allSettings.length ; i<iLen ; i++ ) { /* Base check on table node */ if ( allSettings[i].nTable == this ) { var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve; var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy; if ( emptyInit || bRetrieve ) { return allSettings[i].oInstance; } else if ( bDestroy ) { allSettings[i].oInstance.fnDestroy(); break; } else { _fnLog( allSettings[i], 0, 'Cannot reinitialise DataTable', 3 ); return; } } /* If the element we are initialising has the same ID as a table which was previously * initialised, but the table nodes don't match (from before) then we destroy the old * instance by simply deleting it. This is under the assumption that the table has been * destroyed by other methods. Anyone using non-id selectors will need to do this manually */ if ( allSettings[i].sTableId == this.id ) { allSettings.splice( i, 1 ); break; } } /* Ensure the table has an ID - required for accessibility */ if ( sId === null || sId === "" ) { sId = "DataTables_Table_"+(DataTable.ext._unique++); this.id = sId; } /* Create the settings object for this table and set some of the default parameters */ var oSettings = $.extend( true, {}, DataTable.models.oSettings, { "nTable": this, "oApi": _that.internal, "oInit": oInit, "sDestroyWidth": $(this)[0].style.width, "sInstance": sId, "sTableId": sId } ); allSettings.push( oSettings ); // Need to add the instance after the instance after the settings object has been added // to the settings array, so we can self reference the table instance if more than one oSettings.oInstance = (_that.length===1) ? _that : $(this).dataTable(); // Backwards compatibility, before we apply all the defaults _fnCompatOpts( oInit ); if ( oInit.oLanguage ) { _fnLanguageCompat( oInit.oLanguage ); } // If the length menu is given, but the init display length is not, use the length menu if ( oInit.aLengthMenu && ! oInit.iDisplayLength ) { oInit.iDisplayLength = $.isArray( oInit.aLengthMenu[0] ) ? oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0]; } // Apply the defaults and init options to make a single init object will all // options defined from defaults and instance options. oInit = _fnExtend( $.extend( true, {}, defaults ), oInit ); // Map the initialisation options onto the settings object _fnMap( oSettings.oFeatures, oInit, [ "bPaginate", "bLengthChange", "bFilter", "bSort", "bSortMulti", "bInfo", "bProcessing", "bAutoWidth", "bSortClasses", "bServerSide", "bDeferRender" ] ); _fnMap( oSettings, oInit, [ "asStripeClasses", "ajax", "fnServerData", "fnFormatNumber", "sServerMethod", "aaSorting", "aaSortingFixed", "aLengthMenu", "sPaginationType", "sAjaxSource", "sAjaxDataProp", "iStateDuration", "sDom", "bSortCellsTop", "iTabIndex", "fnStateLoadCallback", "fnStateSaveCallback", "renderer", "searchDelay", [ "iCookieDuration", "iStateDuration" ], // backwards compat [ "oSearch", "oPreviousSearch" ], [ "aoSearchCols", "aoPreSearchCols" ], [ "iDisplayLength", "_iDisplayLength" ], [ "bJQueryUI", "bJUI" ] ] ); _fnMap( oSettings.oScroll, oInit, [ [ "sScrollX", "sX" ], [ "sScrollXInner", "sXInner" ], [ "sScrollY", "sY" ], [ "bScrollCollapse", "bCollapse" ] ] ); _fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" ); /* Callback functions which are array driven */ _fnCallbackReg( oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user' ); _fnCallbackReg( oSettings, 'aoServerParams', oInit.fnServerParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user' ); _fnCallbackReg( oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user' ); _fnCallbackReg( oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user' ); _fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user' ); _fnCallbackReg( oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user' ); _fnCallbackReg( oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user' ); _fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' ); _fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' ); var oClasses = oSettings.oClasses; // @todo Remove in 1.11 if ( oInit.bJQueryUI ) { /* Use the JUI classes object for display. You could clone the oStdClasses object if * you want to have multiple tables with multiple independent classes */ $.extend( oClasses, DataTable.ext.oJUIClasses, oInit.oClasses ); if ( oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip" ) { /* Set the DOM to use a layout suitable for jQuery UI's theming */ oSettings.sDom = '<"H"lfr>t<"F"ip>'; } if ( ! oSettings.renderer ) { oSettings.renderer = 'jqueryui'; } else if ( $.isPlainObject( oSettings.renderer ) && ! oSettings.renderer.header ) { oSettings.renderer.header = 'jqueryui'; } } else { $.extend( oClasses, DataTable.ext.classes, oInit.oClasses ); } $(this).addClass( oClasses.sTable ); /* Calculate the scroll bar width and cache it for use later on */ if ( oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "" ) { oSettings.oScroll.iBarWidth = _fnScrollBarWidth(); } if ( oSettings.oScroll.sX === true ) { // Easy initialisation of x-scrolling oSettings.oScroll.sX = '100%'; } if ( oSettings.iInitDisplayStart === undefined ) { /* Display start point, taking into account the save saving */ oSettings.iInitDisplayStart = oInit.iDisplayStart; oSettings._iDisplayStart = oInit.iDisplayStart; } if ( oInit.iDeferLoading !== null ) { oSettings.bDeferLoading = true; var tmp = $.isArray( oInit.iDeferLoading ); oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading; oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading; } /* Language definitions */ var oLanguage = oSettings.oLanguage; $.extend( true, oLanguage, oInit.oLanguage ); if ( oLanguage.sUrl !== "" ) { /* Get the language definitions from a file - because this Ajax call makes the language * get async to the remainder of this function we use bInitHandedOff to indicate that * _fnInitialise will be fired by the returned Ajax handler, rather than the constructor */ $.ajax( { dataType: 'json', url: oLanguage.sUrl, success: function ( json ) { _fnLanguageCompat( json ); _fnCamelToHungarian( defaults.oLanguage, json ); $.extend( true, oLanguage, json ); _fnInitialise( oSettings ); }, error: function () { // Error occurred loading language file, continue on as best we can _fnInitialise( oSettings ); } } ); bInitHandedOff = true; } /* * Stripes */ if ( oInit.asStripeClasses === null ) { oSettings.asStripeClasses =[ oClasses.sStripeOdd, oClasses.sStripeEven ]; } /* Remove row stripe classes if they are already on the table row */ var stripeClasses = oSettings.asStripeClasses; var rowOne = $('tbody tr:eq(0)', this); if ( $.inArray( true, $.map( stripeClasses, function(el, i) { return rowOne.hasClass(el); } ) ) !== -1 ) { $('tbody tr', this).removeClass( stripeClasses.join(' ') ); oSettings.asDestroyStripes = stripeClasses.slice(); } /* * Columns * See if we should load columns automatically or use defined ones */ var anThs = []; var aoColumnsInit; var nThead = this.getElementsByTagName('thead'); if ( nThead.length !== 0 ) { _fnDetectHeader( oSettings.aoHeader, nThead[0] ); anThs = _fnGetUniqueThs( oSettings ); } /* If not given a column array, generate one with nulls */ if ( oInit.aoColumns === null ) { aoColumnsInit = []; for ( i=0, iLen=anThs.length ; i<iLen ; i++ ) { aoColumnsInit.push( null ); } } else { aoColumnsInit = oInit.aoColumns; } /* Add the columns */ for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ ) { _fnAddColumn( oSettings, anThs ? anThs[i] : null ); } /* Apply the column definitions */ _fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) { _fnColumnOptions( oSettings, iCol, oDef ); } ); /* HTML5 attribute detection - build an mData object automatically if the * attributes are found */ if ( rowOne.length ) { var a = function ( cell, name ) { return cell.getAttribute( 'data-'+name ) ? name : null; }; $.each( _fnGetRowElements( oSettings, rowOne[0] ).cells, function (i, cell) { var col = oSettings.aoColumns[i]; if ( col.mData === i ) { var sort = a( cell, 'sort' ) || a( cell, 'order' ); var filter = a( cell, 'filter' ) || a( cell, 'search' ); if ( sort !== null || filter !== null ) { col.mData = { _: i+'.display', sort: sort !== null ? i+'.@data-'+sort : undefined, type: sort !== null ? i+'.@data-'+sort : undefined, filter: filter !== null ? i+'.@data-'+filter : undefined }; _fnColumnOptions( oSettings, i ); } } } ); } var features = oSettings.oFeatures; /* Must be done after everything which can be overridden by the state saving! */ if ( oInit.bStateSave ) { features.bStateSave = true; _fnLoadState( oSettings, oInit ); _fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' ); } /* * Sorting * @todo For modularisation (1.11) this needs to do into a sort start up handler */ // If aaSorting is not defined, then we use the first indicator in asSorting // in case that has been altered, so the default sort reflects that option if ( oInit.aaSorting === undefined ) { var sorting = oSettings.aaSorting; for ( i=0, iLen=sorting.length ; i<iLen ; i++ ) { sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0]; } } /* Do a first pass on the sorting classes (allows any size changes to be taken into * account, and also will apply sorting disabled classes if disabled */ _fnSortingClasses( oSettings ); if ( features.bSort ) { _fnCallbackReg( oSettings, 'aoDrawCallback', function () { if ( oSettings.bSorted ) { var aSort = _fnSortFlatten( oSettings ); var sortedColumns = {}; $.each( aSort, function (i, val) { sortedColumns[ val.src ] = val.dir; } ); _fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] ); _fnSortAria( oSettings ); } } ); } _fnCallbackReg( oSettings, 'aoDrawCallback', function () { if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) { _fnSortingClasses( oSettings ); } }, 'sc' ); /* * Final init * Cache the header, body and footer as required, creating them if needed */ /* Browser support detection */ _fnBrowserDetect( oSettings ); // Work around for Webkit bug 83867 - store the caption-side before removing from doc var captions = $(this).children('caption').each( function () { this._captionSide = $(this).css('caption-side'); } ); var thead = $(this).children('thead'); if ( thead.length === 0 ) { thead = $('<thead/>').appendTo(this); } oSettings.nTHead = thead[0]; var tbody = $(this).children('tbody'); if ( tbody.length === 0 ) { tbody = $('<tbody/>').appendTo(this); } oSettings.nTBody = tbody[0]; var tfoot = $(this).children('tfoot'); if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") ) { // If we are a scrolling table, and no footer has been given, then we need to create // a tfoot element for the caption element to be appended to tfoot = $('<tfoot/>').appendTo(this); } if ( tfoot.length === 0 || tfoot.children().length === 0 ) { $(this).addClass( oClasses.sNoFooter ); } else if ( tfoot.length > 0 ) { oSettings.nTFoot = tfoot[0]; _fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot ); } /* Check if there is data passing into the constructor */ if ( oInit.aaData ) { for ( i=0 ; i<oInit.aaData.length ; i++ ) { _fnAddData( oSettings, oInit.aaData[ i ] ); } } else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' ) { /* Grab the data from the page - only do this when deferred loading or no Ajax * source since there is no point in reading the DOM data if we are then going * to replace it with Ajax data */ _fnAddTr( oSettings, $(oSettings.nTBody).children('tr') ); } /* Copy the data index array */ oSettings.aiDisplay = oSettings.aiDisplayMaster.slice(); /* Initialisation complete - table can be drawn */ oSettings.bInitialised = true; /* Check if we need to initialise the table (it might not have been handed off to the * language processor) */ if ( bInitHandedOff === false ) { _fnInitialise( oSettings ); } } ); _that = null; return this; }; /** * Computed structure of the DataTables API, defined by the options passed to * `DataTable.Api.register()` when building the API. * * The structure is built in order to speed creation and extension of the Api * objects since the extensions are effectively pre-parsed. * * The array is an array of objects with the following structure, where this * base array represents the Api prototype base: * * [ * { * name: 'data' -- string - Property name * val: function () {}, -- function - Api method (or undefined if just an object * methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result * propExt: [ ... ] -- array - Array of Api object definitions to extend the property * }, * { * name: 'row' * val: {}, * methodExt: [ ... ], * propExt: [ * { * name: 'data' * val: function () {}, * methodExt: [ ... ], * propExt: [ ... ] * }, * ... * ] * } * ] * * @type {Array} * @ignore */ var __apiStruct = []; /** * `Array.prototype` reference. * * @type object * @ignore */ var __arrayProto = Array.prototype; /** * Abstraction for `context` parameter of the `Api` constructor to allow it to * take several different forms for ease of use. * * Each of the input parameter types will be converted to a DataTables settings * object where possible. * * @param {string|node|jQuery|object} mixed DataTable identifier. Can be one * of: * * * `string` - jQuery selector. Any DataTables' matching the given selector * with be found and used. * * `node` - `TABLE` node which has already been formed into a DataTable. * * `jQuery` - A jQuery object of `TABLE` nodes. * * `object` - DataTables settings object * * `DataTables.Api` - API instance * @return {array|null} Matching DataTables settings objects. `null` or * `undefined` is returned if no matching DataTable is found. * @ignore */ var _toSettings = function ( mixed ) { var idx, jq; var settings = DataTable.settings; var tables = $.map( settings, function (el, i) { return el.nTable; } ); if ( ! mixed ) { return []; } else if ( mixed.nTable && mixed.oApi ) { // DataTables settings object return [ mixed ]; } else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) { // Table node idx = $.inArray( mixed, tables ); return idx !== -1 ? [ settings[idx] ] : null; } else if ( mixed && typeof mixed.settings === 'function' ) { return mixed.settings().toArray(); } else if ( typeof mixed === 'string' ) { // jQuery selector jq = $(mixed); } else if ( mixed instanceof $ ) { // jQuery object (also DataTables instance) jq = mixed; } if ( jq ) { return jq.map( function(i) { idx = $.inArray( this, tables ); return idx !== -1 ? settings[idx] : null; } ).toArray(); } }; /** * DataTables API class - used to control and interface with one or more * DataTables enhanced tables. * * The API class is heavily based on jQuery, presenting a chainable interface * that you can use to interact with tables. Each instance of the API class has * a "context" - i.e. the tables that it will operate on. This could be a single * table, all tables on a page or a sub-set thereof. * * Additionally the API is designed to allow you to easily work with the data in * the tables, retrieving and manipulating it as required. This is done by * presenting the API class as an array like interface. The contents of the * array depend upon the actions requested by each method (for example * `rows().nodes()` will return an array of nodes, while `rows().data()` will * return an array of objects or arrays depending upon your table's * configuration). The API object has a number of array like methods (`push`, * `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`, * `unique` etc) to assist your working with the data held in a table. * * Most methods (those which return an Api instance) are chainable, which means * the return from a method call also has all of the methods available that the * top level object had. For example, these two calls are equivalent: * * // Not chained * api.row.add( {...} ); * api.draw(); * * // Chained * api.row.add( {...} ).draw(); * * @class DataTable.Api * @param {array|object|string|jQuery} context DataTable identifier. This is * used to define which DataTables enhanced tables this API will operate on. * Can be one of: * * * `string` - jQuery selector. Any DataTables' matching the given selector * with be found and used. * * `node` - `TABLE` node which has already been formed into a DataTable. * * `jQuery` - A jQuery object of `TABLE` nodes. * * `object` - DataTables settings object * @param {array} [data] Data to initialise the Api instance with. * * @example * // Direct initialisation during DataTables construction * var api = $('#example').DataTable(); * * @example * // Initialisation using a DataTables jQuery object * var api = $('#example').dataTable().api(); * * @example * // Initialisation as a constructor * var api = new $.fn.DataTable.Api( 'table.dataTable' ); */ _Api = function ( context, data ) { if ( ! this instanceof _Api ) { throw 'DT API must be constructed as a new object'; // or should it do the 'new' for the caller? // return new _Api.apply( this, arguments ); } var settings = []; var ctxSettings = function ( o ) { var a = _toSettings( o ); if ( a ) { settings.push.apply( settings, a ); } }; if ( $.isArray( context ) ) { for ( var i=0, ien=context.length ; i<ien ; i++ ) { ctxSettings( context[i] ); } } else { ctxSettings( context ); } // Remove duplicates this.context = _unique( settings ); // Initial data if ( data ) { this.push.apply( this, data.toArray ? data.toArray() : data ); } // selector this.selector = { rows: null, cols: null, opts: null }; _Api.extend( this, this, __apiStruct ); }; DataTable.Api = _Api; _Api.prototype = /** @lends DataTables.Api */{ /** * Return a new Api instance, comprised of the data held in the current * instance, join with the other array(s) and/or value(s). * * An alias for `Array.prototype.concat`. * * @type method * @param {*} value1 Arrays and/or values to concatenate. * @param {*} [...] Additional arrays and/or values to concatenate. * @returns {DataTables.Api} New API instance, comprising of the combined * array. */ concat: __arrayProto.concat, context: [], // array of table settings objects each: function ( fn ) { for ( var i=0, ien=this.length ; i<ien; i++ ) { fn.call( this, this[i], i, this ); } return this; }, eq: function ( idx ) { var ctx = this.context; return ctx.length > idx ? new _Api( ctx[idx], this[idx] ) : null; }, filter: function ( fn ) { var a = []; if ( __arrayProto.filter ) { a = __arrayProto.filter.call( this, fn, this ); } else { // Compatibility for browsers without EMCA-252-5 (JS 1.6) for ( var i=0, ien=this.length ; i<ien ; i++ ) { if ( fn.call( this, this[i], i, this ) ) { a.push( this[i] ); } } } return new _Api( this.context, a ); }, flatten: function () { var a = []; return new _Api( this.context, a.concat.apply( a, this.toArray() ) ); }, join: __arrayProto.join, indexOf: __arrayProto.indexOf || function (obj, start) { for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) { if ( this[i] === obj ) { return i; } } return -1; }, // Note that `alwaysNew` is internal - use iteratorNew externally iterator: function ( flatten, type, fn, alwaysNew ) { var a = [], ret, i, ien, j, jen, context = this.context, rows, items, item, selector = this.selector; // Argument shifting if ( typeof flatten === 'string' ) { alwaysNew = fn; fn = type; type = flatten; flatten = false; } for ( i=0, ien=context.length ; i<ien ; i++ ) { var apiInst = new _Api( context[i] ); if ( type === 'table' ) { ret = fn.call( apiInst, context[i], i ); if ( ret !== undefined ) { a.push( ret ); } } else if ( type === 'columns' || type === 'rows' ) { // this has same length as context - one entry for each table ret = fn.call( apiInst, context[i], this[i], i ); if ( ret !== undefined ) { a.push( ret ); } } else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) { // columns and rows share the same structure. // 'this' is an array of column indexes for each context items = this[i]; if ( type === 'column-rows' ) { rows = _selector_row_indexes( context[i], selector.opts ); } for ( j=0, jen=items.length ; j<jen ; j++ ) { item = items[j]; if ( type === 'cell' ) { ret = fn.call( apiInst, context[i], item.row, item.column, i, j ); } else { ret = fn.call( apiInst, context[i], item, i, j, rows ); } if ( ret !== undefined ) { a.push( ret ); } } } } if ( a.length || alwaysNew ) { var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a ); var apiSelector = api.selector; apiSelector.rows = selector.rows; apiSelector.cols = selector.cols; apiSelector.opts = selector.opts; return api; } return this; }, lastIndexOf: __arrayProto.lastIndexOf || function (obj, start) { // Bit cheeky... return this.indexOf.apply( this.toArray.reverse(), arguments ); }, length: 0, map: function ( fn ) { var a = []; if ( __arrayProto.map ) { a = __arrayProto.map.call( this, fn, this ); } else { // Compatibility for browsers without EMCA-252-5 (JS 1.6) for ( var i=0, ien=this.length ; i<ien ; i++ ) { a.push( fn.call( this, this[i], i ) ); } } return new _Api( this.context, a ); }, pluck: function ( prop ) { return this.map( function ( el ) { return el[ prop ]; } ); }, pop: __arrayProto.pop, push: __arrayProto.push, // Does not return an API instance reduce: __arrayProto.reduce || function ( fn, init ) { return _fnReduce( this, fn, init, 0, this.length, 1 ); }, reduceRight: __arrayProto.reduceRight || function ( fn, init ) { return _fnReduce( this, fn, init, this.length-1, -1, -1 ); }, reverse: __arrayProto.reverse, // Object with rows, columns and opts selector: null, shift: __arrayProto.shift, sort: __arrayProto.sort, // ? name - order? splice: __arrayProto.splice, toArray: function () { return __arrayProto.slice.call( this ); }, to$: function () { return $( this ); }, toJQuery: function () { return $( this ); }, unique: function () { return new _Api( this.context, _unique(this) ); }, unshift: __arrayProto.unshift }; _Api.extend = function ( scope, obj, ext ) { // Only extend API instances and static properties of the API if ( ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) { return; } var i, ien, j, jen, struct, inner, methodScoping = function ( scope, fn, struc ) { return function () { var ret = fn.apply( scope, arguments ); // Method extension _Api.extend( ret, ret, struc.methodExt ); return ret; }; }; for ( i=0, ien=ext.length ; i<ien ; i++ ) { struct = ext[i]; // Value obj[ struct.name ] = typeof struct.val === 'function' ? methodScoping( scope, struct.val, struct ) : $.isPlainObject( struct.val ) ? {} : struct.val; obj[ struct.name ].__dt_wrapper = true; // Property extension _Api.extend( scope, obj[ struct.name ], struct.propExt ); } }; // @todo - Is there need for an augment function? // _Api.augment = function ( inst, name ) // { // // Find src object in the structure from the name // var parts = name.split('.'); // _Api.extend( inst, obj ); // }; // [ // { // name: 'data' -- string - Property name // val: function () {}, -- function - Api method (or undefined if just an object // methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result // propExt: [ ... ] -- array - Array of Api object definitions to extend the property // }, // { // name: 'row' // val: {}, // methodExt: [ ... ], // propExt: [ // { // name: 'data' // val: function () {}, // methodExt: [ ... ], // propExt: [ ... ] // }, // ... // ] // } // ] _Api.register = _api_register = function ( name, val ) { if ( $.isArray( name ) ) { for ( var j=0, jen=name.length ; j<jen ; j++ ) { _Api.register( name[j], val ); } return; } var i, ien, heir = name.split('.'), struct = __apiStruct, key, method; var find = function ( src, name ) { for ( var i=0, ien=src.length ; i<ien ; i++ ) { if ( src[i].name === name ) { return src[i]; } } return null; }; for ( i=0, ien=heir.length ; i<ien ; i++ ) { method = heir[i].indexOf('()') !== -1; key = method ? heir[i].replace('()', '') : heir[i]; var src = find( struct, key ); if ( ! src ) { src = { name: key, val: {}, methodExt: [], propExt: [] }; struct.push( src ); } if ( i === ien-1 ) { src.val = val; } else { struct = method ? src.methodExt : src.propExt; } } }; _Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) { _Api.register( pluralName, val ); _Api.register( singularName, function () { var ret = val.apply( this, arguments ); if ( ret === this ) { // Returned item is the API instance that was passed in, return it return this; } else if ( ret instanceof _Api ) { // New API instance returned, want the value from the first item // in the returned array for the singular result. return ret.length ? $.isArray( ret[0] ) ? new _Api( ret.context, ret[0] ) : // Array results are 'enhanced' ret[0] : undefined; } // Non-API return - just fire it back return ret; } ); }; /** * Selector for HTML tables. Apply the given selector to the give array of * DataTables settings objects. * * @param {string|integer} [selector] jQuery selector string or integer * @param {array} Array of DataTables settings objects to be filtered * @return {array} * @ignore */ var __table_selector = function ( selector, a ) { // Integer is used to pick out a table by index if ( typeof selector === 'number' ) { return [ a[ selector ] ]; } // Perform a jQuery selector on the table nodes var nodes = $.map( a, function (el, i) { return el.nTable; } ); return $(nodes) .filter( selector ) .map( function (i) { // Need to translate back from the table node to the settings var idx = $.inArray( this, nodes ); return a[ idx ]; } ) .toArray(); }; /** * Context selector for the API's context (i.e. the tables the API instance * refers to. * * @name DataTable.Api#tables * @param {string|integer} [selector] Selector to pick which tables the iterator * should operate on. If not given, all tables in the current context are * used. This can be given as a jQuery selector (for example `':gt(0)'`) to * select multiple tables or as an integer to select a single table. * @returns {DataTable.Api} Returns a new API instance if a selector is given. */ _api_register( 'tables()', function ( selector ) { // A new instance is created if there was a selector specified return selector ? new _Api( __table_selector( selector, this.context ) ) : this; } ); _api_register( 'table()', function ( selector ) { var tables = this.tables( selector ); var ctx = tables.context; // Truncate to the first matched table return ctx.length ? new _Api( ctx[0] ) : tables; } ); _api_registerPlural( 'tables().nodes()', 'table().node()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTable; }, 1 ); } ); _api_registerPlural( 'tables().body()', 'table().body()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTBody; }, 1 ); } ); _api_registerPlural( 'tables().header()', 'table().header()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTHead; }, 1 ); } ); _api_registerPlural( 'tables().footer()', 'table().footer()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTFoot; }, 1 ); } ); _api_registerPlural( 'tables().containers()', 'table().container()' , function () { return this.iterator( 'table', function ( ctx ) { return ctx.nTableWrapper; }, 1 ); } ); /** * Redraw the tables in the current context. * * @param {boolean} [reset=true] Reset (default) or hold the current paging * position. A full re-sort and re-filter is performed when this method is * called, which is why the pagination reset is the default action. * @returns {DataTables.Api} this */ _api_register( 'draw()', function ( resetPaging ) { return this.iterator( 'table', function ( settings ) { _fnReDraw( settings, resetPaging===false ); } ); } ); /** * Get the current page index. * * @return {integer} Current page index (zero based) *//** * Set the current page. * * Note that if you attempt to show a page which does not exist, DataTables will * not throw an error, but rather reset the paging. * * @param {integer|string} action The paging action to take. This can be one of: * * `integer` - The page index to jump to * * `string` - An action to take: * * `first` - Jump to first page. * * `next` - Jump to the next page * * `previous` - Jump to previous page * * `last` - Jump to the last page. * @returns {DataTables.Api} this */ _api_register( 'page()', function ( action ) { if ( action === undefined ) { return this.page.info().page; // not an expensive call } // else, have an action to take on all tables return this.iterator( 'table', function ( settings ) { _fnPageChange( settings, action ); } ); } ); /** * Paging information for the first table in the current context. * * If you require paging information for another table, use the `table()` method * with a suitable selector. * * @return {object} Object with the following properties set: * * `page` - Current page index (zero based - i.e. the first page is `0`) * * `pages` - Total number of pages * * `start` - Display index for the first record shown on the current page * * `end` - Display index for the last record shown on the current page * * `length` - Display length (number of records). Note that generally `start * + length = end`, but this is not always true, for example if there are * only 2 records to show on the final page, with a length of 10. * * `recordsTotal` - Full data set length * * `recordsDisplay` - Data set length once the current filtering criterion * are applied. */ _api_register( 'page.info()', function ( action ) { if ( this.context.length === 0 ) { return undefined; } var settings = this.context[0], start = settings._iDisplayStart, len = settings._iDisplayLength, visRecords = settings.fnRecordsDisplay(), all = len === -1; return { "page": all ? 0 : Math.floor( start / len ), "pages": all ? 1 : Math.ceil( visRecords / len ), "start": start, "end": settings.fnDisplayEnd(), "length": len, "recordsTotal": settings.fnRecordsTotal(), "recordsDisplay": visRecords }; } ); /** * Get the current page length. * * @return {integer} Current page length. Note `-1` indicates that all records * are to be shown. *//** * Set the current page length. * * @param {integer} Page length to set. Use `-1` to show all records. * @returns {DataTables.Api} this */ _api_register( 'page.len()', function ( len ) { // Note that we can't call this function 'length()' because `length` // is a Javascript property of functions which defines how many arguments // the function expects. if ( len === undefined ) { return this.context.length !== 0 ? this.context[0]._iDisplayLength : undefined; } // else, set the page length return this.iterator( 'table', function ( settings ) { _fnLengthChange( settings, len ); } ); } ); var __reload = function ( settings, holdPosition, callback ) { if ( _fnDataSource( settings ) == 'ssp' ) { _fnReDraw( settings, holdPosition ); } else { // Trigger xhr _fnProcessingDisplay( settings, true ); _fnBuildAjax( settings, [], function( json ) { _fnClearTable( settings ); var data = _fnAjaxDataSrc( settings, json ); for ( var i=0, ien=data.length ; i<ien ; i++ ) { _fnAddData( settings, data[i] ); } _fnReDraw( settings, holdPosition ); _fnProcessingDisplay( settings, false ); } ); } // Use the draw event to trigger a callback, regardless of if it is an async // or sync draw if ( callback ) { var api = new _Api( settings ); api.one( 'draw', function () { callback( api.ajax.json() ); } ); } }; /** * Get the JSON response from the last Ajax request that DataTables made to the * server. Note that this returns the JSON from the first table in the current * context. * * @return {object} JSON received from the server. */ _api_register( 'ajax.json()', function () { var ctx = this.context; if ( ctx.length > 0 ) { return ctx[0].json; } // else return undefined; } ); /** * Get the data submitted in the last Ajax request */ _api_register( 'ajax.params()', function () { var ctx = this.context; if ( ctx.length > 0 ) { return ctx[0].oAjaxData; } // else return undefined; } ); /** * Reload tables from the Ajax data source. Note that this function will * automatically re-draw the table when the remote data has been loaded. * * @param {boolean} [reset=true] Reset (default) or hold the current paging * position. A full re-sort and re-filter is performed when this method is * called, which is why the pagination reset is the default action. * @returns {DataTables.Api} this */ _api_register( 'ajax.reload()', function ( callback, resetPaging ) { return this.iterator( 'table', function (settings) { __reload( settings, resetPaging===false, callback ); } ); } ); /** * Get the current Ajax URL. Note that this returns the URL from the first * table in the current context. * * @return {string} Current Ajax source URL *//** * Set the Ajax URL. Note that this will set the URL for all tables in the * current context. * * @param {string} url URL to set. * @returns {DataTables.Api} this */ _api_register( 'ajax.url()', function ( url ) { var ctx = this.context; if ( url === undefined ) { // get if ( ctx.length === 0 ) { return undefined; } ctx = ctx[0]; return ctx.ajax ? $.isPlainObject( ctx.ajax ) ? ctx.ajax.url : ctx.ajax : ctx.sAjaxSource; } // set return this.iterator( 'table', function ( settings ) { if ( $.isPlainObject( settings.ajax ) ) { settings.ajax.url = url; } else { settings.ajax = url; } // No need to consider sAjaxSource here since DataTables gives priority // to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any // value of `sAjaxSource` redundant. } ); } ); /** * Load data from the newly set Ajax URL. Note that this method is only * available when `ajax.url()` is used to set a URL. Additionally, this method * has the same effect as calling `ajax.reload()` but is provided for * convenience when setting a new URL. Like `ajax.reload()` it will * automatically redraw the table once the remote data has been loaded. * * @returns {DataTables.Api} this */ _api_register( 'ajax.url().load()', function ( callback, resetPaging ) { // Same as a reload, but makes sense to present it for easy access after a // url change return this.iterator( 'table', function ( ctx ) { __reload( ctx, resetPaging===false, callback ); } ); } ); var _selector_run = function ( selector, select ) { var out = [], res, a, i, ien, j, jen, selectorType = typeof selector; // Can't just check for isArray here, as an API or jQuery instance might be // given with their array like look if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) { selector = [ selector ]; } for ( i=0, ien=selector.length ; i<ien ; i++ ) { a = selector[i] && selector[i].split ? selector[i].split(',') : [ selector[i] ]; for ( j=0, jen=a.length ; j<jen ; j++ ) { res = select( typeof a[j] === 'string' ? $.trim(a[j]) : a[j] ); if ( res && res.length ) { out.push.apply( out, res ); } } } return out; }; var _selector_opts = function ( opts ) { if ( ! opts ) { opts = {}; } // Backwards compatibility for 1.9- which used the terminology filter rather // than search if ( opts.filter && ! opts.search ) { opts.search = opts.filter; } return { search: opts.search || 'none', order: opts.order || 'current', page: opts.page || 'all' }; }; var _selector_first = function ( inst ) { // Reduce the API instance to the first item found for ( var i=0, ien=inst.length ; i<ien ; i++ ) { if ( inst[i].length > 0 ) { // Assign the first element to the first item in the instance // and truncate the instance and context inst[0] = inst[i]; inst.length = 1; inst.context = [ inst.context[i] ]; return inst; } } // Not found - return an empty instance inst.length = 0; return inst; }; var _selector_row_indexes = function ( settings, opts ) { var i, ien, tmp, a=[], displayFiltered = settings.aiDisplay, displayMaster = settings.aiDisplayMaster; var search = opts.search, // none, applied, removed order = opts.order, // applied, current, index (original - compatibility with 1.9) page = opts.page; // all, current if ( _fnDataSource( settings ) == 'ssp' ) { // In server-side processing mode, most options are irrelevant since // rows not shown don't exist and the index order is the applied order // Removed is a special case - for consistency just return an empty // array return search === 'removed' ? [] : _range( 0, displayMaster.length ); } else if ( page == 'current' ) { // Current page implies that order=current and fitler=applied, since it is // fairly senseless otherwise, regardless of what order and search actually // are for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) { a.push( displayFiltered[i] ); } } else if ( order == 'current' || order == 'applied' ) { a = search == 'none' ? displayMaster.slice() : // no search search == 'applied' ? displayFiltered.slice() : // applied search $.map( displayMaster, function (el, i) { // removed search return $.inArray( el, displayFiltered ) === -1 ? el : null; } ); } else if ( order == 'index' || order == 'original' ) { for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) { if ( search == 'none' ) { a.push( i ); } else { // applied | removed tmp = $.inArray( i, displayFiltered ); if ((tmp === -1 && search == 'removed') || (tmp >= 0 && search == 'applied') ) { a.push( i ); } } } } return a; }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Rows * * {} - no selector - use all available rows * {integer} - row aoData index * {node} - TR node * {string} - jQuery selector to apply to the TR elements * {array} - jQuery array of nodes, or simply an array of TR nodes * */ var __row_selector = function ( settings, selector, opts ) { return _selector_run( selector, function ( sel ) { var selInt = _intVal( sel ); var i, ien; // Short cut - selector is a number and no options provided (default is // all records, so no need to check if the index is in there, since it // must be - dev error if the index doesn't exist). if ( selInt !== null && ! opts ) { return [ selInt ]; } var rows = _selector_row_indexes( settings, opts ); if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) { // Selector - integer return [ selInt ]; } else if ( ! sel ) { // Selector - none return rows; } // Selector - function if ( typeof sel === 'function' ) { return $.map( rows, function (idx) { var row = settings.aoData[ idx ]; return sel( idx, row._aData, row.nTr ) ? idx : null; } ); } // Get nodes in the order from the `rows` array with null values removed var nodes = _removeEmpty( _pluck_order( settings.aoData, rows, 'nTr' ) ); // Selector - node if ( sel.nodeName ) { if ( $.inArray( sel, nodes ) !== -1 ) { return [ sel._DT_RowIndex ]; // sel is a TR node that is in the table // and DataTables adds a prop for fast lookup } } // Selector - jQuery selector string, array of nodes or jQuery object/ // As jQuery's .filter() allows jQuery objects to be passed in filter, // it also allows arrays, so this will cope with all three options return $(nodes) .filter( sel ) .map( function () { return this._DT_RowIndex; } ) .toArray(); } ); }; /** * */ _api_register( 'rows()', function ( selector, opts ) { // argument shifting if ( selector === undefined ) { selector = ''; } else if ( $.isPlainObject( selector ) ) { opts = selector; selector = ''; } opts = _selector_opts( opts ); var inst = this.iterator( 'table', function ( settings ) { return __row_selector( settings, selector, opts ); }, 1 ); // Want argument shifting here and in __row_selector? inst.selector.rows = selector; inst.selector.opts = opts; return inst; } ); _api_register( 'rows().nodes()', function () { return this.iterator( 'row', function ( settings, row ) { return settings.aoData[ row ].nTr || undefined; }, 1 ); } ); _api_register( 'rows().data()', function () { return this.iterator( true, 'rows', function ( settings, rows ) { return _pluck_order( settings.aoData, rows, '_aData' ); }, 1 ); } ); _api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) { return this.iterator( 'row', function ( settings, row ) { var r = settings.aoData[ row ]; return type === 'search' ? r._aFilterData : r._aSortData; }, 1 ); } ); _api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) { return this.iterator( 'row', function ( settings, row ) { _fnInvalidate( settings, row, src ); } ); } ); _api_registerPlural( 'rows().indexes()', 'row().index()', function () { return this.iterator( 'row', function ( settings, row ) { return row; }, 1 ); } ); _api_registerPlural( 'rows().remove()', 'row().remove()', function () { var that = this; return this.iterator( 'row', function ( settings, row, thatIdx ) { var data = settings.aoData; data.splice( row, 1 ); // Update the _DT_RowIndex parameter on all rows in the table for ( var i=0, ien=data.length ; i<ien ; i++ ) { if ( data[i].nTr !== null ) { data[i].nTr._DT_RowIndex = i; } } // Remove the target row from the search array var displayIndex = $.inArray( row, settings.aiDisplay ); // Delete from the display arrays _fnDeleteIndex( settings.aiDisplayMaster, row ); _fnDeleteIndex( settings.aiDisplay, row ); _fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes // Check for an 'overflow' they case for displaying the table _fnLengthOverflow( settings ); } ); } ); _api_register( 'rows.add()', function ( rows ) { var newRows = this.iterator( 'table', function ( settings ) { var row, i, ien; var out = []; for ( i=0, ien=rows.length ; i<ien ; i++ ) { row = rows[i]; if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) { out.push( _fnAddTr( settings, row )[0] ); } else { out.push( _fnAddData( settings, row ) ); } } return out; }, 1 ); // Return an Api.rows() extended instance, so rows().nodes() etc can be used var modRows = this.rows( -1 ); modRows.pop(); modRows.push.apply( modRows, newRows.toArray() ); return modRows; } ); /** * */ _api_register( 'row()', function ( selector, opts ) { return _selector_first( this.rows( selector, opts ) ); } ); _api_register( 'row().data()', function ( data ) { var ctx = this.context; if ( data === undefined ) { // Get return ctx.length && this.length ? ctx[0].aoData[ this[0] ]._aData : undefined; } // Set ctx[0].aoData[ this[0] ]._aData = data; // Automatically invalidate _fnInvalidate( ctx[0], this[0], 'data' ); return this; } ); _api_register( 'row().node()', function () { var ctx = this.context; return ctx.length && this.length ? ctx[0].aoData[ this[0] ].nTr || null : null; } ); _api_register( 'row.add()', function ( row ) { // Allow a jQuery object to be passed in - only a single row is added from // it though - the first element in the set if ( row instanceof $ && row.length ) { row = row[0]; } var rows = this.iterator( 'table', function ( settings ) { if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) { return _fnAddTr( settings, row )[0]; } return _fnAddData( settings, row ); } ); // Return an Api.rows() extended instance, with the newly added row selected return this.row( rows[0] ); } ); var __details_add = function ( ctx, row, data, klass ) { // Convert to array of TR elements var rows = []; var addRow = function ( r, k ) { // If we get a TR element, then just add it directly - up to the dev // to add the correct number of columns etc if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) { rows.push( r ); } else { // Otherwise create a row with a wrapper var created = $('<tr><td/></tr>').addClass( k ); $('td', created) .addClass( k ) .html( r ) [0].colSpan = _fnVisbleColumns( ctx ); rows.push( created[0] ); } }; if ( $.isArray( data ) || data instanceof $ ) { for ( var i=0, ien=data.length ; i<ien ; i++ ) { addRow( data[i], klass ); } } else { addRow( data, klass ); } if ( row._details ) { row._details.remove(); } row._details = $(rows); // If the children were already shown, that state should be retained if ( row._detailsShow ) { row._details.insertAfter( row.nTr ); } }; var __details_remove = function ( api, idx ) { var ctx = api.context; if ( ctx.length ) { var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ]; if ( row._details ) { row._details.remove(); row._detailsShow = undefined; row._details = undefined; } } }; var __details_display = function ( api, show ) { var ctx = api.context; if ( ctx.length && api.length ) { var row = ctx[0].aoData[ api[0] ]; if ( row._details ) { row._detailsShow = show; if ( show ) { row._details.insertAfter( row.nTr ); } else { row._details.detach(); } __details_events( ctx[0] ); } } }; var __details_events = function ( settings ) { var api = new _Api( settings ); var namespace = '.dt.DT_details'; var drawEvent = 'draw'+namespace; var colvisEvent = 'column-visibility'+namespace; var destroyEvent = 'destroy'+namespace; var data = settings.aoData; api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent ); if ( _pluck( data, '_details' ).length > 0 ) { // On each draw, insert the required elements into the document api.on( drawEvent, function ( e, ctx ) { if ( settings !== ctx ) { return; } api.rows( {page:'current'} ).eq(0).each( function (idx) { // Internal data grab var row = data[ idx ]; if ( row._detailsShow ) { row._details.insertAfter( row.nTr ); } } ); } ); // Column visibility change - update the colspan api.on( colvisEvent, function ( e, ctx, idx, vis ) { if ( settings !== ctx ) { return; } // Update the colspan for the details rows (note, only if it already has // a colspan) var row, visible = _fnVisbleColumns( ctx ); for ( var i=0, ien=data.length ; i<ien ; i++ ) { row = data[i]; if ( row._details ) { row._details.children('td[colspan]').attr('colspan', visible ); } } } ); // Table destroyed - nuke any child rows api.on( destroyEvent, function ( e, ctx ) { if ( settings !== ctx ) { return; } for ( var i=0, ien=data.length ; i<ien ; i++ ) { if ( data[i]._details ) { __details_remove( api, i ); } } } ); } }; // Strings for the method names to help minification var _emp = ''; var _child_obj = _emp+'row().child'; var _child_mth = _child_obj+'()'; // data can be: // tr // string // jQuery or array of any of the above _api_register( _child_mth, function ( data, klass ) { var ctx = this.context; if ( data === undefined ) { // get return ctx.length && this.length ? ctx[0].aoData[ this[0] ]._details : undefined; } else if ( data === true ) { // show this.child.show(); } else if ( data === false ) { // remove __details_remove( this ); } else if ( ctx.length && this.length ) { // set __details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass ); } return this; } ); _api_register( [ _child_obj+'.show()', _child_mth+'.show()' // only when `child()` was called with parameters (without ], function ( show ) { // it returns an object and this method is not executed) __details_display( this, true ); return this; } ); _api_register( [ _child_obj+'.hide()', _child_mth+'.hide()' // only when `child()` was called with parameters (without ], function () { // it returns an object and this method is not executed) __details_display( this, false ); return this; } ); _api_register( [ _child_obj+'.remove()', _child_mth+'.remove()' // only when `child()` was called with parameters (without ], function () { // it returns an object and this method is not executed) __details_remove( this ); return this; } ); _api_register( _child_obj+'.isShown()', function () { var ctx = this.context; if ( ctx.length && this.length ) { // _detailsShown as false or undefined will fall through to return false return ctx[0].aoData[ this[0] ]._detailsShow || false; } return false; } ); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Columns * * {integer} - column index (>=0 count from left, <0 count from right) * "{integer}:visIdx" - visible column index (i.e. translate to column index) (>=0 count from left, <0 count from right) * "{integer}:visible" - alias for {integer}:visIdx (>=0 count from left, <0 count from right) * "{string}:name" - column name * "{string}" - jQuery selector on column header nodes * */ // can be an array of these items, comma separated list, or an array of comma // separated lists var __re_column_selector = /^(.+):(name|visIdx|visible)$/; // r1 and r2 are redundant - but it means that the parameters match for the // iterator callback in columns().data() var __columnData = function ( settings, column, r1, r2, rows ) { var a = []; for ( var row=0, ien=rows.length ; row<ien ; row++ ) { a.push( _fnGetCellData( settings, rows[row], column ) ); } return a; }; var __column_selector = function ( settings, selector, opts ) { var columns = settings.aoColumns, names = _pluck( columns, 'sName' ), nodes = _pluck( columns, 'nTh' ); return _selector_run( selector, function ( s ) { var selInt = _intVal( s ); // Selector - all if ( s === '' ) { return _range( columns.length ); } // Selector - index if ( selInt !== null ) { return [ selInt >= 0 ? selInt : // Count from left columns.length + selInt // Count from right (+ because its a negative value) ]; } // Selector = function if ( typeof s === 'function' ) { var rows = _selector_row_indexes( settings, opts ); return $.map( columns, function (col, idx) { return s( idx, __columnData( settings, idx, 0, 0, rows ), nodes[ idx ] ) ? idx : null; } ); } // jQuery or string selector var match = typeof s === 'string' ? s.match( __re_column_selector ) : ''; if ( match ) { switch( match[2] ) { case 'visIdx': case 'visible': var idx = parseInt( match[1], 10 ); // Visible index given, convert to column index if ( idx < 0 ) { // Counting from the right var visColumns = $.map( columns, function (col,i) { return col.bVisible ? i : null; } ); return [ visColumns[ visColumns.length + idx ] ]; } // Counting from the left return [ _fnVisibleToColumnIndex( settings, idx ) ]; case 'name': // match by name. `names` is column index complete and in order return $.map( names, function (name, i) { return name === match[1] ? i : null; } ); } } else { // jQuery selector on the TH elements for the columns return $( nodes ) .filter( s ) .map( function () { return $.inArray( this, nodes ); // `nodes` is column index complete and in order } ) .toArray(); } } ); }; var __setColumnVis = function ( settings, column, vis, recalc ) { var cols = settings.aoColumns, col = cols[ column ], data = settings.aoData, row, cells, i, ien, tr; // Get if ( vis === undefined ) { return col.bVisible; } // Set // No change if ( col.bVisible === vis ) { return; } if ( vis ) { // Insert column // Need to decide if we should use appendChild or insertBefore var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 ); for ( i=0, ien=data.length ; i<ien ; i++ ) { tr = data[i].nTr; cells = data[i].anCells; if ( tr ) { // insertBefore can act like appendChild if 2nd arg is null tr.insertBefore( cells[ column ], cells[ insertBefore ] || null ); } } } else { // Remove column $( _pluck( settings.aoData, 'anCells', column ) ).detach(); } // Common actions col.bVisible = vis; _fnDrawHead( settings, settings.aoHeader ); _fnDrawHead( settings, settings.aoFooter ); if ( recalc === undefined || recalc ) { // Automatically adjust column sizing _fnAdjustColumnSizing( settings ); // Realign columns for scrolling if ( settings.oScroll.sX || settings.oScroll.sY ) { _fnScrollDraw( settings ); } } _fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis] ); _fnSaveState( settings ); }; /** * */ _api_register( 'columns()', function ( selector, opts ) { // argument shifting if ( selector === undefined ) { selector = ''; } else if ( $.isPlainObject( selector ) ) { opts = selector; selector = ''; } opts = _selector_opts( opts ); var inst = this.iterator( 'table', function ( settings ) { return __column_selector( settings, selector, opts ); }, 1 ); // Want argument shifting here and in _row_selector? inst.selector.cols = selector; inst.selector.opts = opts; return inst; } ); /** * */ _api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) { return this.iterator( 'column', function ( settings, column ) { return settings.aoColumns[column].nTh; }, 1 ); } ); /** * */ _api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) { return this.iterator( 'column', function ( settings, column ) { return settings.aoColumns[column].nTf; }, 1 ); } ); /** * */ _api_registerPlural( 'columns().data()', 'column().data()', function () { return this.iterator( 'column-rows', __columnData, 1 ); } ); _api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () { return this.iterator( 'column', function ( settings, column ) { return settings.aoColumns[column].mData; }, 1 ); } ); _api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) { return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) { return _pluck_order( settings.aoData, rows, type === 'search' ? '_aFilterData' : '_aSortData', column ); }, 1 ); } ); _api_registerPlural( 'columns().nodes()', 'column().nodes()', function () { return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) { return _pluck_order( settings.aoData, rows, 'anCells', column ) ; }, 1 ); } ); _api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) { return this.iterator( 'column', function ( settings, column ) { if ( vis === undefined ) { return settings.aoColumns[ column ].bVisible; } // else __setColumnVis( settings, column, vis, calc ); } ); } ); _api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) { return this.iterator( 'column', function ( settings, column ) { return type === 'visible' ? _fnColumnIndexToVisible( settings, column ) : column; }, 1 ); } ); // _api_register( 'columns().show()', function () { // var selector = this.selector; // return this.columns( selector.cols, selector.opts ).visible( true ); // } ); // _api_register( 'columns().hide()', function () { // var selector = this.selector; // return this.columns( selector.cols, selector.opts ).visible( false ); // } ); _api_register( 'columns.adjust()', function () { return this.iterator( 'table', function ( settings ) { _fnAdjustColumnSizing( settings ); }, 1 ); } ); // Convert from one column index type, to another type _api_register( 'column.index()', function ( type, idx ) { if ( this.context.length !== 0 ) { var ctx = this.context[0]; if ( type === 'fromVisible' || type === 'toData' ) { return _fnVisibleToColumnIndex( ctx, idx ); } else if ( type === 'fromData' || type === 'toVisible' ) { return _fnColumnIndexToVisible( ctx, idx ); } } } ); _api_register( 'column()', function ( selector, opts ) { return _selector_first( this.columns( selector, opts ) ); } ); var __cell_selector = function ( settings, selector, opts ) { var data = settings.aoData; var rows = _selector_row_indexes( settings, opts ); var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) ); var allCells = $( [].concat.apply([], cells) ); var row; var columns = settings.aoColumns.length; var a, i, ien, j, o, host; return _selector_run( selector, function ( s ) { var fnSelector = typeof s === 'function'; if ( s === null || s === undefined || fnSelector ) { // All cells and function selectors a = []; for ( i=0, ien=rows.length ; i<ien ; i++ ) { row = rows[i]; for ( j=0 ; j<columns ; j++ ) { o = { row: row, column: j }; if ( fnSelector ) { // Selector - function host = settings.aoData[ row ]; if ( s( o, _fnGetCellData(settings, row, j), host.anCells[j] ) ) { a.push( o ); } } else { // Selector - all a.push( o ); } } } return a; } // Selector - index if ( $.isPlainObject( s ) ) { return [s]; } // Selector - jQuery filtered cells return allCells .filter( s ) .map( function (i, el) { row = el.parentNode._DT_RowIndex; return { row: row, column: $.inArray( el, data[ row ].anCells ) }; } ) .toArray(); } ); }; _api_register( 'cells()', function ( rowSelector, columnSelector, opts ) { // Argument shifting if ( $.isPlainObject( rowSelector ) ) { // Indexes if ( typeof rowSelector.row !== undefined ) { opts = columnSelector; columnSelector = null; } else { opts = rowSelector; rowSelector = null; } } if ( $.isPlainObject( columnSelector ) ) { opts = columnSelector; columnSelector = null; } // Cell selector if ( columnSelector === null || columnSelector === undefined ) { return this.iterator( 'table', function ( settings ) { return __cell_selector( settings, rowSelector, _selector_opts( opts ) ); } ); } // Row + column selector var columns = this.columns( columnSelector, opts ); var rows = this.rows( rowSelector, opts ); var a, i, ien, j, jen; var cells = this.iterator( 'table', function ( settings, idx ) { a = []; for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) { for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) { a.push( { row: rows[idx][i], column: columns[idx][j] } ); } } return a; }, 1 ); $.extend( cells.selector, { cols: columnSelector, rows: rowSelector, opts: opts } ); return cells; } ); _api_registerPlural( 'cells().nodes()', 'cell().node()', function () { return this.iterator( 'cell', function ( settings, row, column ) { var cells = settings.aoData[ row ].anCells; return cells ? cells[ column ] : undefined; }, 1 ); } ); _api_register( 'cells().data()', function () { return this.iterator( 'cell', function ( settings, row, column ) { return _fnGetCellData( settings, row, column ); }, 1 ); } ); _api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) { type = type === 'search' ? '_aFilterData' : '_aSortData'; return this.iterator( 'cell', function ( settings, row, column ) { return settings.aoData[ row ][ type ][ column ]; }, 1 ); } ); _api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) { return this.iterator( 'cell', function ( settings, row, column ) { return _fnGetCellData( settings, row, column, type ); }, 1 ); } ); _api_registerPlural( 'cells().indexes()', 'cell().index()', function () { return this.iterator( 'cell', function ( settings, row, column ) { return { row: row, column: column, columnVisible: _fnColumnIndexToVisible( settings, column ) }; }, 1 ); } ); _api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) { return this.iterator( 'cell', function ( settings, row, column ) { _fnInvalidate( settings, row, src, column ); } ); } ); _api_register( 'cell()', function ( rowSelector, columnSelector, opts ) { return _selector_first( this.cells( rowSelector, columnSelector, opts ) ); } ); _api_register( 'cell().data()', function ( data ) { var ctx = this.context; var cell = this[0]; if ( data === undefined ) { // Get return ctx.length && cell.length ? _fnGetCellData( ctx[0], cell[0].row, cell[0].column ) : undefined; } // Set _fnSetCellData( ctx[0], cell[0].row, cell[0].column, data ); _fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column ); return this; } ); /** * Get current ordering (sorting) that has been applied to the table. * * @returns {array} 2D array containing the sorting information for the first * table in the current context. Each element in the parent array represents * a column being sorted upon (i.e. multi-sorting with two columns would have * 2 inner arrays). The inner arrays may have 2 or 3 elements. The first is * the column index that the sorting condition applies to, the second is the * direction of the sort (`desc` or `asc`) and, optionally, the third is the * index of the sorting order from the `column.sorting` initialisation array. *//** * Set the ordering for the table. * * @param {integer} order Column index to sort upon. * @param {string} direction Direction of the sort to be applied (`asc` or `desc`) * @returns {DataTables.Api} this *//** * Set the ordering for the table. * * @param {array} order 1D array of sorting information to be applied. * @param {array} [...] Optional additional sorting conditions * @returns {DataTables.Api} this *//** * Set the ordering for the table. * * @param {array} order 2D array of sorting information to be applied. * @returns {DataTables.Api} this */ _api_register( 'order()', function ( order, dir ) { var ctx = this.context; if ( order === undefined ) { // get return ctx.length !== 0 ? ctx[0].aaSorting : undefined; } // set if ( typeof order === 'number' ) { // Simple column / direction passed in order = [ [ order, dir ] ]; } else if ( ! $.isArray( order[0] ) ) { // Arguments passed in (list of 1D arrays) order = Array.prototype.slice.call( arguments ); } // otherwise a 2D array was passed in return this.iterator( 'table', function ( settings ) { settings.aaSorting = order.slice(); } ); } ); /** * Attach a sort listener to an element for a given column * * @param {node|jQuery|string} node Identifier for the element(s) to attach the * listener to. This can take the form of a single DOM node, a jQuery * collection of nodes or a jQuery selector which will identify the node(s). * @param {integer} column the column that a click on this node will sort on * @param {function} [callback] callback function when sort is run * @returns {DataTables.Api} this */ _api_register( 'order.listener()', function ( node, column, callback ) { return this.iterator( 'table', function ( settings ) { _fnSortAttachListener( settings, node, column, callback ); } ); } ); // Order by the selected column(s) _api_register( [ 'columns().order()', 'column().order()' ], function ( dir ) { var that = this; return this.iterator( 'table', function ( settings, i ) { var sort = []; $.each( that[i], function (j, col) { sort.push( [ col, dir ] ); } ); settings.aaSorting = sort; } ); } ); _api_register( 'search()', function ( input, regex, smart, caseInsen ) { var ctx = this.context; if ( input === undefined ) { // get return ctx.length !== 0 ? ctx[0].oPreviousSearch.sSearch : undefined; } // set return this.iterator( 'table', function ( settings ) { if ( ! settings.oFeatures.bFilter ) { return; } _fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, { "sSearch": input+"", "bRegex": regex === null ? false : regex, "bSmart": smart === null ? true : smart, "bCaseInsensitive": caseInsen === null ? true : caseInsen } ), 1 ); } ); } ); _api_registerPlural( 'columns().search()', 'column().search()', function ( input, regex, smart, caseInsen ) { return this.iterator( 'column', function ( settings, column ) { var preSearch = settings.aoPreSearchCols; if ( input === undefined ) { // get return preSearch[ column ].sSearch; } // set if ( ! settings.oFeatures.bFilter ) { return; } $.extend( preSearch[ column ], { "sSearch": input+"", "bRegex": regex === null ? false : regex, "bSmart": smart === null ? true : smart, "bCaseInsensitive": caseInsen === null ? true : caseInsen } ); _fnFilterComplete( settings, settings.oPreviousSearch, 1 ); } ); } ); /* * State API methods */ _api_register( 'state()', function () { return this.context.length ? this.context[0].oSavedState : null; } ); _api_register( 'state.clear()', function () { return this.iterator( 'table', function ( settings ) { // Save an empty object settings.fnStateSaveCallback.call( settings.oInstance, settings, {} ); } ); } ); _api_register( 'state.loaded()', function () { return this.context.length ? this.context[0].oLoadedState : null; } ); _api_register( 'state.save()', function () { return this.iterator( 'table', function ( settings ) { _fnSaveState( settings ); } ); } ); /** * Provide a common method for plug-ins to check the version of DataTables being * used, in order to ensure compatibility. * * @param {string} version Version string to check for, in the format "X.Y.Z". * Note that the formats "X" and "X.Y" are also acceptable. * @returns {boolean} true if this version of DataTables is greater or equal to * the required version, or false if this version of DataTales is not * suitable * @static * @dtopt API-Static * * @example * alert( $.fn.dataTable.versionCheck( '1.9.0' ) ); */ DataTable.versionCheck = DataTable.fnVersionCheck = function( version ) { var aThis = DataTable.version.split('.'); var aThat = version.split('.'); var iThis, iThat; for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) { iThis = parseInt( aThis[i], 10 ) || 0; iThat = parseInt( aThat[i], 10 ) || 0; // Parts are the same, keep comparing if (iThis === iThat) { continue; } // Parts are different, return immediately return iThis > iThat; } return true; }; /** * Check if a `<table>` node is a DataTable table already or not. * * @param {node|jquery|string} table Table node, jQuery object or jQuery * selector for the table to test. Note that if more than more than one * table is passed on, only the first will be checked * @returns {boolean} true the table given is a DataTable, or false otherwise * @static * @dtopt API-Static * * @example * if ( ! $.fn.DataTable.isDataTable( '#example' ) ) { * $('#example').dataTable(); * } */ DataTable.isDataTable = DataTable.fnIsDataTable = function ( table ) { var t = $(table).get(0); var is = false; $.each( DataTable.settings, function (i, o) { if ( o.nTable === t || o.nScrollHead === t || o.nScrollFoot === t ) { is = true; } } ); return is; }; /** * Get all DataTable tables that have been initialised - optionally you can * select to get only currently visible tables. * * @param {boolean} [visible=false] Flag to indicate if you want all (default) * or visible tables only. * @returns {array} Array of `table` nodes (not DataTable instances) which are * DataTables * @static * @dtopt API-Static * * @example * $.each( $.fn.dataTable.tables(true), function () { * $(table).DataTable().columns.adjust(); * } ); */ DataTable.tables = DataTable.fnTables = function ( visible ) { return $.map( DataTable.settings, function (o) { if ( !visible || (visible && $(o.nTable).is(':visible')) ) { return o.nTable; } } ); }; /** * DataTables utility methods * * This namespace provides helper methods that DataTables uses internally to * create a DataTable, but which are not exclusively used only for DataTables. * These methods can be used by extension authors to save the duplication of * code. * * @namespace */ DataTable.util = { /** * Throttle the calls to a function. Arguments and context are maintained * for the throttled function. * * @param {function} fn Function to be called * @param {integer} freq Call frequency in mS * @return {function} Wrapped function */ throttle: _fnThrottle, /** * Escape a string such that it can be used in a regular expression * * @param {string} sVal string to escape * @returns {string} escaped string */ escapeRegex: _fnEscapeRegex }; /** * Convert from camel case parameters to Hungarian notation. This is made public * for the extensions to provide the same ability as DataTables core to accept * either the 1.9 style Hungarian notation, or the 1.10+ style camelCase * parameters. * * @param {object} src The model object which holds all parameters that can be * mapped. * @param {object} user The object to convert from camel case to Hungarian. * @param {boolean} force When set to `true`, properties which already have a * Hungarian value in the `user` object will be overwritten. Otherwise they * won't be. */ DataTable.camelToHungarian = _fnCamelToHungarian; /** * */ _api_register( '$()', function ( selector, opts ) { var rows = this.rows( opts ).nodes(), // Get all rows jqRows = $(rows); return $( [].concat( jqRows.filter( selector ).toArray(), jqRows.find( selector ).toArray() ) ); } ); // jQuery functions to operate on the tables $.each( [ 'on', 'one', 'off' ], function (i, key) { _api_register( key+'()', function ( /* event, handler */ ) { var args = Array.prototype.slice.call(arguments); // Add the `dt` namespace automatically if it isn't already present if ( ! args[0].match(/\.dt\b/) ) { args[0] += '.dt'; } var inst = $( this.tables().nodes() ); inst[key].apply( inst, args ); return this; } ); } ); _api_register( 'clear()', function () { return this.iterator( 'table', function ( settings ) { _fnClearTable( settings ); } ); } ); _api_register( 'settings()', function () { return new _Api( this.context, this.context ); } ); _api_register( 'data()', function () { return this.iterator( 'table', function ( settings ) { return _pluck( settings.aoData, '_aData' ); } ).flatten(); } ); _api_register( 'destroy()', function ( remove ) { remove = remove || false; return this.iterator( 'table', function ( settings ) { var orig = settings.nTableWrapper.parentNode; var classes = settings.oClasses; var table = settings.nTable; var tbody = settings.nTBody; var thead = settings.nTHead; var tfoot = settings.nTFoot; var jqTable = $(table); var jqTbody = $(tbody); var jqWrapper = $(settings.nTableWrapper); var rows = $.map( settings.aoData, function (r) { return r.nTr; } ); var i, ien; // Flag to note that the table is currently being destroyed - no action // should be taken settings.bDestroying = true; // Fire off the destroy callbacks for plug-ins etc _fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] ); // If not being removed from the document, make all columns visible if ( ! remove ) { new _Api( settings ).columns().visible( true ); } // Blitz all `DT` namespaced events (these are internal events, the // lowercase, `dt` events are user subscribed and they are responsible // for removing them jqWrapper.unbind('.DT').find(':not(tbody *)').unbind('.DT'); $(window).unbind('.DT-'+settings.sInstance); // When scrolling we had to break the table up - restore it if ( table != thead.parentNode ) { jqTable.children('thead').detach(); jqTable.append( thead ); } if ( tfoot && table != tfoot.parentNode ) { jqTable.children('tfoot').detach(); jqTable.append( tfoot ); } // Remove the DataTables generated nodes, events and classes jqTable.detach(); jqWrapper.detach(); settings.aaSorting = []; settings.aaSortingFixed = []; _fnSortingClasses( settings ); $( rows ).removeClass( settings.asStripeClasses.join(' ') ); $('th, td', thead).removeClass( classes.sSortable+' '+ classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone ); if ( settings.bJUI ) { $('th span.'+classes.sSortIcon+ ', td span.'+classes.sSortIcon, thead).detach(); $('th, td', thead).each( function () { var wrapper = $('div.'+classes.sSortJUIWrapper, this); $(this).append( wrapper.contents() ); wrapper.detach(); } ); } if ( ! remove && orig ) { // insertBefore acts like appendChild if !arg[1] orig.insertBefore( table, settings.nTableReinsertBefore ); } // Add the TR elements back into the table in their original order jqTbody.children().detach(); jqTbody.append( rows ); // Restore the width of the original table - was read from the style property, // so we can restore directly to that jqTable .css( 'width', settings.sDestroyWidth ) .removeClass( classes.sTable ); // If the were originally stripe classes - then we add them back here. // Note this is not fool proof (for example if not all rows had stripe // classes - but it's a good effort without getting carried away ien = settings.asDestroyStripes.length; if ( ien ) { jqTbody.children().each( function (i) { $(this).addClass( settings.asDestroyStripes[i % ien] ); } ); } /* Remove the settings object from the settings array */ var idx = $.inArray( settings, DataTable.settings ); if ( idx !== -1 ) { DataTable.settings.splice( idx, 1 ); } } ); } ); /** * Version string for plug-ins to check compatibility. Allowed format is * `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used * only for non-release builds. See http://semver.org/ for more information. * @member * @type string * @default Version number */ DataTable.version = "1.10.4"; /** * Private data store, containing all of the settings objects that are * created for the tables on a given page. * * Note that the `DataTable.settings` object is aliased to * `jQuery.fn.dataTableExt` through which it may be accessed and * manipulated, or `jQuery.fn.dataTable.settings`. * @member * @type array * @default [] * @private */ DataTable.settings = []; /** * Object models container, for the various models that DataTables has * available to it. These models define the objects that are used to hold * the active state and configuration of the table. * @namespace */ DataTable.models = {}; /** * Template object for the way in which DataTables holds information about * search information for the global filter and individual column filters. * @namespace */ DataTable.models.oSearch = { /** * Flag to indicate if the filtering should be case insensitive or not * @type boolean * @default true */ "bCaseInsensitive": true, /** * Applied search term * @type string * @default <i>Empty string</i> */ "sSearch": "", /** * Flag to indicate if the search term should be interpreted as a * regular expression (true) or not (false) and therefore and special * regex characters escaped. * @type boolean * @default false */ "bRegex": false, /** * Flag to indicate if DataTables is to use its smart filtering or not. * @type boolean * @default true */ "bSmart": true }; /** * Template object for the way in which DataTables holds information about * each individual row. This is the object format used for the settings * aoData array. * @namespace */ DataTable.models.oRow = { /** * TR element for the row * @type node * @default null */ "nTr": null, /** * Array of TD elements for each row. This is null until the row has been * created. * @type array nodes * @default [] */ "anCells": null, /** * Data object from the original data source for the row. This is either * an array if using the traditional form of DataTables, or an object if * using mData options. The exact type will depend on the passed in * data from the data source, or will be an array if using DOM a data * source. * @type array|object * @default [] */ "_aData": [], /** * Sorting data cache - this array is ostensibly the same length as the * number of columns (although each index is generated only as it is * needed), and holds the data that is used for sorting each column in the * row. We do this cache generation at the start of the sort in order that * the formatting of the sort data need be done only once for each cell * per sort. This array should not be read from or written to by anything * other than the master sorting methods. * @type array * @default null * @private */ "_aSortData": null, /** * Per cell filtering data cache. As per the sort data cache, used to * increase the performance of the filtering in DataTables * @type array * @default null * @private */ "_aFilterData": null, /** * Filtering data cache. This is the same as the cell filtering cache, but * in this case a string rather than an array. This is easily computed with * a join on `_aFilterData`, but is provided as a cache so the join isn't * needed on every search (memory traded for performance) * @type array * @default null * @private */ "_sFilterRow": null, /** * Cache of the class name that DataTables has applied to the row, so we * can quickly look at this variable rather than needing to do a DOM check * on className for the nTr property. * @type string * @default <i>Empty string</i> * @private */ "_sRowStripe": "", /** * Denote if the original data source was from the DOM, or the data source * object. This is used for invalidating data, so DataTables can * automatically read data from the original source, unless uninstructed * otherwise. * @type string * @default null * @private */ "src": null }; /** * Template object for the column information object in DataTables. This object * is held in the settings aoColumns array and contains all the information that * DataTables needs about each individual column. * * Note that this object is related to {@link DataTable.defaults.column} * but this one is the internal data store for DataTables's cache of columns. * It should NOT be manipulated outside of DataTables. Any configuration should * be done through the initialisation options. * @namespace */ DataTable.models.oColumn = { /** * Column index. This could be worked out on-the-fly with $.inArray, but it * is faster to just hold it as a variable * @type integer * @default null */ "idx": null, /** * A list of the columns that sorting should occur on when this column * is sorted. That this property is an array allows multi-column sorting * to be defined for a column (for example first name / last name columns * would benefit from this). The values are integers pointing to the * columns to be sorted on (typically it will be a single integer pointing * at itself, but that doesn't need to be the case). * @type array */ "aDataSort": null, /** * Define the sorting directions that are applied to the column, in sequence * as the column is repeatedly sorted upon - i.e. the first value is used * as the sorting direction when the column if first sorted (clicked on). * Sort it again (click again) and it will move on to the next index. * Repeat until loop. * @type array */ "asSorting": null, /** * Flag to indicate if the column is searchable, and thus should be included * in the filtering or not. * @type boolean */ "bSearchable": null, /** * Flag to indicate if the column is sortable or not. * @type boolean */ "bSortable": null, /** * Flag to indicate if the column is currently visible in the table or not * @type boolean */ "bVisible": null, /** * Store for manual type assignment using the `column.type` option. This * is held in store so we can manipulate the column's `sType` property. * @type string * @default null * @private */ "_sManualType": null, /** * Flag to indicate if HTML5 data attributes should be used as the data * source for filtering or sorting. True is either are. * @type boolean * @default false * @private */ "_bAttrSrc": false, /** * Developer definable function that is called whenever a cell is created (Ajax source, * etc) or processed for input (DOM source). This can be used as a compliment to mRender * allowing you to modify the DOM element (add background colour for example) when the * element is available. * @type function * @param {element} nTd The TD node that has been created * @param {*} sData The Data for the cell * @param {array|object} oData The data for the whole row * @param {int} iRow The row index for the aoData data store * @default null */ "fnCreatedCell": null, /** * Function to get data from a cell in a column. You should <b>never</b> * access data directly through _aData internally in DataTables - always use * the method attached to this property. It allows mData to function as * required. This function is automatically assigned by the column * initialisation method * @type function * @param {array|object} oData The data array/object for the array * (i.e. aoData[]._aData) * @param {string} sSpecific The specific data type you want to get - * 'display', 'type' 'filter' 'sort' * @returns {*} The data for the cell from the given row's data * @default null */ "fnGetData": null, /** * Function to set data for a cell in the column. You should <b>never</b> * set the data directly to _aData internally in DataTables - always use * this method. It allows mData to function as required. This function * is automatically assigned by the column initialisation method * @type function * @param {array|object} oData The data array/object for the array * (i.e. aoData[]._aData) * @param {*} sValue Value to set * @default null */ "fnSetData": null, /** * Property to read the value for the cells in the column from the data * source array / object. If null, then the default content is used, if a * function is given then the return from the function is used. * @type function|int|string|null * @default null */ "mData": null, /** * Partner property to mData which is used (only when defined) to get * the data - i.e. it is basically the same as mData, but without the * 'set' option, and also the data fed to it is the result from mData. * This is the rendering method to match the data method of mData. * @type function|int|string|null * @default null */ "mRender": null, /** * Unique header TH/TD element for this column - this is what the sorting * listener is attached to (if sorting is enabled.) * @type node * @default null */ "nTh": null, /** * Unique footer TH/TD element for this column (if there is one). Not used * in DataTables as such, but can be used for plug-ins to reference the * footer for each column. * @type node * @default null */ "nTf": null, /** * The class to apply to all TD elements in the table's TBODY for the column * @type string * @default null */ "sClass": null, /** * When DataTables calculates the column widths to assign to each column, * it finds the longest string in each column and then constructs a * temporary table and reads the widths from that. The problem with this * is that "mmm" is much wider then "iiii", but the latter is a longer * string - thus the calculation can go wrong (doing it properly and putting * it into an DOM object and measuring that is horribly(!) slow). Thus as * a "work around" we provide this option. It will append its value to the * text that is found to be the longest string for the column - i.e. padding. * @type string */ "sContentPadding": null, /** * Allows a default value to be given for a column's data, and will be used * whenever a null data source is encountered (this can be because mData * is set to null, or because the data source itself is null). * @type string * @default null */ "sDefaultContent": null, /** * Name for the column, allowing reference to the column by name as well as * by index (needs a lookup to work by name). * @type string */ "sName": null, /** * Custom sorting data type - defines which of the available plug-ins in * afnSortData the custom sorting will use - if any is defined. * @type string * @default std */ "sSortDataType": 'std', /** * Class to be applied to the header element when sorting on this column * @type string * @default null */ "sSortingClass": null, /** * Class to be applied to the header element when sorting on this column - * when jQuery UI theming is used. * @type string * @default null */ "sSortingClassJUI": null, /** * Title of the column - what is seen in the TH element (nTh). * @type string */ "sTitle": null, /** * Column sorting and filtering type * @type string * @default null */ "sType": null, /** * Width of the column * @type string * @default null */ "sWidth": null, /** * Width of the column when it was first "encountered" * @type string * @default null */ "sWidthOrig": null }; /* * Developer note: The properties of the object below are given in Hungarian * notation, that was used as the interface for DataTables prior to v1.10, however * from v1.10 onwards the primary interface is camel case. In order to avoid * breaking backwards compatibility utterly with this change, the Hungarian * version is still, internally the primary interface, but is is not documented * - hence the @name tags in each doc comment. This allows a Javascript function * to create a map from Hungarian notation to camel case (going the other direction * would require each property to be listed, which would at around 3K to the size * of DataTables, while this method is about a 0.5K hit. * * Ultimately this does pave the way for Hungarian notation to be dropped * completely, but that is a massive amount of work and will break current * installs (therefore is on-hold until v2). */ /** * Initialisation options that can be given to DataTables at initialisation * time. * @namespace */ DataTable.defaults = { /** * An array of data to use for the table, passed in at initialisation which * will be used in preference to any data which is already in the DOM. This is * particularly useful for constructing tables purely in Javascript, for * example with a custom Ajax call. * @type array * @default null * * @dtopt Option * @name DataTable.defaults.data * * @example * // Using a 2D array data source * $(document).ready( function () { * $('#example').dataTable( { * "data": [ * ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'], * ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'], * ], * "columns": [ * { "title": "Engine" }, * { "title": "Browser" }, * { "title": "Platform" }, * { "title": "Version" }, * { "title": "Grade" } * ] * } ); * } ); * * @example * // Using an array of objects as a data source (`data`) * $(document).ready( function () { * $('#example').dataTable( { * "data": [ * { * "engine": "Trident", * "browser": "Internet Explorer 4.0", * "platform": "Win 95+", * "version": 4, * "grade": "X" * }, * { * "engine": "Trident", * "browser": "Internet Explorer 5.0", * "platform": "Win 95+", * "version": 5, * "grade": "C" * } * ], * "columns": [ * { "title": "Engine", "data": "engine" }, * { "title": "Browser", "data": "browser" }, * { "title": "Platform", "data": "platform" }, * { "title": "Version", "data": "version" }, * { "title": "Grade", "data": "grade" } * ] * } ); * } ); */ "aaData": null, /** * If ordering is enabled, then DataTables will perform a first pass sort on * initialisation. You can define which column(s) the sort is performed * upon, and the sorting direction, with this variable. The `sorting` array * should contain an array for each column to be sorted initially containing * the column's index and a direction string ('asc' or 'desc'). * @type array * @default [[0,'asc']] * * @dtopt Option * @name DataTable.defaults.order * * @example * // Sort by 3rd column first, and then 4th column * $(document).ready( function() { * $('#example').dataTable( { * "order": [[2,'asc'], [3,'desc']] * } ); * } ); * * // No initial sorting * $(document).ready( function() { * $('#example').dataTable( { * "order": [] * } ); * } ); */ "aaSorting": [[0,'asc']], /** * This parameter is basically identical to the `sorting` parameter, but * cannot be overridden by user interaction with the table. What this means * is that you could have a column (visible or hidden) which the sorting * will always be forced on first - any sorting after that (from the user) * will then be performed as required. This can be useful for grouping rows * together. * @type array * @default null * * @dtopt Option * @name DataTable.defaults.orderFixed * * @example * $(document).ready( function() { * $('#example').dataTable( { * "orderFixed": [[0,'asc']] * } ); * } ) */ "aaSortingFixed": [], /** * DataTables can be instructed to load data to display in the table from a * Ajax source. This option defines how that Ajax call is made and where to. * * The `ajax` property has three different modes of operation, depending on * how it is defined. These are: * * * `string` - Set the URL from where the data should be loaded from. * * `object` - Define properties for `jQuery.ajax`. * * `function` - Custom data get function * * `string` * -------- * * As a string, the `ajax` property simply defines the URL from which * DataTables will load data. * * `object` * -------- * * As an object, the parameters in the object are passed to * [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control * of the Ajax request. DataTables has a number of default parameters which * you can override using this option. Please refer to the jQuery * documentation for a full description of the options available, although * the following parameters provide additional options in DataTables or * require special consideration: * * * `data` - As with jQuery, `data` can be provided as an object, but it * can also be used as a function to manipulate the data DataTables sends * to the server. The function takes a single parameter, an object of * parameters with the values that DataTables has readied for sending. An * object may be returned which will be merged into the DataTables * defaults, or you can add the items to the object that was passed in and * not return anything from the function. This supersedes `fnServerParams` * from DataTables 1.9-. * * * `dataSrc` - By default DataTables will look for the property `data` (or * `aaData` for compatibility with DataTables 1.9-) when obtaining data * from an Ajax source or for server-side processing - this parameter * allows that property to be changed. You can use Javascript dotted * object notation to get a data source for multiple levels of nesting, or * it my be used as a function. As a function it takes a single parameter, * the JSON returned from the server, which can be manipulated as * required, with the returned value being that used by DataTables as the * data source for the table. This supersedes `sAjaxDataProp` from * DataTables 1.9-. * * * `success` - Should not be overridden it is used internally in * DataTables. To manipulate / transform the data returned by the server * use `ajax.dataSrc`, or use `ajax` as a function (see below). * * `function` * ---------- * * As a function, making the Ajax call is left up to yourself allowing * complete control of the Ajax request. Indeed, if desired, a method other * than Ajax could be used to obtain the required data, such as Web storage * or an AIR database. * * The function is given four parameters and no return is required. The * parameters are: * * 1. _object_ - Data to send to the server * 2. _function_ - Callback function that must be executed when the required * data has been obtained. That data should be passed into the callback * as the only parameter * 3. _object_ - DataTables settings object for the table * * Note that this supersedes `fnServerData` from DataTables 1.9-. * * @type string|object|function * @default null * * @dtopt Option * @name DataTable.defaults.ajax * @since 1.10.0 * * @example * // Get JSON data from a file via Ajax. * // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default). * $('#example').dataTable( { * "ajax": "data.json" * } ); * * @example * // Get JSON data from a file via Ajax, using `dataSrc` to change * // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`) * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "dataSrc": "tableData" * } * } ); * * @example * // Get JSON data from a file via Ajax, using `dataSrc` to read data * // from a plain array rather than an array in an object * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "dataSrc": "" * } * } ); * * @example * // Manipulate the data returned from the server - add a link to data * // (note this can, should, be done using `render` for the column - this * // is just a simple example of how the data can be manipulated). * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "dataSrc": function ( json ) { * for ( var i=0, ien=json.length ; i<ien ; i++ ) { * json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>'; * } * return json; * } * } * } ); * * @example * // Add data to the request * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "data": function ( d ) { * return { * "extra_search": $('#extra').val() * }; * } * } * } ); * * @example * // Send request as POST * $('#example').dataTable( { * "ajax": { * "url": "data.json", * "type": "POST" * } * } ); * * @example * // Get the data from localStorage (could interface with a form for * // adding, editing and removing rows). * $('#example').dataTable( { * "ajax": function (data, callback, settings) { * callback( * JSON.parse( localStorage.getItem('dataTablesData') ) * ); * } * } ); */ "ajax": null, /** * This parameter allows you to readily specify the entries in the length drop * down menu that DataTables shows when pagination is enabled. It can be * either a 1D array of options which will be used for both the displayed * option and the value, or a 2D array which will use the array in the first * position as the value, and the array in the second position as the * displayed options (useful for language strings such as 'All'). * * Note that the `pageLength` property will be automatically set to the * first value given in this array, unless `pageLength` is also provided. * @type array * @default [ 10, 25, 50, 100 ] * * @dtopt Option * @name DataTable.defaults.lengthMenu * * @example * $(document).ready( function() { * $('#example').dataTable( { * "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]] * } ); * } ); */ "aLengthMenu": [ 10, 25, 50, 100 ], /** * The `columns` option in the initialisation parameter allows you to define * details about the way individual columns behave. For a full list of * column options that can be set, please see * {@link DataTable.defaults.column}. Note that if you use `columns` to * define your columns, you must have an entry in the array for every single * column that you have in your table (these can be null if you don't which * to specify any options). * @member * * @name DataTable.defaults.column */ "aoColumns": null, /** * Very similar to `columns`, `columnDefs` allows you to target a specific * column, multiple columns, or all columns, using the `targets` property of * each object in the array. This allows great flexibility when creating * tables, as the `columnDefs` arrays can be of any length, targeting the * columns you specifically want. `columnDefs` may use any of the column * options available: {@link DataTable.defaults.column}, but it _must_ * have `targets` defined in each object in the array. Values in the `targets` * array may be: * <ul> * <li>a string - class name will be matched on the TH for the column</li> * <li>0 or a positive integer - column index counting from the left</li> * <li>a negative integer - column index counting from the right</li> * <li>the string "_all" - all columns (i.e. assign a default)</li> * </ul> * @member * * @name DataTable.defaults.columnDefs */ "aoColumnDefs": null, /** * Basically the same as `search`, this parameter defines the individual column * filtering state at initialisation time. The array must be of the same size * as the number of columns, and each element be an object with the parameters * `search` and `escapeRegex` (the latter is optional). 'null' is also * accepted and the default will be used. * @type array * @default [] * * @dtopt Option * @name DataTable.defaults.searchCols * * @example * $(document).ready( function() { * $('#example').dataTable( { * "searchCols": [ * null, * { "search": "My filter" }, * null, * { "search": "^[0-9]", "escapeRegex": false } * ] * } ); * } ) */ "aoSearchCols": [], /** * An array of CSS classes that should be applied to displayed rows. This * array may be of any length, and DataTables will apply each class * sequentially, looping when required. * @type array * @default null <i>Will take the values determined by the `oClasses.stripe*` * options</i> * * @dtopt Option * @name DataTable.defaults.stripeClasses * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stripeClasses": [ 'strip1', 'strip2', 'strip3' ] * } ); * } ) */ "asStripeClasses": null, /** * Enable or disable automatic column width calculation. This can be disabled * as an optimisation (it takes some time to calculate the widths) if the * tables widths are passed in using `columns`. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.autoWidth * * @example * $(document).ready( function () { * $('#example').dataTable( { * "autoWidth": false * } ); * } ); */ "bAutoWidth": true, /** * Deferred rendering can provide DataTables with a huge speed boost when you * are using an Ajax or JS data source for the table. This option, when set to * true, will cause DataTables to defer the creation of the table elements for * each row until they are needed for a draw - saving a significant amount of * time. * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.deferRender * * @example * $(document).ready( function() { * $('#example').dataTable( { * "ajax": "sources/arrays.txt", * "deferRender": true * } ); * } ); */ "bDeferRender": false, /** * Replace a DataTable which matches the given selector and replace it with * one which has the properties of the new initialisation object passed. If no * table matches the selector, then the new DataTable will be constructed as * per normal. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.destroy * * @example * $(document).ready( function() { * $('#example').dataTable( { * "srollY": "200px", * "paginate": false * } ); * * // Some time later.... * $('#example').dataTable( { * "filter": false, * "destroy": true * } ); * } ); */ "bDestroy": false, /** * Enable or disable filtering of data. Filtering in DataTables is "smart" in * that it allows the end user to input multiple words (space separated) and * will match a row containing those words, even if not in the order that was * specified (this allow matching across multiple columns). Note that if you * wish to use filtering in DataTables this must remain 'true' - to remove the * default filtering input box and retain filtering abilities, please use * {@link DataTable.defaults.dom}. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.searching * * @example * $(document).ready( function () { * $('#example').dataTable( { * "searching": false * } ); * } ); */ "bFilter": true, /** * Enable or disable the table information display. This shows information * about the data that is currently visible on the page, including information * about filtered data if that action is being performed. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.info * * @example * $(document).ready( function () { * $('#example').dataTable( { * "info": false * } ); * } ); */ "bInfo": true, /** * Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some * slightly different and additional mark-up from what DataTables has * traditionally used). * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.jQueryUI * * @example * $(document).ready( function() { * $('#example').dataTable( { * "jQueryUI": true * } ); * } ); */ "bJQueryUI": false, /** * Allows the end user to select the size of a formatted page from a select * menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`). * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.lengthChange * * @example * $(document).ready( function () { * $('#example').dataTable( { * "lengthChange": false * } ); * } ); */ "bLengthChange": true, /** * Enable or disable pagination. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.paging * * @example * $(document).ready( function () { * $('#example').dataTable( { * "paging": false * } ); * } ); */ "bPaginate": true, /** * Enable or disable the display of a 'processing' indicator when the table is * being processed (e.g. a sort). This is particularly useful for tables with * large amounts of data where it can take a noticeable amount of time to sort * the entries. * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.processing * * @example * $(document).ready( function () { * $('#example').dataTable( { * "processing": true * } ); * } ); */ "bProcessing": false, /** * Retrieve the DataTables object for the given selector. Note that if the * table has already been initialised, this parameter will cause DataTables * to simply return the object that has already been set up - it will not take * account of any changes you might have made to the initialisation object * passed to DataTables (setting this parameter to true is an acknowledgement * that you understand this). `destroy` can be used to reinitialise a table if * you need. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.retrieve * * @example * $(document).ready( function() { * initTable(); * tableActions(); * } ); * * function initTable () * { * return $('#example').dataTable( { * "scrollY": "200px", * "paginate": false, * "retrieve": true * } ); * } * * function tableActions () * { * var table = initTable(); * // perform API operations with oTable * } */ "bRetrieve": false, /** * When vertical (y) scrolling is enabled, DataTables will force the height of * the table's viewport to the given height at all times (useful for layout). * However, this can look odd when filtering data down to a small data set, * and the footer is left "floating" further down. This parameter (when * enabled) will cause DataTables to collapse the table's viewport down when * the result set will fit within the given Y height. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.scrollCollapse * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollY": "200", * "scrollCollapse": true * } ); * } ); */ "bScrollCollapse": false, /** * Configure DataTables to use server-side processing. Note that the * `ajax` parameter must also be given in order to give DataTables a * source to obtain the required data for each draw. * @type boolean * @default false * * @dtopt Features * @dtopt Server-side * @name DataTable.defaults.serverSide * * @example * $(document).ready( function () { * $('#example').dataTable( { * "serverSide": true, * "ajax": "xhr.php" * } ); * } ); */ "bServerSide": false, /** * Enable or disable sorting of columns. Sorting of individual columns can be * disabled by the `sortable` option for each column. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.ordering * * @example * $(document).ready( function () { * $('#example').dataTable( { * "ordering": false * } ); * } ); */ "bSort": true, /** * Enable or display DataTables' ability to sort multiple columns at the * same time (activated by shift-click by the user). * @type boolean * @default true * * @dtopt Options * @name DataTable.defaults.orderMulti * * @example * // Disable multiple column sorting ability * $(document).ready( function () { * $('#example').dataTable( { * "orderMulti": false * } ); * } ); */ "bSortMulti": true, /** * Allows control over whether DataTables should use the top (true) unique * cell that is found for a single column, or the bottom (false - default). * This is useful when using complex headers. * @type boolean * @default false * * @dtopt Options * @name DataTable.defaults.orderCellsTop * * @example * $(document).ready( function() { * $('#example').dataTable( { * "orderCellsTop": true * } ); * } ); */ "bSortCellsTop": false, /** * Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and * `sorting\_3` to the columns which are currently being sorted on. This is * presented as a feature switch as it can increase processing time (while * classes are removed and added) so for large data sets you might want to * turn this off. * @type boolean * @default true * * @dtopt Features * @name DataTable.defaults.orderClasses * * @example * $(document).ready( function () { * $('#example').dataTable( { * "orderClasses": false * } ); * } ); */ "bSortClasses": true, /** * Enable or disable state saving. When enabled HTML5 `localStorage` will be * used to save table display information such as pagination information, * display length, filtering and sorting. As such when the end user reloads * the page the display display will match what thy had previously set up. * * Due to the use of `localStorage` the default state saving is not supported * in IE6 or 7. If state saving is required in those browsers, use * `stateSaveCallback` to provide a storage solution such as cookies. * @type boolean * @default false * * @dtopt Features * @name DataTable.defaults.stateSave * * @example * $(document).ready( function () { * $('#example').dataTable( { * "stateSave": true * } ); * } ); */ "bStateSave": false, /** * This function is called when a TR element is created (and all TD child * elements have been inserted), or registered if using a DOM source, allowing * manipulation of the TR element (adding classes etc). * @type function * @param {node} row "TR" element for the current row * @param {array} data Raw data array for this row * @param {int} dataIndex The index of this row in the internal aoData array * * @dtopt Callbacks * @name DataTable.defaults.createdRow * * @example * $(document).ready( function() { * $('#example').dataTable( { * "createdRow": function( row, data, dataIndex ) { * // Bold the grade for all 'A' grade browsers * if ( data[4] == "A" ) * { * $('td:eq(4)', row).html( '<b>A</b>' ); * } * } * } ); * } ); */ "fnCreatedRow": null, /** * This function is called on every 'draw' event, and allows you to * dynamically modify any aspect you want about the created DOM. * @type function * @param {object} settings DataTables settings object * * @dtopt Callbacks * @name DataTable.defaults.drawCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "drawCallback": function( settings ) { * alert( 'DataTables has redrawn the table' ); * } * } ); * } ); */ "fnDrawCallback": null, /** * Identical to fnHeaderCallback() but for the table footer this function * allows you to modify the table footer on every 'draw' event. * @type function * @param {node} foot "TR" element for the footer * @param {array} data Full table data (as derived from the original HTML) * @param {int} start Index for the current display starting point in the * display array * @param {int} end Index for the current display ending point in the * display array * @param {array int} display Index array to translate the visual position * to the full data array * * @dtopt Callbacks * @name DataTable.defaults.footerCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "footerCallback": function( tfoot, data, start, end, display ) { * tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start; * } * } ); * } ) */ "fnFooterCallback": null, /** * When rendering large numbers in the information element for the table * (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers * to have a comma separator for the 'thousands' units (e.g. 1 million is * rendered as "1,000,000") to help readability for the end user. This * function will override the default method DataTables uses. * @type function * @member * @param {int} toFormat number to be formatted * @returns {string} formatted string for DataTables to show the number * * @dtopt Callbacks * @name DataTable.defaults.formatNumber * * @example * // Format a number using a single quote for the separator (note that * // this can also be done with the language.thousands option) * $(document).ready( function() { * $('#example').dataTable( { * "formatNumber": function ( toFormat ) { * return toFormat.toString().replace( * /\B(?=(\d{3})+(?!\d))/g, "'" * ); * }; * } ); * } ); */ "fnFormatNumber": function ( toFormat ) { return toFormat.toString().replace( /\B(?=(\d{3})+(?!\d))/g, this.oLanguage.sThousands ); }, /** * This function is called on every 'draw' event, and allows you to * dynamically modify the header row. This can be used to calculate and * display useful information about the table. * @type function * @param {node} head "TR" element for the header * @param {array} data Full table data (as derived from the original HTML) * @param {int} start Index for the current display starting point in the * display array * @param {int} end Index for the current display ending point in the * display array * @param {array int} display Index array to translate the visual position * to the full data array * * @dtopt Callbacks * @name DataTable.defaults.headerCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "fheaderCallback": function( head, data, start, end, display ) { * head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records"; * } * } ); * } ) */ "fnHeaderCallback": null, /** * The information element can be used to convey information about the current * state of the table. Although the internationalisation options presented by * DataTables are quite capable of dealing with most customisations, there may * be times where you wish to customise the string further. This callback * allows you to do exactly that. * @type function * @param {object} oSettings DataTables settings object * @param {int} start Starting position in data for the draw * @param {int} end End position in data for the draw * @param {int} max Total number of rows in the table (regardless of * filtering) * @param {int} total Total number of rows in the data set, after filtering * @param {string} pre The string that DataTables has formatted using it's * own rules * @returns {string} The string to be displayed in the information element. * * @dtopt Callbacks * @name DataTable.defaults.infoCallback * * @example * $('#example').dataTable( { * "infoCallback": function( settings, start, end, max, total, pre ) { * return start +" to "+ end; * } * } ); */ "fnInfoCallback": null, /** * Called when the table has been initialised. Normally DataTables will * initialise sequentially and there will be no need for this function, * however, this does not hold true when using external language information * since that is obtained using an async XHR call. * @type function * @param {object} settings DataTables settings object * @param {object} json The JSON object request from the server - only * present if client-side Ajax sourced data is used * * @dtopt Callbacks * @name DataTable.defaults.initComplete * * @example * $(document).ready( function() { * $('#example').dataTable( { * "initComplete": function(settings, json) { * alert( 'DataTables has finished its initialisation.' ); * } * } ); * } ) */ "fnInitComplete": null, /** * Called at the very start of each table draw and can be used to cancel the * draw by returning false, any other return (including undefined) results in * the full draw occurring). * @type function * @param {object} settings DataTables settings object * @returns {boolean} False will cancel the draw, anything else (including no * return) will allow it to complete. * * @dtopt Callbacks * @name DataTable.defaults.preDrawCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "preDrawCallback": function( settings ) { * if ( $('#test').val() == 1 ) { * return false; * } * } * } ); * } ); */ "fnPreDrawCallback": null, /** * This function allows you to 'post process' each row after it have been * generated for each table draw, but before it is rendered on screen. This * function might be used for setting the row class name etc. * @type function * @param {node} row "TR" element for the current row * @param {array} data Raw data array for this row * @param {int} displayIndex The display index for the current table draw * @param {int} displayIndexFull The index of the data in the full list of * rows (after filtering) * * @dtopt Callbacks * @name DataTable.defaults.rowCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "rowCallback": function( row, data, displayIndex, displayIndexFull ) { * // Bold the grade for all 'A' grade browsers * if ( data[4] == "A" ) { * $('td:eq(4)', row).html( '<b>A</b>' ); * } * } * } ); * } ); */ "fnRowCallback": null, /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * This parameter allows you to override the default function which obtains * the data from the server so something more suitable for your application. * For example you could use POST data, or pull information from a Gears or * AIR database. * @type function * @member * @param {string} source HTTP source to obtain the data from (`ajax`) * @param {array} data A key/value pair object containing the data to send * to the server * @param {function} callback to be called on completion of the data get * process that will draw the data on the page. * @param {object} settings DataTables settings object * * @dtopt Callbacks * @dtopt Server-side * @name DataTable.defaults.serverData * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "fnServerData": null, /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * It is often useful to send extra data to the server when making an Ajax * request - for example custom filtering information, and this callback * function makes it trivial to send extra information to the server. The * passed in parameter is the data set that has been constructed by * DataTables, and you can add to this or modify it as you require. * @type function * @param {array} data Data array (array of objects which are name/value * pairs) that has been constructed by DataTables and will be sent to the * server. In the case of Ajax sourced data with server-side processing * this will be an empty array, for server-side processing there will be a * significant number of parameters! * @returns {undefined} Ensure that you modify the data array passed in, * as this is passed by reference. * * @dtopt Callbacks * @dtopt Server-side * @name DataTable.defaults.serverParams * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "fnServerParams": null, /** * Load the table state. With this function you can define from where, and how, the * state of a table is loaded. By default DataTables will load from `localStorage` * but you might wish to use a server-side database or cookies. * @type function * @member * @param {object} settings DataTables settings object * @return {object} The DataTables state object to be loaded * * @dtopt Callbacks * @name DataTable.defaults.stateLoadCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoadCallback": function (settings) { * var o; * * // Send an Ajax request to the server to get the data. Note that * // this is a synchronous request. * $.ajax( { * "url": "/state_load", * "async": false, * "dataType": "json", * "success": function (json) { * o = json; * } * } ); * * return o; * } * } ); * } ); */ "fnStateLoadCallback": function ( settings ) { try { return JSON.parse( (settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem( 'DataTables_'+settings.sInstance+'_'+location.pathname ) ); } catch (e) {} }, /** * Callback which allows modification of the saved state prior to loading that state. * This callback is called when the table is loading state from the stored data, but * prior to the settings object being modified by the saved state. Note that for * plug-in authors, you should use the `stateLoadParams` event to load parameters for * a plug-in. * @type function * @param {object} settings DataTables settings object * @param {object} data The state object that is to be loaded * * @dtopt Callbacks * @name DataTable.defaults.stateLoadParams * * @example * // Remove a saved filter, so filtering is never loaded * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoadParams": function (settings, data) { * data.oSearch.sSearch = ""; * } * } ); * } ); * * @example * // Disallow state loading by returning false * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoadParams": function (settings, data) { * return false; * } * } ); * } ); */ "fnStateLoadParams": null, /** * Callback that is called when the state has been loaded from the state saving method * and the DataTables settings object has been modified as a result of the loaded state. * @type function * @param {object} settings DataTables settings object * @param {object} data The state object that was loaded * * @dtopt Callbacks * @name DataTable.defaults.stateLoaded * * @example * // Show an alert with the filtering value that was saved * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateLoaded": function (settings, data) { * alert( 'Saved filter was: '+data.oSearch.sSearch ); * } * } ); * } ); */ "fnStateLoaded": null, /** * Save the table state. This function allows you to define where and how the state * information for the table is stored By default DataTables will use `localStorage` * but you might wish to use a server-side database or cookies. * @type function * @member * @param {object} settings DataTables settings object * @param {object} data The state object to be saved * * @dtopt Callbacks * @name DataTable.defaults.stateSaveCallback * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateSaveCallback": function (settings, data) { * // Send an Ajax request to the server with the state object * $.ajax( { * "url": "/state_save", * "data": data, * "dataType": "json", * "method": "POST" * "success": function () {} * } ); * } * } ); * } ); */ "fnStateSaveCallback": function ( settings, data ) { try { (settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem( 'DataTables_'+settings.sInstance+'_'+location.pathname, JSON.stringify( data ) ); } catch (e) {} }, /** * Callback which allows modification of the state to be saved. Called when the table * has changed state a new state save is required. This method allows modification of * the state saving object prior to actually doing the save, including addition or * other state properties or modification. Note that for plug-in authors, you should * use the `stateSaveParams` event to save parameters for a plug-in. * @type function * @param {object} settings DataTables settings object * @param {object} data The state object to be saved * * @dtopt Callbacks * @name DataTable.defaults.stateSaveParams * * @example * // Remove a saved filter, so filtering is never saved * $(document).ready( function() { * $('#example').dataTable( { * "stateSave": true, * "stateSaveParams": function (settings, data) { * data.oSearch.sSearch = ""; * } * } ); * } ); */ "fnStateSaveParams": null, /** * Duration for which the saved state information is considered valid. After this period * has elapsed the state will be returned to the default. * Value is given in seconds. * @type int * @default 7200 <i>(2 hours)</i> * * @dtopt Options * @name DataTable.defaults.stateDuration * * @example * $(document).ready( function() { * $('#example').dataTable( { * "stateDuration": 60*60*24; // 1 day * } ); * } ) */ "iStateDuration": 7200, /** * When enabled DataTables will not make a request to the server for the first * page draw - rather it will use the data already on the page (no sorting etc * will be applied to it), thus saving on an XHR at load time. `deferLoading` * is used to indicate that deferred loading is required, but it is also used * to tell DataTables how many records there are in the full table (allowing * the information element and pagination to be displayed correctly). In the case * where a filtering is applied to the table on initial load, this can be * indicated by giving the parameter as an array, where the first element is * the number of records available after filtering and the second element is the * number of records without filtering (allowing the table information element * to be shown correctly). * @type int | array * @default null * * @dtopt Options * @name DataTable.defaults.deferLoading * * @example * // 57 records available in the table, no filtering applied * $(document).ready( function() { * $('#example').dataTable( { * "serverSide": true, * "ajax": "scripts/server_processing.php", * "deferLoading": 57 * } ); * } ); * * @example * // 57 records after filtering, 100 without filtering (an initial filter applied) * $(document).ready( function() { * $('#example').dataTable( { * "serverSide": true, * "ajax": "scripts/server_processing.php", * "deferLoading": [ 57, 100 ], * "search": { * "search": "my_filter" * } * } ); * } ); */ "iDeferLoading": null, /** * Number of rows to display on a single page when using pagination. If * feature enabled (`lengthChange`) then the end user will be able to override * this to a custom setting using a pop-up menu. * @type int * @default 10 * * @dtopt Options * @name DataTable.defaults.pageLength * * @example * $(document).ready( function() { * $('#example').dataTable( { * "pageLength": 50 * } ); * } ) */ "iDisplayLength": 10, /** * Define the starting point for data display when using DataTables with * pagination. Note that this parameter is the number of records, rather than * the page number, so if you have 10 records per page and want to start on * the third page, it should be "20". * @type int * @default 0 * * @dtopt Options * @name DataTable.defaults.displayStart * * @example * $(document).ready( function() { * $('#example').dataTable( { * "displayStart": 20 * } ); * } ) */ "iDisplayStart": 0, /** * By default DataTables allows keyboard navigation of the table (sorting, paging, * and filtering) by adding a `tabindex` attribute to the required elements. This * allows you to tab through the controls and press the enter key to activate them. * The tabindex is default 0, meaning that the tab follows the flow of the document. * You can overrule this using this parameter if you wish. Use a value of -1 to * disable built-in keyboard navigation. * @type int * @default 0 * * @dtopt Options * @name DataTable.defaults.tabIndex * * @example * $(document).ready( function() { * $('#example').dataTable( { * "tabIndex": 1 * } ); * } ); */ "iTabIndex": 0, /** * Classes that DataTables assigns to the various components and features * that it adds to the HTML table. This allows classes to be configured * during initialisation in addition to through the static * {@link DataTable.ext.oStdClasses} object). * @namespace * @name DataTable.defaults.classes */ "oClasses": {}, /** * All strings that DataTables uses in the user interface that it creates * are defined in this object, allowing you to modified them individually or * completely replace them all as required. * @namespace * @name DataTable.defaults.language */ "oLanguage": { /** * Strings that are used for WAI-ARIA labels and controls only (these are not * actually visible on the page, but will be read by screenreaders, and thus * must be internationalised as well). * @namespace * @name DataTable.defaults.language.aria */ "oAria": { /** * ARIA label that is added to the table headers when the column may be * sorted ascending by activing the column (click or return when focused). * Note that the column header is prefixed to this string. * @type string * @default : activate to sort column ascending * * @dtopt Language * @name DataTable.defaults.language.aria.sortAscending * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "aria": { * "sortAscending": " - click/return to sort ascending" * } * } * } ); * } ); */ "sSortAscending": ": activate to sort column ascending", /** * ARIA label that is added to the table headers when the column may be * sorted descending by activing the column (click or return when focused). * Note that the column header is prefixed to this string. * @type string * @default : activate to sort column ascending * * @dtopt Language * @name DataTable.defaults.language.aria.sortDescending * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "aria": { * "sortDescending": " - click/return to sort descending" * } * } * } ); * } ); */ "sSortDescending": ": activate to sort column descending" }, /** * Pagination string used by DataTables for the built-in pagination * control types. * @namespace * @name DataTable.defaults.language.paginate */ "oPaginate": { /** * Text to use when using the 'full_numbers' type of pagination for the * button to take the user to the first page. * @type string * @default First * * @dtopt Language * @name DataTable.defaults.language.paginate.first * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "first": "First page" * } * } * } ); * } ); */ "sFirst": "First", /** * Text to use when using the 'full_numbers' type of pagination for the * button to take the user to the last page. * @type string * @default Last * * @dtopt Language * @name DataTable.defaults.language.paginate.last * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "last": "Last page" * } * } * } ); * } ); */ "sLast": "Last", /** * Text to use for the 'next' pagination button (to take the user to the * next page). * @type string * @default Next * * @dtopt Language * @name DataTable.defaults.language.paginate.next * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "next": "Next page" * } * } * } ); * } ); */ "sNext": "Next", /** * Text to use for the 'previous' pagination button (to take the user to * the previous page). * @type string * @default Previous * * @dtopt Language * @name DataTable.defaults.language.paginate.previous * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "paginate": { * "previous": "Previous page" * } * } * } ); * } ); */ "sPrevious": "Previous" }, /** * This string is shown in preference to `zeroRecords` when the table is * empty of data (regardless of filtering). Note that this is an optional * parameter - if it is not given, the value of `zeroRecords` will be used * instead (either the default or given value). * @type string * @default No data available in table * * @dtopt Language * @name DataTable.defaults.language.emptyTable * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "emptyTable": "No data available in table" * } * } ); * } ); */ "sEmptyTable": "No data available in table", /** * This string gives information to the end user about the information * that is current on display on the page. The following tokens can be * used in the string and will be dynamically replaced as the table * display updates. This tokens can be placed anywhere in the string, or * removed as needed by the language requires: * * * `\_START\_` - Display index of the first record on the current page * * `\_END\_` - Display index of the last record on the current page * * `\_TOTAL\_` - Number of records in the table after filtering * * `\_MAX\_` - Number of records in the table without filtering * * `\_PAGE\_` - Current page number * * `\_PAGES\_` - Total number of pages of data in the table * * @type string * @default Showing _START_ to _END_ of _TOTAL_ entries * * @dtopt Language * @name DataTable.defaults.language.info * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "info": "Showing page _PAGE_ of _PAGES_" * } * } ); * } ); */ "sInfo": "Showing _START_ to _END_ of _TOTAL_ entries", /** * Display information string for when the table is empty. Typically the * format of this string should match `info`. * @type string * @default Showing 0 to 0 of 0 entries * * @dtopt Language * @name DataTable.defaults.language.infoEmpty * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "infoEmpty": "No entries to show" * } * } ); * } ); */ "sInfoEmpty": "Showing 0 to 0 of 0 entries", /** * When a user filters the information in a table, this string is appended * to the information (`info`) to give an idea of how strong the filtering * is. The variable _MAX_ is dynamically updated. * @type string * @default (filtered from _MAX_ total entries) * * @dtopt Language * @name DataTable.defaults.language.infoFiltered * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "infoFiltered": " - filtering from _MAX_ records" * } * } ); * } ); */ "sInfoFiltered": "(filtered from _MAX_ total entries)", /** * If can be useful to append extra information to the info string at times, * and this variable does exactly that. This information will be appended to * the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are * being used) at all times. * @type string * @default <i>Empty string</i> * * @dtopt Language * @name DataTable.defaults.language.infoPostFix * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "infoPostFix": "All records shown are derived from real information." * } * } ); * } ); */ "sInfoPostFix": "", /** * This decimal place operator is a little different from the other * language options since DataTables doesn't output floating point * numbers, so it won't ever use this for display of a number. Rather, * what this parameter does is modify the sort methods of the table so * that numbers which are in a format which has a character other than * a period (`.`) as a decimal place will be sorted numerically. * * Note that numbers with different decimal places cannot be shown in * the same table and still be sortable, the table must be consistent. * However, multiple different tables on the page can use different * decimal place characters. * @type string * @default * * @dtopt Language * @name DataTable.defaults.language.decimal * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "decimal": "," * "thousands": "." * } * } ); * } ); */ "sDecimal": "", /** * DataTables has a build in number formatter (`formatNumber`) which is * used to format large numbers that are used in the table information. * By default a comma is used, but this can be trivially changed to any * character you wish with this parameter. * @type string * @default , * * @dtopt Language * @name DataTable.defaults.language.thousands * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "thousands": "'" * } * } ); * } ); */ "sThousands": ",", /** * Detail the action that will be taken when the drop down menu for the * pagination length option is changed. The '_MENU_' variable is replaced * with a default select list of 10, 25, 50 and 100, and can be replaced * with a custom select box if required. * @type string * @default Show _MENU_ entries * * @dtopt Language * @name DataTable.defaults.language.lengthMenu * * @example * // Language change only * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "lengthMenu": "Display _MENU_ records" * } * } ); * } ); * * @example * // Language and options change * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "lengthMenu": 'Display <select>'+ * '<option value="10">10</option>'+ * '<option value="20">20</option>'+ * '<option value="30">30</option>'+ * '<option value="40">40</option>'+ * '<option value="50">50</option>'+ * '<option value="-1">All</option>'+ * '</select> records' * } * } ); * } ); */ "sLengthMenu": "Show _MENU_ entries", /** * When using Ajax sourced data and during the first draw when DataTables is * gathering the data, this message is shown in an empty row in the table to * indicate to the end user the the data is being loaded. Note that this * parameter is not used when loading data by server-side processing, just * Ajax sourced data with client-side processing. * @type string * @default Loading... * * @dtopt Language * @name DataTable.defaults.language.loadingRecords * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "loadingRecords": "Please wait - loading..." * } * } ); * } ); */ "sLoadingRecords": "Loading...", /** * Text which is displayed when the table is processing a user action * (usually a sort command or similar). * @type string * @default Processing... * * @dtopt Language * @name DataTable.defaults.language.processing * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "processing": "DataTables is currently busy" * } * } ); * } ); */ "sProcessing": "Processing...", /** * Details the actions that will be taken when the user types into the * filtering input text box. The variable "_INPUT_", if used in the string, * is replaced with the HTML text box for the filtering input allowing * control over where it appears in the string. If "_INPUT_" is not given * then the input box is appended to the string automatically. * @type string * @default Search: * * @dtopt Language * @name DataTable.defaults.language.search * * @example * // Input text box will be appended at the end automatically * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "search": "Filter records:" * } * } ); * } ); * * @example * // Specify where the filter should appear * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "search": "Apply filter _INPUT_ to table" * } * } ); * } ); */ "sSearch": "Search:", /** * Assign a `placeholder` attribute to the search `input` element * @type string * @default * * @dtopt Language * @name DataTable.defaults.language.searchPlaceholder */ "sSearchPlaceholder": "", /** * All of the language information can be stored in a file on the * server-side, which DataTables will look up if this parameter is passed. * It must store the URL of the language file, which is in a JSON format, * and the object has the same properties as the oLanguage object in the * initialiser object (i.e. the above parameters). Please refer to one of * the example language files to see how this works in action. * @type string * @default <i>Empty string - i.e. disabled</i> * * @dtopt Language * @name DataTable.defaults.language.url * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "url": "http://www.sprymedia.co.uk/dataTables/lang.txt" * } * } ); * } ); */ "sUrl": "", /** * Text shown inside the table records when the is no information to be * displayed after filtering. `emptyTable` is shown when there is simply no * information in the table at all (regardless of filtering). * @type string * @default No matching records found * * @dtopt Language * @name DataTable.defaults.language.zeroRecords * * @example * $(document).ready( function() { * $('#example').dataTable( { * "language": { * "zeroRecords": "No records to display" * } * } ); * } ); */ "sZeroRecords": "No matching records found" }, /** * This parameter allows you to have define the global filtering state at * initialisation time. As an object the `search` parameter must be * defined, but all other parameters are optional. When `regex` is true, * the search string will be treated as a regular expression, when false * (default) it will be treated as a straight string. When `smart` * DataTables will use it's smart filtering methods (to word match at * any point in the data), when false this will not be done. * @namespace * @extends DataTable.models.oSearch * * @dtopt Options * @name DataTable.defaults.search * * @example * $(document).ready( function() { * $('#example').dataTable( { * "search": {"search": "Initial search"} * } ); * } ) */ "oSearch": $.extend( {}, DataTable.models.oSearch ), /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * By default DataTables will look for the property `data` (or `aaData` for * compatibility with DataTables 1.9-) when obtaining data from an Ajax * source or for server-side processing - this parameter allows that * property to be changed. You can use Javascript dotted object notation to * get a data source for multiple levels of nesting. * @type string * @default data * * @dtopt Options * @dtopt Server-side * @name DataTable.defaults.ajaxDataProp * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "sAjaxDataProp": "data", /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * You can instruct DataTables to load data from an external * source using this parameter (use aData if you want to pass data in you * already have). Simply provide a url a JSON object can be obtained from. * @type string * @default null * * @dtopt Options * @dtopt Server-side * @name DataTable.defaults.ajaxSource * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "sAjaxSource": null, /** * This initialisation variable allows you to specify exactly where in the * DOM you want DataTables to inject the various controls it adds to the page * (for example you might want the pagination controls at the top of the * table). DIV elements (with or without a custom class) can also be added to * aid styling. The follow syntax is used: * <ul> * <li>The following options are allowed: * <ul> * <li>'l' - Length changing</li> * <li>'f' - Filtering input</li> * <li>'t' - The table!</li> * <li>'i' - Information</li> * <li>'p' - Pagination</li> * <li>'r' - pRocessing</li> * </ul> * </li> * <li>The following constants are allowed: * <ul> * <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li> * <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li> * </ul> * </li> * <li>The following syntax is expected: * <ul> * <li>'<' and '>' - div elements</li> * <li>'<"class" and '>' - div with a class</li> * <li>'<"#id" and '>' - div with an ID</li> * </ul> * </li> * <li>Examples: * <ul> * <li>'<"wrapper"flipt>'</li> * <li>'<lf<t>ip>'</li> * </ul> * </li> * </ul> * @type string * @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b> * <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i> * * @dtopt Options * @name DataTable.defaults.dom * * @example * $(document).ready( function() { * $('#example').dataTable( { * "dom": '<"top"i>rt<"bottom"flp><"clear">' * } ); * } ); */ "sDom": "lfrtip", /** * Search delay option. This will throttle full table searches that use the * DataTables provided search input element (it does not effect calls to * `dt-api search()`, providing a delay before the search is made. * @type integer * @default 0 * * @dtopt Options * @name DataTable.defaults.searchDelay * * @example * $(document).ready( function() { * $('#example').dataTable( { * "searchDelay": 200 * } ); * } ) */ "searchDelay": null, /** * DataTables features four different built-in options for the buttons to * display for pagination control: * * * `simple` - 'Previous' and 'Next' buttons only * * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers * * `full` - 'First', 'Previous', 'Next' and 'Last' buttons * * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus * page numbers * * Further methods can be added using {@link DataTable.ext.oPagination}. * @type string * @default simple_numbers * * @dtopt Options * @name DataTable.defaults.pagingType * * @example * $(document).ready( function() { * $('#example').dataTable( { * "pagingType": "full_numbers" * } ); * } ) */ "sPaginationType": "simple_numbers", /** * Enable horizontal scrolling. When a table is too wide to fit into a * certain layout, or you have a large number of columns in the table, you * can enable x-scrolling to show the table in a viewport, which can be * scrolled. This property can be `true` which will allow the table to * scroll horizontally when needed, or any CSS unit, or a number (in which * case it will be treated as a pixel measurement). Setting as simply `true` * is recommended. * @type boolean|string * @default <i>blank string - i.e. disabled</i> * * @dtopt Features * @name DataTable.defaults.scrollX * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollX": true, * "scrollCollapse": true * } ); * } ); */ "sScrollX": "", /** * This property can be used to force a DataTable to use more width than it * might otherwise do when x-scrolling is enabled. For example if you have a * table which requires to be well spaced, this parameter is useful for * "over-sizing" the table, and thus forcing scrolling. This property can by * any CSS unit, or a number (in which case it will be treated as a pixel * measurement). * @type string * @default <i>blank string - i.e. disabled</i> * * @dtopt Options * @name DataTable.defaults.scrollXInner * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollX": "100%", * "scrollXInner": "110%" * } ); * } ); */ "sScrollXInner": "", /** * Enable vertical scrolling. Vertical scrolling will constrain the DataTable * to the given height, and enable scrolling for any data which overflows the * current viewport. This can be used as an alternative to paging to display * a lot of data in a small area (although paging and scrolling can both be * enabled at the same time). This property can be any CSS unit, or a number * (in which case it will be treated as a pixel measurement). * @type string * @default <i>blank string - i.e. disabled</i> * * @dtopt Features * @name DataTable.defaults.scrollY * * @example * $(document).ready( function() { * $('#example').dataTable( { * "scrollY": "200px", * "paginate": false * } ); * } ); */ "sScrollY": "", /** * __Deprecated__ The functionality provided by this parameter has now been * superseded by that provided through `ajax`, which should be used instead. * * Set the HTTP method that is used to make the Ajax call for server-side * processing or Ajax sourced data. * @type string * @default GET * * @dtopt Options * @dtopt Server-side * @name DataTable.defaults.serverMethod * * @deprecated 1.10. Please use `ajax` for this functionality now. */ "sServerMethod": "GET", /** * DataTables makes use of renderers when displaying HTML elements for * a table. These renderers can be added or modified by plug-ins to * generate suitable mark-up for a site. For example the Bootstrap * integration plug-in for DataTables uses a paging button renderer to * display pagination buttons in the mark-up required by Bootstrap. * * For further information about the renderers available see * DataTable.ext.renderer * @type string|object * @default null * * @name DataTable.defaults.renderer * */ "renderer": null }; _fnHungarianMap( DataTable.defaults ); /* * Developer note - See note in model.defaults.js about the use of Hungarian * notation and camel case. */ /** * Column options that can be given to DataTables at initialisation time. * @namespace */ DataTable.defaults.column = { /** * Define which column(s) an order will occur on for this column. This * allows a column's ordering to take multiple columns into account when * doing a sort or use the data from a different column. For example first * name / last name columns make sense to do a multi-column sort over the * two columns. * @type array|int * @default null <i>Takes the value of the column index automatically</i> * * @name DataTable.defaults.column.orderData * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderData": [ 0, 1 ], "targets": [ 0 ] }, * { "orderData": [ 1, 0 ], "targets": [ 1 ] }, * { "orderData": 2, "targets": [ 2 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "orderData": [ 0, 1 ] }, * { "orderData": [ 1, 0 ] }, * { "orderData": 2 }, * null, * null * ] * } ); * } ); */ "aDataSort": null, "iDataSort": -1, /** * You can control the default ordering direction, and even alter the * behaviour of the sort handler (i.e. only allow ascending ordering etc) * using this parameter. * @type array * @default [ 'asc', 'desc' ] * * @name DataTable.defaults.column.orderSequence * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderSequence": [ "asc" ], "targets": [ 1 ] }, * { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] }, * { "orderSequence": [ "desc" ], "targets": [ 3 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * { "orderSequence": [ "asc" ] }, * { "orderSequence": [ "desc", "asc", "asc" ] }, * { "orderSequence": [ "desc" ] }, * null * ] * } ); * } ); */ "asSorting": [ 'asc', 'desc' ], /** * Enable or disable filtering on the data in this column. * @type boolean * @default true * * @name DataTable.defaults.column.searchable * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "searchable": false, "targets": [ 0 ] } * ] } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "searchable": false }, * null, * null, * null, * null * ] } ); * } ); */ "bSearchable": true, /** * Enable or disable ordering on this column. * @type boolean * @default true * * @name DataTable.defaults.column.orderable * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderable": false, "targets": [ 0 ] } * ] } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "orderable": false }, * null, * null, * null, * null * ] } ); * } ); */ "bSortable": true, /** * Enable or disable the display of this column. * @type boolean * @default true * * @name DataTable.defaults.column.visible * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "visible": false, "targets": [ 0 ] } * ] } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "visible": false }, * null, * null, * null, * null * ] } ); * } ); */ "bVisible": true, /** * Developer definable function that is called whenever a cell is created (Ajax source, * etc) or processed for input (DOM source). This can be used as a compliment to mRender * allowing you to modify the DOM element (add background colour for example) when the * element is available. * @type function * @param {element} td The TD node that has been created * @param {*} cellData The Data for the cell * @param {array|object} rowData The data for the whole row * @param {int} row The row index for the aoData data store * @param {int} col The column index for aoColumns * * @name DataTable.defaults.column.createdCell * @dtopt Columns * * @example * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [3], * "createdCell": function (td, cellData, rowData, row, col) { * if ( cellData == "1.7" ) { * $(td).css('color', 'blue') * } * } * } ] * }); * } ); */ "fnCreatedCell": null, /** * This parameter has been replaced by `data` in DataTables to ensure naming * consistency. `dataProp` can still be used, as there is backwards * compatibility in DataTables for this option, but it is strongly * recommended that you use `data` in preference to `dataProp`. * @name DataTable.defaults.column.dataProp */ /** * This property can be used to read data from any data source property, * including deeply nested objects / properties. `data` can be given in a * number of different ways which effect its behaviour: * * * `integer` - treated as an array index for the data source. This is the * default that DataTables uses (incrementally increased for each column). * * `string` - read an object property from the data source. There are * three 'special' options that can be used in the string to alter how * DataTables reads the data from the source object: * * `.` - Dotted Javascript notation. Just as you use a `.` in * Javascript to read from nested objects, so to can the options * specified in `data`. For example: `browser.version` or * `browser.name`. If your object parameter name contains a period, use * `\\` to escape it - i.e. `first\\.name`. * * `[]` - Array notation. DataTables can automatically combine data * from and array source, joining the data with the characters provided * between the two brackets. For example: `name[, ]` would provide a * comma-space separated list from the source array. If no characters * are provided between the brackets, the original array source is * returned. * * `()` - Function notation. Adding `()` to the end of a parameter will * execute a function of the name given. For example: `browser()` for a * simple function on the data source, `browser.version()` for a * function in a nested property or even `browser().version` to get an * object property if the function called returns an object. Note that * function notation is recommended for use in `render` rather than * `data` as it is much simpler to use as a renderer. * * `null` - use the original data source for the row rather than plucking * data directly from it. This action has effects on two other * initialisation options: * * `defaultContent` - When null is given as the `data` option and * `defaultContent` is specified for the column, the value defined by * `defaultContent` will be used for the cell. * * `render` - When null is used for the `data` option and the `render` * option is specified for the column, the whole data source for the * row is used for the renderer. * * `function` - the function given will be executed whenever DataTables * needs to set or get the data for a cell in the column. The function * takes three parameters: * * Parameters: * * `{array|object}` The data source for the row * * `{string}` The type call data requested - this will be 'set' when * setting data or 'filter', 'display', 'type', 'sort' or undefined * when gathering data. Note that when `undefined` is given for the * type DataTables expects to get the raw data for the object back< * * `{*}` Data to set when the second parameter is 'set'. * * Return: * * The return value from the function is not required when 'set' is * the type of call, but otherwise the return is what will be used * for the data requested. * * Note that `data` is a getter and setter option. If you just require * formatting of data for output, you will likely want to use `render` which * is simply a getter and thus simpler to use. * * Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The * name change reflects the flexibility of this property and is consistent * with the naming of mRender. If 'mDataProp' is given, then it will still * be used by DataTables, as it automatically maps the old name to the new * if required. * * @type string|int|function|null * @default null <i>Use automatically calculated column index</i> * * @name DataTable.defaults.column.data * @dtopt Columns * * @example * // Read table data from objects * // JSON structure for each row: * // { * // "engine": {value}, * // "browser": {value}, * // "platform": {value}, * // "version": {value}, * // "grade": {value} * // } * $(document).ready( function() { * $('#example').dataTable( { * "ajaxSource": "sources/objects.txt", * "columns": [ * { "data": "engine" }, * { "data": "browser" }, * { "data": "platform" }, * { "data": "version" }, * { "data": "grade" } * ] * } ); * } ); * * @example * // Read information from deeply nested objects * // JSON structure for each row: * // { * // "engine": {value}, * // "browser": {value}, * // "platform": { * // "inner": {value} * // }, * // "details": [ * // {value}, {value} * // ] * // } * $(document).ready( function() { * $('#example').dataTable( { * "ajaxSource": "sources/deep.txt", * "columns": [ * { "data": "engine" }, * { "data": "browser" }, * { "data": "platform.inner" }, * { "data": "platform.details.0" }, * { "data": "platform.details.1" } * ] * } ); * } ); * * @example * // Using `data` as a function to provide different information for * // sorting, filtering and display. In this case, currency (price) * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": function ( source, type, val ) { * if (type === 'set') { * source.price = val; * // Store the computed dislay and filter values for efficiency * source.price_display = val=="" ? "" : "$"+numberFormat(val); * source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val; * return; * } * else if (type === 'display') { * return source.price_display; * } * else if (type === 'filter') { * return source.price_filter; * } * // 'sort', 'type' and undefined all just use the integer * return source.price; * } * } ] * } ); * } ); * * @example * // Using default content * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": null, * "defaultContent": "Click to edit" * } ] * } ); * } ); * * @example * // Using array notation - outputting a list from an array * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": "name[, ]" * } ] * } ); * } ); * */ "mData": null, /** * This property is the rendering partner to `data` and it is suggested that * when you want to manipulate data for display (including filtering, * sorting etc) without altering the underlying data for the table, use this * property. `render` can be considered to be the the read only companion to * `data` which is read / write (then as such more complex). Like `data` * this option can be given in a number of different ways to effect its * behaviour: * * * `integer` - treated as an array index for the data source. This is the * default that DataTables uses (incrementally increased for each column). * * `string` - read an object property from the data source. There are * three 'special' options that can be used in the string to alter how * DataTables reads the data from the source object: * * `.` - Dotted Javascript notation. Just as you use a `.` in * Javascript to read from nested objects, so to can the options * specified in `data`. For example: `browser.version` or * `browser.name`. If your object parameter name contains a period, use * `\\` to escape it - i.e. `first\\.name`. * * `[]` - Array notation. DataTables can automatically combine data * from and array source, joining the data with the characters provided * between the two brackets. For example: `name[, ]` would provide a * comma-space separated list from the source array. If no characters * are provided between the brackets, the original array source is * returned. * * `()` - Function notation. Adding `()` to the end of a parameter will * execute a function of the name given. For example: `browser()` for a * simple function on the data source, `browser.version()` for a * function in a nested property or even `browser().version` to get an * object property if the function called returns an object. * * `object` - use different data for the different data types requested by * DataTables ('filter', 'display', 'type' or 'sort'). The property names * of the object is the data type the property refers to and the value can * defined using an integer, string or function using the same rules as * `render` normally does. Note that an `_` option _must_ be specified. * This is the default value to use if you haven't specified a value for * the data type requested by DataTables. * * `function` - the function given will be executed whenever DataTables * needs to set or get the data for a cell in the column. The function * takes three parameters: * * Parameters: * * {array|object} The data source for the row (based on `data`) * * {string} The type call data requested - this will be 'filter', * 'display', 'type' or 'sort'. * * {array|object} The full data source for the row (not based on * `data`) * * Return: * * The return value from the function is what will be used for the * data requested. * * @type string|int|function|object|null * @default null Use the data source value. * * @name DataTable.defaults.column.render * @dtopt Columns * * @example * // Create a comma separated list from an array of objects * $(document).ready( function() { * $('#example').dataTable( { * "ajaxSource": "sources/deep.txt", * "columns": [ * { "data": "engine" }, * { "data": "browser" }, * { * "data": "platform", * "render": "[, ].name" * } * ] * } ); * } ); * * @example * // Execute a function to obtain data * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": null, // Use the full data source object for the renderer's source * "render": "browserName()" * } ] * } ); * } ); * * @example * // As an object, extracting different data for the different types * // This would be used with a data source such as: * // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" } * // Here the `phone` integer is used for sorting and type detection, while `phone_filter` * // (which has both forms) is used for filtering for if a user inputs either format, while * // the formatted phone number is the one that is shown in the table. * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": null, // Use the full data source object for the renderer's source * "render": { * "_": "phone", * "filter": "phone_filter", * "display": "phone_display" * } * } ] * } ); * } ); * * @example * // Use as a function to create a link from the data source * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "data": "download_link", * "render": function ( data, type, full ) { * return '<a href="'+data+'">Download</a>'; * } * } ] * } ); * } ); */ "mRender": null, /** * Change the cell type created for the column - either TD cells or TH cells. This * can be useful as TH cells have semantic meaning in the table body, allowing them * to act as a header for a row (you may wish to add scope='row' to the TH elements). * @type string * @default td * * @name DataTable.defaults.column.cellType * @dtopt Columns * * @example * // Make the first column use TH cells * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ { * "targets": [ 0 ], * "cellType": "th" * } ] * } ); * } ); */ "sCellType": "td", /** * Class to give to each cell in this column. * @type string * @default <i>Empty string</i> * * @name DataTable.defaults.column.class * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "class": "my_class", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "class": "my_class" }, * null, * null, * null, * null * ] * } ); * } ); */ "sClass": "", /** * When DataTables calculates the column widths to assign to each column, * it finds the longest string in each column and then constructs a * temporary table and reads the widths from that. The problem with this * is that "mmm" is much wider then "iiii", but the latter is a longer * string - thus the calculation can go wrong (doing it properly and putting * it into an DOM object and measuring that is horribly(!) slow). Thus as * a "work around" we provide this option. It will append its value to the * text that is found to be the longest string for the column - i.e. padding. * Generally you shouldn't need this! * @type string * @default <i>Empty string<i> * * @name DataTable.defaults.column.contentPadding * @dtopt Columns * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * null, * null, * { * "contentPadding": "mmm" * } * ] * } ); * } ); */ "sContentPadding": "", /** * Allows a default value to be given for a column's data, and will be used * whenever a null data source is encountered (this can be because `data` * is set to null, or because the data source itself is null). * @type string * @default null * * @name DataTable.defaults.column.defaultContent * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { * "data": null, * "defaultContent": "Edit", * "targets": [ -1 ] * } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * null, * null, * { * "data": null, * "defaultContent": "Edit" * } * ] * } ); * } ); */ "sDefaultContent": null, /** * This parameter is only used in DataTables' server-side processing. It can * be exceptionally useful to know what columns are being displayed on the * client side, and to map these to database fields. When defined, the names * also allow DataTables to reorder information from the server if it comes * back in an unexpected order (i.e. if you switch your columns around on the * client-side, your server-side code does not also need updating). * @type string * @default <i>Empty string</i> * * @name DataTable.defaults.column.name * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "name": "engine", "targets": [ 0 ] }, * { "name": "browser", "targets": [ 1 ] }, * { "name": "platform", "targets": [ 2 ] }, * { "name": "version", "targets": [ 3 ] }, * { "name": "grade", "targets": [ 4 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "name": "engine" }, * { "name": "browser" }, * { "name": "platform" }, * { "name": "version" }, * { "name": "grade" } * ] * } ); * } ); */ "sName": "", /** * Defines a data source type for the ordering which can be used to read * real-time information from the table (updating the internally cached * version) prior to ordering. This allows ordering to occur on user * editable elements such as form inputs. * @type string * @default std * * @name DataTable.defaults.column.orderDataType * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "orderDataType": "dom-text", "targets": [ 2, 3 ] }, * { "type": "numeric", "targets": [ 3 ] }, * { "orderDataType": "dom-select", "targets": [ 4 ] }, * { "orderDataType": "dom-checkbox", "targets": [ 5 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * null, * null, * { "orderDataType": "dom-text" }, * { "orderDataType": "dom-text", "type": "numeric" }, * { "orderDataType": "dom-select" }, * { "orderDataType": "dom-checkbox" } * ] * } ); * } ); */ "sSortDataType": "std", /** * The title of this column. * @type string * @default null <i>Derived from the 'TH' value for this column in the * original HTML table.</i> * * @name DataTable.defaults.column.title * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "title": "My column title", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "title": "My column title" }, * null, * null, * null, * null * ] * } ); * } ); */ "sTitle": null, /** * The type allows you to specify how the data for this column will be * ordered. Four types (string, numeric, date and html (which will strip * HTML tags before ordering)) are currently available. Note that only date * formats understood by Javascript's Date() object will be accepted as type * date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string', * 'numeric', 'date' or 'html' (by default). Further types can be adding * through plug-ins. * @type string * @default null <i>Auto-detected from raw data</i> * * @name DataTable.defaults.column.type * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "type": "html", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "type": "html" }, * null, * null, * null, * null * ] * } ); * } ); */ "sType": null, /** * Defining the width of the column, this parameter may take any CSS value * (3em, 20px etc). DataTables applies 'smart' widths to columns which have not * been given a specific width through this interface ensuring that the table * remains readable. * @type string * @default null <i>Automatic</i> * * @name DataTable.defaults.column.width * @dtopt Columns * * @example * // Using `columnDefs` * $(document).ready( function() { * $('#example').dataTable( { * "columnDefs": [ * { "width": "20%", "targets": [ 0 ] } * ] * } ); * } ); * * @example * // Using `columns` * $(document).ready( function() { * $('#example').dataTable( { * "columns": [ * { "width": "20%" }, * null, * null, * null, * null * ] * } ); * } ); */ "sWidth": null }; _fnHungarianMap( DataTable.defaults.column ); /** * DataTables settings object - this holds all the information needed for a * given table, including configuration, data and current application of the * table options. DataTables does not have a single instance for each DataTable * with the settings attached to that instance, but rather instances of the * DataTable "class" are created on-the-fly as needed (typically by a * $().dataTable() call) and the settings object is then applied to that * instance. * * Note that this object is related to {@link DataTable.defaults} but this * one is the internal data store for DataTables's cache of columns. It should * NOT be manipulated outside of DataTables. Any configuration should be done * through the initialisation options. * @namespace * @todo Really should attach the settings object to individual instances so we * don't need to create new instances on each $().dataTable() call (if the * table already exists). It would also save passing oSettings around and * into every single function. However, this is a very significant * architecture change for DataTables and will almost certainly break * backwards compatibility with older installations. This is something that * will be done in 2.0. */ DataTable.models.oSettings = { /** * Primary features of DataTables and their enablement state. * @namespace */ "oFeatures": { /** * Flag to say if DataTables should automatically try to calculate the * optimum table and columns widths (true) or not (false). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bAutoWidth": null, /** * Delay the creation of TR and TD elements until they are actually * needed by a driven page draw. This can give a significant speed * increase for Ajax source and Javascript source data, but makes no * difference at all fro DOM and server-side processing tables. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bDeferRender": null, /** * Enable filtering on the table or not. Note that if this is disabled * then there is no filtering at all on the table, including fnFilter. * To just remove the filtering input use sDom and remove the 'f' option. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bFilter": null, /** * Table information element (the 'Showing x of y records' div) enable * flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bInfo": null, /** * Present a user control allowing the end user to change the page size * when pagination is enabled. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bLengthChange": null, /** * Pagination enabled or not. Note that if this is disabled then length * changing must also be disabled. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bPaginate": null, /** * Processing indicator enable flag whenever DataTables is enacting a * user request - typically an Ajax request for server-side processing. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bProcessing": null, /** * Server-side processing enabled flag - when enabled DataTables will * get all data from the server for every draw - there is no filtering, * sorting or paging done on the client-side. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bServerSide": null, /** * Sorting enablement flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSort": null, /** * Multi-column sorting * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortMulti": null, /** * Apply a class to the columns which are being sorted to provide a * visual highlight or not. This can slow things down when enabled since * there is a lot of DOM interaction. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortClasses": null, /** * State saving enablement flag. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bStateSave": null }, /** * Scrolling settings for a table. * @namespace */ "oScroll": { /** * When the table is shorter in height than sScrollY, collapse the * table container down to the height of the table (when true). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bCollapse": null, /** * Width of the scrollbar for the web-browser's platform. Calculated * during table initialisation. * @type int * @default 0 */ "iBarWidth": 0, /** * Viewport width for horizontal scrolling. Horizontal scrolling is * disabled if an empty string. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sX": null, /** * Width to expand the table to when using x-scrolling. Typically you * should not need to use this. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @deprecated */ "sXInner": null, /** * Viewport height for vertical scrolling. Vertical scrolling is disabled * if an empty string. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sY": null }, /** * Language information for the table. * @namespace * @extends DataTable.defaults.oLanguage */ "oLanguage": { /** * Information callback function. See * {@link DataTable.defaults.fnInfoCallback} * @type function * @default null */ "fnInfoCallback": null }, /** * Browser support parameters * @namespace */ "oBrowser": { /** * Indicate if the browser incorrectly calculates width:100% inside a * scrolling element (IE6/7) * @type boolean * @default false */ "bScrollOversize": false, /** * Determine if the vertical scrollbar is on the right or left of the * scrolling container - needed for rtl language layout, although not * all browsers move the scrollbar (Safari). * @type boolean * @default false */ "bScrollbarLeft": false }, "ajax": null, /** * Array referencing the nodes which are used for the features. The * parameters of this object match what is allowed by sDom - i.e. * <ul> * <li>'l' - Length changing</li> * <li>'f' - Filtering input</li> * <li>'t' - The table!</li> * <li>'i' - Information</li> * <li>'p' - Pagination</li> * <li>'r' - pRocessing</li> * </ul> * @type array * @default [] */ "aanFeatures": [], /** * Store data information - see {@link DataTable.models.oRow} for detailed * information. * @type array * @default [] */ "aoData": [], /** * Array of indexes which are in the current display (after filtering etc) * @type array * @default [] */ "aiDisplay": [], /** * Array of indexes for display - no filtering * @type array * @default [] */ "aiDisplayMaster": [], /** * Store information about each column that is in use * @type array * @default [] */ "aoColumns": [], /** * Store information about the table's header * @type array * @default [] */ "aoHeader": [], /** * Store information about the table's footer * @type array * @default [] */ "aoFooter": [], /** * Store the applied global search information in case we want to force a * research or compare the old search to a new one. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @namespace * @extends DataTable.models.oSearch */ "oPreviousSearch": {}, /** * Store the applied search for each column - see * {@link DataTable.models.oSearch} for the format that is used for the * filtering information for each column. * @type array * @default [] */ "aoPreSearchCols": [], /** * Sorting that is applied to the table. Note that the inner arrays are * used in the following manner: * <ul> * <li>Index 0 - column number</li> * <li>Index 1 - current sorting direction</li> * </ul> * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @todo These inner arrays should really be objects */ "aaSorting": null, /** * Sorting that is always applied to the table (i.e. prefixed in front of * aaSorting). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "aaSortingFixed": [], /** * Classes to use for the striping of a table. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "asStripeClasses": null, /** * If restoring a table - we should restore its striping classes as well * @type array * @default [] */ "asDestroyStripes": [], /** * If restoring a table - we should restore its width * @type int * @default 0 */ "sDestroyWidth": 0, /** * Callback functions array for every time a row is inserted (i.e. on a draw). * @type array * @default [] */ "aoRowCallback": [], /** * Callback functions for the header on each draw. * @type array * @default [] */ "aoHeaderCallback": [], /** * Callback function for the footer on each draw. * @type array * @default [] */ "aoFooterCallback": [], /** * Array of callback functions for draw callback functions * @type array * @default [] */ "aoDrawCallback": [], /** * Array of callback functions for row created function * @type array * @default [] */ "aoRowCreatedCallback": [], /** * Callback functions for just before the table is redrawn. A return of * false will be used to cancel the draw. * @type array * @default [] */ "aoPreDrawCallback": [], /** * Callback functions for when the table has been initialised. * @type array * @default [] */ "aoInitComplete": [], /** * Callbacks for modifying the settings to be stored for state saving, prior to * saving state. * @type array * @default [] */ "aoStateSaveParams": [], /** * Callbacks for modifying the settings that have been stored for state saving * prior to using the stored values to restore the state. * @type array * @default [] */ "aoStateLoadParams": [], /** * Callbacks for operating on the settings object once the saved state has been * loaded * @type array * @default [] */ "aoStateLoaded": [], /** * Cache the table ID for quick access * @type string * @default <i>Empty string</i> */ "sTableId": "", /** * The TABLE node for the main table * @type node * @default null */ "nTable": null, /** * Permanent ref to the thead element * @type node * @default null */ "nTHead": null, /** * Permanent ref to the tfoot element - if it exists * @type node * @default null */ "nTFoot": null, /** * Permanent ref to the tbody element * @type node * @default null */ "nTBody": null, /** * Cache the wrapper node (contains all DataTables controlled elements) * @type node * @default null */ "nTableWrapper": null, /** * Indicate if when using server-side processing the loading of data * should be deferred until the second draw. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean * @default false */ "bDeferLoading": false, /** * Indicate if all required information has been read in * @type boolean * @default false */ "bInitialised": false, /** * Information about open rows. Each object in the array has the parameters * 'nTr' and 'nParent' * @type array * @default [] */ "aoOpenRows": [], /** * Dictate the positioning of DataTables' control elements - see * {@link DataTable.model.oInit.sDom}. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default null */ "sDom": null, /** * Search delay (in mS) * @type integer * @default null */ "searchDelay": null, /** * Which type of pagination should be used. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default two_button */ "sPaginationType": "two_button", /** * The state duration (for `stateSave`) in seconds. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type int * @default 0 */ "iStateDuration": 0, /** * Array of callback functions for state saving. Each array element is an * object with the following parameters: * <ul> * <li>function:fn - function to call. Takes two parameters, oSettings * and the JSON string to save that has been thus far created. Returns * a JSON string to be inserted into a json object * (i.e. '"param": [ 0, 1, 2]')</li> * <li>string:sName - name of callback</li> * </ul> * @type array * @default [] */ "aoStateSave": [], /** * Array of callback functions for state loading. Each array element is an * object with the following parameters: * <ul> * <li>function:fn - function to call. Takes two parameters, oSettings * and the object stored. May return false to cancel state loading</li> * <li>string:sName - name of callback</li> * </ul> * @type array * @default [] */ "aoStateLoad": [], /** * State that was saved. Useful for back reference * @type object * @default null */ "oSavedState": null, /** * State that was loaded. Useful for back reference * @type object * @default null */ "oLoadedState": null, /** * Source url for AJAX data for the table. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string * @default null */ "sAjaxSource": null, /** * Property from a given object from which to read the table data from. This * can be an empty string (when not server-side processing), in which case * it is assumed an an array is given directly. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sAjaxDataProp": null, /** * Note if draw should be blocked while getting data * @type boolean * @default true */ "bAjaxDataGet": true, /** * The last jQuery XHR object that was used for server-side data gathering. * This can be used for working with the XHR information in one of the * callbacks * @type object * @default null */ "jqXHR": null, /** * JSON returned from the server in the last Ajax request * @type object * @default undefined */ "json": undefined, /** * Data submitted as part of the last Ajax request * @type object * @default undefined */ "oAjaxData": undefined, /** * Function to get the server-side data. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function */ "fnServerData": null, /** * Functions which are called prior to sending an Ajax request so extra * parameters can easily be sent to the server * @type array * @default [] */ "aoServerParams": [], /** * Send the XHR HTTP method - GET or POST (could be PUT or DELETE if * required). * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type string */ "sServerMethod": null, /** * Format numbers for display. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type function */ "fnFormatNumber": null, /** * List of options that can be used for the user selectable length menu. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type array * @default [] */ "aLengthMenu": null, /** * Counter for the draws that the table does. Also used as a tracker for * server-side processing * @type int * @default 0 */ "iDraw": 0, /** * Indicate if a redraw is being done - useful for Ajax * @type boolean * @default false */ "bDrawing": false, /** * Draw index (iDraw) of the last error when parsing the returned data * @type int * @default -1 */ "iDrawError": -1, /** * Paging display length * @type int * @default 10 */ "_iDisplayLength": 10, /** * Paging start point - aiDisplay index * @type int * @default 0 */ "_iDisplayStart": 0, /** * Server-side processing - number of records in the result set * (i.e. before filtering), Use fnRecordsTotal rather than * this property to get the value of the number of records, regardless of * the server-side processing setting. * @type int * @default 0 * @private */ "_iRecordsTotal": 0, /** * Server-side processing - number of records in the current display set * (i.e. after filtering). Use fnRecordsDisplay rather than * this property to get the value of the number of records, regardless of * the server-side processing setting. * @type boolean * @default 0 * @private */ "_iRecordsDisplay": 0, /** * Flag to indicate if jQuery UI marking and classes should be used. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bJUI": null, /** * The classes to use for the table * @type object * @default {} */ "oClasses": {}, /** * Flag attached to the settings object so you can check in the draw * callback if filtering has been done in the draw. Deprecated in favour of * events. * @type boolean * @default false * @deprecated */ "bFiltered": false, /** * Flag attached to the settings object so you can check in the draw * callback if sorting has been done in the draw. Deprecated in favour of * events. * @type boolean * @default false * @deprecated */ "bSorted": false, /** * Indicate that if multiple rows are in the header and there is more than * one unique cell per column, if the top one (true) or bottom one (false) * should be used for sorting / title by DataTables. * Note that this parameter will be set by the initialisation routine. To * set a default use {@link DataTable.defaults}. * @type boolean */ "bSortCellsTop": null, /** * Initialisation object that is used for the table * @type object * @default null */ "oInit": null, /** * Destroy callback functions - for plug-ins to attach themselves to the * destroy so they can clean up markup and events. * @type array * @default [] */ "aoDestroyCallback": [], /** * Get the number of records in the current record set, before filtering * @type function */ "fnRecordsTotal": function () { return _fnDataSource( this ) == 'ssp' ? this._iRecordsTotal * 1 : this.aiDisplayMaster.length; }, /** * Get the number of records in the current record set, after filtering * @type function */ "fnRecordsDisplay": function () { return _fnDataSource( this ) == 'ssp' ? this._iRecordsDisplay * 1 : this.aiDisplay.length; }, /** * Get the display end point - aiDisplay index * @type function */ "fnDisplayEnd": function () { var len = this._iDisplayLength, start = this._iDisplayStart, calc = start + len, records = this.aiDisplay.length, features = this.oFeatures, paginate = features.bPaginate; if ( features.bServerSide ) { return paginate === false || len === -1 ? start + records : Math.min( start+len, this._iRecordsDisplay ); } else { return ! paginate || calc>records || len===-1 ? records : calc; } }, /** * The DataTables object for this table * @type object * @default null */ "oInstance": null, /** * Unique identifier for each instance of the DataTables object. If there * is an ID on the table node, then it takes that value, otherwise an * incrementing internal counter is used. * @type string * @default null */ "sInstance": null, /** * tabindex attribute value that is added to DataTables control elements, allowing * keyboard navigation of the table and its controls. */ "iTabIndex": 0, /** * DIV container for the footer scrolling table if scrolling */ "nScrollHead": null, /** * DIV container for the footer scrolling table if scrolling */ "nScrollFoot": null, /** * Last applied sort * @type array * @default [] */ "aLastSort": [], /** * Stored plug-in instances * @type object * @default {} */ "oPlugins": {} }; /** * Extension object for DataTables that is used to provide all extension * options. * * Note that the `DataTable.ext` object is available through * `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is * also aliased to `jQuery.fn.dataTableExt` for historic reasons. * @namespace * @extends DataTable.models.ext */ /** * DataTables extensions * * This namespace acts as a collection area for plug-ins that can be used to * extend DataTables capabilities. Indeed many of the build in methods * use this method to provide their own capabilities (sorting methods for * example). * * Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy * reasons * * @namespace */ DataTable.ext = _ext = { /** * Element class names * * @type object * @default {} */ classes: {}, /** * Error reporting. * * How should DataTables report an error. Can take the value 'alert' or * 'throw' * * @type string * @default alert */ errMode: "alert", /** * Feature plug-ins. * * This is an array of objects which describe the feature plug-ins that are * available to DataTables. These feature plug-ins are then available for * use through the `dom` initialisation option. * * Each feature plug-in is described by an object which must have the * following properties: * * * `fnInit` - function that is used to initialise the plug-in, * * `cFeature` - a character so the feature can be enabled by the `dom` * instillation option. This is case sensitive. * * The `fnInit` function has the following input parameters: * * 1. `{object}` DataTables settings object: see * {@link DataTable.models.oSettings} * * And the following return is expected: * * * {node|null} The element which contains your feature. Note that the * return may also be void if your plug-in does not require to inject any * DOM elements into DataTables control (`dom`) - for example this might * be useful when developing a plug-in which allows table control via * keyboard entry * * @type array * * @example * $.fn.dataTable.ext.features.push( { * "fnInit": function( oSettings ) { * return new TableTools( { "oDTSettings": oSettings } ); * }, * "cFeature": "T" * } ); */ feature: [], /** * Row searching. * * This method of searching is complimentary to the default type based * searching, and a lot more comprehensive as it allows you complete control * over the searching logic. Each element in this array is a function * (parameters described below) that is called for every row in the table, * and your logic decides if it should be included in the searching data set * or not. * * Searching functions have the following input parameters: * * 1. `{object}` DataTables settings object: see * {@link DataTable.models.oSettings} * 2. `{array|object}` Data for the row to be processed (same as the * original format that was passed in as the data source, or an array * from a DOM data source * 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which * can be useful to retrieve the `TR` element if you need DOM interaction. * * And the following return is expected: * * * {boolean} Include the row in the searched result set (true) or not * (false) * * Note that as with the main search ability in DataTables, technically this * is "filtering", since it is subtractive. However, for consistency in * naming we call it searching here. * * @type array * @default [] * * @example * // The following example shows custom search being applied to the * // fourth column (i.e. the data[3] index) based on two input values * // from the end-user, matching the data in a certain range. * $.fn.dataTable.ext.search.push( * function( settings, data, dataIndex ) { * var min = document.getElementById('min').value * 1; * var max = document.getElementById('max').value * 1; * var version = data[3] == "-" ? 0 : data[3]*1; * * if ( min == "" && max == "" ) { * return true; * } * else if ( min == "" && version < max ) { * return true; * } * else if ( min < version && "" == max ) { * return true; * } * else if ( min < version && version < max ) { * return true; * } * return false; * } * ); */ search: [], /** * Internal functions, exposed for used in plug-ins. * * Please note that you should not need to use the internal methods for * anything other than a plug-in (and even then, try to avoid if possible). * The internal function may change between releases. * * @type object * @default {} */ internal: {}, /** * Legacy configuration options. Enable and disable legacy options that * are available in DataTables. * * @type object */ legacy: { /** * Enable / disable DataTables 1.9 compatible server-side processing * requests * * @type boolean * @default null */ ajax: null }, /** * Pagination plug-in methods. * * Each entry in this object is a function and defines which buttons should * be shown by the pagination rendering method that is used for the table: * {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the * buttons are displayed in the document, while the functions here tell it * what buttons to display. This is done by returning an array of button * descriptions (what each button will do). * * Pagination types (the four built in options and any additional plug-in * options defined here) can be used through the `paginationType` * initialisation parameter. * * The functions defined take two parameters: * * 1. `{int} page` The current page index * 2. `{int} pages` The number of pages in the table * * Each function is expected to return an array where each element of the * array can be one of: * * * `first` - Jump to first page when activated * * `last` - Jump to last page when activated * * `previous` - Show previous page when activated * * `next` - Show next page when activated * * `{int}` - Show page of the index given * * `{array}` - A nested array containing the above elements to add a * containing 'DIV' element (might be useful for styling). * * Note that DataTables v1.9- used this object slightly differently whereby * an object with two functions would be defined for each plug-in. That * ability is still supported by DataTables 1.10+ to provide backwards * compatibility, but this option of use is now decremented and no longer * documented in DataTables 1.10+. * * @type object * @default {} * * @example * // Show previous, next and current page buttons only * $.fn.dataTableExt.oPagination.current = function ( page, pages ) { * return [ 'previous', page, 'next' ]; * }; */ pager: {}, renderer: { pageButton: {}, header: {} }, /** * Ordering plug-ins - custom data source * * The extension options for ordering of data available here is complimentary * to the default type based ordering that DataTables typically uses. It * allows much greater control over the the data that is being used to * order a column, but is necessarily therefore more complex. * * This type of ordering is useful if you want to do ordering based on data * live from the DOM (for example the contents of an 'input' element) rather * than just the static string that DataTables knows of. * * The way these plug-ins work is that you create an array of the values you * wish to be ordering for the column in question and then return that * array. The data in the array much be in the index order of the rows in * the table (not the currently ordering order!). Which order data gathering * function is run here depends on the `dt-init columns.orderDataType` * parameter that is used for the column (if any). * * The functions defined take two parameters: * * 1. `{object}` DataTables settings object: see * {@link DataTable.models.oSettings} * 2. `{int}` Target column index * * Each function is expected to return an array: * * * `{array}` Data for the column to be ordering upon * * @type array * * @example * // Ordering using `input` node values * $.fn.dataTable.ext.order['dom-text'] = function ( settings, col ) * { * return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) { * return $('input', td).val(); * } ); * } */ order: {}, /** * Type based plug-ins. * * Each column in DataTables has a type assigned to it, either by automatic * detection or by direct assignment using the `type` option for the column. * The type of a column will effect how it is ordering and search (plug-ins * can also make use of the column type if required). * * @namespace */ type: { /** * Type detection functions. * * The functions defined in this object are used to automatically detect * a column's type, making initialisation of DataTables super easy, even * when complex data is in the table. * * The functions defined take two parameters: * * 1. `{*}` Data from the column cell to be analysed * 2. `{settings}` DataTables settings object. This can be used to * perform context specific type detection - for example detection * based on language settings such as using a comma for a decimal * place. Generally speaking the options from the settings will not * be required * * Each function is expected to return: * * * `{string|null}` Data type detected, or null if unknown (and thus * pass it on to the other type detection functions. * * @type array * * @example * // Currency type detection plug-in: * $.fn.dataTable.ext.type.detect.push( * function ( data, settings ) { * // Check the numeric part * if ( ! $.isNumeric( data.substring(1) ) ) { * return null; * } * * // Check prefixed by currency * if ( data.charAt(0) == '$' || data.charAt(0) == '£' ) { * return 'currency'; * } * return null; * } * ); */ detect: [], /** * Type based search formatting. * * The type based searching functions can be used to pre-format the * data to be search on. For example, it can be used to strip HTML * tags or to de-format telephone numbers for numeric only searching. * * Note that is a search is not defined for a column of a given type, * no search formatting will be performed. * * Pre-processing of searching data plug-ins - When you assign the sType * for a column (or have it automatically detected for you by DataTables * or a type detection plug-in), you will typically be using this for * custom sorting, but it can also be used to provide custom searching * by allowing you to pre-processing the data and returning the data in * the format that should be searched upon. This is done by adding * functions this object with a parameter name which matches the sType * for that target column. This is the corollary of <i>afnSortData</i> * for searching data. * * The functions defined take a single parameter: * * 1. `{*}` Data from the column cell to be prepared for searching * * Each function is expected to return: * * * `{string|null}` Formatted string that will be used for the searching. * * @type object * @default {} * * @example * $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) { * return d.replace(/\n/g," ").replace( /<.*?>/g, "" ); * } */ search: {}, /** * Type based ordering. * * The column type tells DataTables what ordering to apply to the table * when a column is sorted upon. The order for each type that is defined, * is defined by the functions available in this object. * * Each ordering option can be described by three properties added to * this object: * * * `{type}-pre` - Pre-formatting function * * `{type}-asc` - Ascending order function * * `{type}-desc` - Descending order function * * All three can be used together, only `{type}-pre` or only * `{type}-asc` and `{type}-desc` together. It is generally recommended * that only `{type}-pre` is used, as this provides the optimal * implementation in terms of speed, although the others are provided * for compatibility with existing Javascript sort functions. * * `{type}-pre`: Functions defined take a single parameter: * * 1. `{*}` Data from the column cell to be prepared for ordering * * And return: * * * `{*}` Data to be sorted upon * * `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort * functions, taking two parameters: * * 1. `{*}` Data to compare to the second parameter * 2. `{*}` Data to compare to the first parameter * * And returning: * * * `{*}` Ordering match: <0 if first parameter should be sorted lower * than the second parameter, ===0 if the two parameters are equal and * >0 if the first parameter should be sorted height than the second * parameter. * * @type object * @default {} * * @example * // Numeric ordering of formatted numbers with a pre-formatter * $.extend( $.fn.dataTable.ext.type.order, { * "string-pre": function(x) { * a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" ); * return parseFloat( a ); * } * } ); * * @example * // Case-sensitive string ordering, with no pre-formatting method * $.extend( $.fn.dataTable.ext.order, { * "string-case-asc": function(x,y) { * return ((x < y) ? -1 : ((x > y) ? 1 : 0)); * }, * "string-case-desc": function(x,y) { * return ((x < y) ? 1 : ((x > y) ? -1 : 0)); * } * } ); */ order: {} }, /** * Unique DataTables instance counter * * @type int * @private */ _unique: 0, // // Depreciated // The following properties are retained for backwards compatiblity only. // The should not be used in new projects and will be removed in a future // version // /** * Version check function. * @type function * @depreciated Since 1.10 */ fnVersionCheck: DataTable.fnVersionCheck, /** * Index for what 'this' index API functions should use * @type int * @deprecated Since v1.10 */ iApiIndex: 0, /** * jQuery UI class container * @type object * @deprecated Since v1.10 */ oJUIClasses: {}, /** * Software version * @type string * @deprecated Since v1.10 */ sVersion: DataTable.version }; // // Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts // $.extend( _ext, { afnFiltering: _ext.search, aTypes: _ext.type.detect, ofnSearch: _ext.type.search, oSort: _ext.type.order, afnSortData: _ext.order, aoFeatures: _ext.feature, oApi: _ext.internal, oStdClasses: _ext.classes, oPagination: _ext.pager } ); $.extend( DataTable.ext.classes, { "sTable": "dataTable", "sNoFooter": "no-footer", /* Paging buttons */ "sPageButton": "paginate_button", "sPageButtonActive": "current", "sPageButtonDisabled": "disabled", /* Striping classes */ "sStripeOdd": "odd", "sStripeEven": "even", /* Empty row */ "sRowEmpty": "dataTables_empty", /* Features */ "sWrapper": "dataTables_wrapper", "sFilter": "dataTables_filter", "sInfo": "dataTables_info", "sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */ "sLength": "dataTables_length", "sProcessing": "dataTables_processing", /* Sorting */ "sSortAsc": "sorting_asc", "sSortDesc": "sorting_desc", "sSortable": "sorting", /* Sortable in both directions */ "sSortableAsc": "sorting_asc_disabled", "sSortableDesc": "sorting_desc_disabled", "sSortableNone": "sorting_disabled", "sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */ /* Filtering */ "sFilterInput": "", /* Page length */ "sLengthSelect": "", /* Scrolling */ "sScrollWrapper": "dataTables_scroll", "sScrollHead": "dataTables_scrollHead", "sScrollHeadInner": "dataTables_scrollHeadInner", "sScrollBody": "dataTables_scrollBody", "sScrollFoot": "dataTables_scrollFoot", "sScrollFootInner": "dataTables_scrollFootInner", /* Misc */ "sHeaderTH": "", "sFooterTH": "", // Deprecated "sSortJUIAsc": "", "sSortJUIDesc": "", "sSortJUI": "", "sSortJUIAscAllowed": "", "sSortJUIDescAllowed": "", "sSortJUIWrapper": "", "sSortIcon": "", "sJUIHeader": "", "sJUIFooter": "" } ); (function() { // Reused strings for better compression. Closure compiler appears to have a // weird edge case where it is trying to expand strings rather than use the // variable version. This results in about 200 bytes being added, for very // little preference benefit since it this run on script load only. var _empty = ''; _empty = ''; var _stateDefault = _empty + 'ui-state-default'; var _sortIcon = _empty + 'css_right ui-icon ui-icon-'; var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix'; $.extend( DataTable.ext.oJUIClasses, DataTable.ext.classes, { /* Full numbers paging buttons */ "sPageButton": "fg-button ui-button "+_stateDefault, "sPageButtonActive": "ui-state-disabled", "sPageButtonDisabled": "ui-state-disabled", /* Features */ "sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi "+ "ui-buttonset-multi paging_", /* Note that the type is postfixed */ /* Sorting */ "sSortAsc": _stateDefault+" sorting_asc", "sSortDesc": _stateDefault+" sorting_desc", "sSortable": _stateDefault+" sorting", "sSortableAsc": _stateDefault+" sorting_asc_disabled", "sSortableDesc": _stateDefault+" sorting_desc_disabled", "sSortableNone": _stateDefault+" sorting_disabled", "sSortJUIAsc": _sortIcon+"triangle-1-n", "sSortJUIDesc": _sortIcon+"triangle-1-s", "sSortJUI": _sortIcon+"carat-2-n-s", "sSortJUIAscAllowed": _sortIcon+"carat-1-n", "sSortJUIDescAllowed": _sortIcon+"carat-1-s", "sSortJUIWrapper": "DataTables_sort_wrapper", "sSortIcon": "DataTables_sort_icon", /* Scrolling */ "sScrollHead": "dataTables_scrollHead "+_stateDefault, "sScrollFoot": "dataTables_scrollFoot "+_stateDefault, /* Misc */ "sHeaderTH": _stateDefault, "sFooterTH": _stateDefault, "sJUIHeader": _headerFooter+" ui-corner-tl ui-corner-tr", "sJUIFooter": _headerFooter+" ui-corner-bl ui-corner-br" } ); }()); var extPagination = DataTable.ext.pager; function _numbers ( page, pages ) { var numbers = [], buttons = extPagination.numbers_length, half = Math.floor( buttons / 2 ), i = 1; if ( pages <= buttons ) { numbers = _range( 0, pages ); } else if ( page <= half ) { numbers = _range( 0, buttons-2 ); numbers.push( 'ellipsis' ); numbers.push( pages-1 ); } else if ( page >= pages - 1 - half ) { numbers = _range( pages-(buttons-2), pages ); numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6 numbers.splice( 0, 0, 0 ); } else { numbers = _range( page-1, page+2 ); numbers.push( 'ellipsis' ); numbers.push( pages-1 ); numbers.splice( 0, 0, 'ellipsis' ); numbers.splice( 0, 0, 0 ); } numbers.DT_el = 'span'; return numbers; } $.extend( extPagination, { simple: function ( page, pages ) { return [ 'previous', 'next' ]; }, full: function ( page, pages ) { return [ 'first', 'previous', 'next', 'last' ]; }, simple_numbers: function ( page, pages ) { return [ 'previous', _numbers(page, pages), 'next' ]; }, full_numbers: function ( page, pages ) { return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ]; }, // For testing and plug-ins to use _numbers: _numbers, numbers_length: 7 } ); $.extend( true, DataTable.ext.renderer, { pageButton: { _: function ( settings, host, idx, buttons, page, pages ) { var classes = settings.oClasses; var lang = settings.oLanguage.oPaginate; var btnDisplay, btnClass, counter=0; var attach = function( container, buttons ) { var i, ien, node, button; var clickHandler = function ( e ) { _fnPageChange( settings, e.data.action, true ); }; for ( i=0, ien=buttons.length ; i<ien ; i++ ) { button = buttons[i]; if ( $.isArray( button ) ) { var inner = $( '<'+(button.DT_el || 'div')+'/>' ) .appendTo( container ); attach( inner, button ); } else { btnDisplay = ''; btnClass = ''; switch ( button ) { case 'ellipsis': container.append('<span>…</span>'); break; case 'first': btnDisplay = lang.sFirst; btnClass = button + (page > 0 ? '' : ' '+classes.sPageButtonDisabled); break; case 'previous': btnDisplay = lang.sPrevious; btnClass = button + (page > 0 ? '' : ' '+classes.sPageButtonDisabled); break; case 'next': btnDisplay = lang.sNext; btnClass = button + (page < pages-1 ? '' : ' '+classes.sPageButtonDisabled); break; case 'last': btnDisplay = lang.sLast; btnClass = button + (page < pages-1 ? '' : ' '+classes.sPageButtonDisabled); break; default: btnDisplay = button + 1; btnClass = page === button ? classes.sPageButtonActive : ''; break; } if ( btnDisplay ) { node = $('<a>', { 'class': classes.sPageButton+' '+btnClass, 'aria-controls': settings.sTableId, 'data-dt-idx': counter, 'tabindex': settings.iTabIndex, 'id': idx === 0 && typeof button === 'string' ? settings.sTableId +'_'+ button : null } ) .html( btnDisplay ) .appendTo( container ); _fnBindAction( node, {action: button}, clickHandler ); counter++; } } } }; // IE9 throws an 'unknown error' if document.activeElement is used // inside an iframe or frame. Try / catch the error. Not good for // accessibility, but neither are frames. try { // Because this approach is destroying and recreating the paging // elements, focus is lost on the select button which is bad for // accessibility. So we want to restore focus once the draw has // completed var activeEl = $(document.activeElement).data('dt-idx'); attach( $(host).empty(), buttons ); if ( activeEl !== null ) { $(host).find( '[data-dt-idx='+activeEl+']' ).focus(); } } catch (e) {} } } } ); // Built in type detection. See model.ext.aTypes for information about // what is required from this methods. $.extend( DataTable.ext.type.detect, [ // Plain numbers - first since V8 detects some plain numbers as dates // e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...). function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _isNumber( d, decimal ) ? 'num'+decimal : null; }, // Dates (only those recognised by the browser's Date.parse) function ( d, settings ) { // V8 will remove any unknown characters at the start and end of the // expression, leading to false matches such as `$245.12` or `10%` being // a valid date. See forum thread 18941 for detail. if ( d && !(d instanceof Date) && ( ! _re_date_start.test(d) || ! _re_date_end.test(d) ) ) { return null; } var parsed = Date.parse(d); return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null; }, // Formatted numbers function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null; }, // HTML numeric function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null; }, // HTML numeric, formatted function ( d, settings ) { var decimal = settings.oLanguage.sDecimal; return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null; }, // HTML (this is strict checking - there must be html) function ( d, settings ) { return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ? 'html' : null; } ] ); // Filter formatting functions. See model.ext.ofnSearch for information about // what is required from these methods. // // Note that additional search methods are added for the html numbers and // html formatted numbers by `_addNumericSort()` when we know what the decimal // place is $.extend( DataTable.ext.type.search, { html: function ( data ) { return _empty(data) ? data : typeof data === 'string' ? data .replace( _re_new_lines, " " ) .replace( _re_html, "" ) : ''; }, string: function ( data ) { return _empty(data) ? data : typeof data === 'string' ? data.replace( _re_new_lines, " " ) : data; } } ); var __numericReplace = function ( d, decimalPlace, re1, re2 ) { if ( d !== 0 && (!d || d === '-') ) { return -Infinity; } // If a decimal place other than `.` is used, it needs to be given to the // function so we can detect it and replace with a `.` which is the only // decimal place Javascript recognises - it is not locale aware. if ( decimalPlace ) { d = _numToDecimal( d, decimalPlace ); } if ( d.replace ) { if ( re1 ) { d = d.replace( re1, '' ); } if ( re2 ) { d = d.replace( re2, '' ); } } return d * 1; }; // Add the numeric 'deformatting' functions for sorting and search. This is done // in a function to provide an easy ability for the language options to add // additional methods if a non-period decimal place is used. function _addNumericSort ( decimalPlace ) { $.each( { // Plain numbers "num": function ( d ) { return __numericReplace( d, decimalPlace ); }, // Formatted numbers "num-fmt": function ( d ) { return __numericReplace( d, decimalPlace, _re_formatted_numeric ); }, // HTML numeric "html-num": function ( d ) { return __numericReplace( d, decimalPlace, _re_html ); }, // HTML numeric, formatted "html-num-fmt": function ( d ) { return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric ); } }, function ( key, fn ) { // Add the ordering method _ext.type.order[ key+decimalPlace+'-pre' ] = fn; // For HTML types add a search formatter that will strip the HTML if ( key.match(/^html\-/) ) { _ext.type.search[ key+decimalPlace ] = _ext.type.search.html; } } ); } // Default sort methods $.extend( _ext.type.order, { // Dates "date-pre": function ( d ) { return Date.parse( d ) || 0; }, // html "html-pre": function ( a ) { return _empty(a) ? '' : a.replace ? a.replace( /<.*?>/g, "" ).toLowerCase() : a+''; }, // string "string-pre": function ( a ) { // This is a little complex, but faster than always calling toString, // http://jsperf.com/tostring-v-check return _empty(a) ? '' : typeof a === 'string' ? a.toLowerCase() : ! a.toString ? '' : a.toString(); }, // string-asc and -desc are retained only for compatibility with the old // sort methods "string-asc": function ( x, y ) { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }, "string-desc": function ( x, y ) { return ((x < y) ? 1 : ((x > y) ? -1 : 0)); } } ); // Numeric sorting types - order doesn't matter here _addNumericSort( '' ); $.extend( true, DataTable.ext.renderer, { header: { _: function ( settings, cell, column, classes ) { // No additional mark-up required // Attach a sort listener to update on sort - note that using the // `DT` namespace will allow the event to be removed automatically // on destroy, while the `dt` namespaced event is the one we are // listening for $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) { if ( settings !== ctx ) { // need to check this this is the host return; // table, not a nested one } var colIdx = column.idx; cell .removeClass( column.sSortingClass +' '+ classes.sSortAsc +' '+ classes.sSortDesc ) .addClass( columns[ colIdx ] == 'asc' ? classes.sSortAsc : columns[ colIdx ] == 'desc' ? classes.sSortDesc : column.sSortingClass ); } ); }, jqueryui: function ( settings, cell, column, classes ) { $('<div/>') .addClass( classes.sSortJUIWrapper ) .append( cell.contents() ) .append( $('<span/>') .addClass( classes.sSortIcon+' '+column.sSortingClassJUI ) ) .appendTo( cell ); // Attach a sort listener to update on sort $(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) { if ( settings !== ctx ) { return; } var colIdx = column.idx; cell .removeClass( classes.sSortAsc +" "+classes.sSortDesc ) .addClass( columns[ colIdx ] == 'asc' ? classes.sSortAsc : columns[ colIdx ] == 'desc' ? classes.sSortDesc : column.sSortingClass ); cell .find( 'span.'+classes.sSortIcon ) .removeClass( classes.sSortJUIAsc +" "+ classes.sSortJUIDesc +" "+ classes.sSortJUI +" "+ classes.sSortJUIAscAllowed +" "+ classes.sSortJUIDescAllowed ) .addClass( columns[ colIdx ] == 'asc' ? classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ? classes.sSortJUIDesc : column.sSortingClassJUI ); } ); } } } ); /* * Public helper functions. These aren't used internally by DataTables, or * called by any of the options passed into DataTables, but they can be used * externally by developers working with DataTables. They are helper functions * to make working with DataTables a little bit easier. */ /** * Helpers for `columns.render`. * * The options defined here can be used with the `columns.render` initialisation * option to provide a display renderer. The following functions are defined: * * * `number` - Will format numeric data (defined by `columns.data`) for * display, retaining the original unformatted data for sorting and filtering. * It takes 4 parameters: * * `string` - Thousands grouping separator * * `string` - Decimal point indicator * * `integer` - Number of decimal points to show * * `string` (optional) - Prefix. * * @example * // Column definition using the number renderer * { * data: "salary", * render: $.fn.dataTable.render.number( '\'', '.', 0, '$' ) * } * * @namespace */ DataTable.render = { number: function ( thousands, decimal, precision, prefix ) { return { display: function ( d ) { var negative = d < 0 ? '-' : ''; d = Math.abs( parseFloat( d ) ); var intPart = parseInt( d, 10 ); var floatPart = precision ? decimal+(d - intPart).toFixed( precision ).substring( 2 ): ''; return negative + (prefix||'') + intPart.toString().replace( /\B(?=(\d{3})+(?!\d))/g, thousands ) + floatPart; } }; } }; /* * This is really a good bit rubbish this method of exposing the internal methods * publicly... - To be fixed in 2.0 using methods on the prototype */ /** * Create a wrapper function for exporting an internal functions to an external API. * @param {string} fn API function name * @returns {function} wrapped function * @memberof DataTable#internal */ function _fnExternApiFunc (fn) { return function() { var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat( Array.prototype.slice.call(arguments) ); return DataTable.ext.internal[fn].apply( this, args ); }; } /** * Reference to internal functions for use by plug-in developers. Note that * these methods are references to internal functions and are considered to be * private. If you use these methods, be aware that they are liable to change * between versions. * @namespace */ $.extend( DataTable.ext.internal, { _fnExternApiFunc: _fnExternApiFunc, _fnBuildAjax: _fnBuildAjax, _fnAjaxUpdate: _fnAjaxUpdate, _fnAjaxParameters: _fnAjaxParameters, _fnAjaxUpdateDraw: _fnAjaxUpdateDraw, _fnAjaxDataSrc: _fnAjaxDataSrc, _fnAddColumn: _fnAddColumn, _fnColumnOptions: _fnColumnOptions, _fnAdjustColumnSizing: _fnAdjustColumnSizing, _fnVisibleToColumnIndex: _fnVisibleToColumnIndex, _fnColumnIndexToVisible: _fnColumnIndexToVisible, _fnVisbleColumns: _fnVisbleColumns, _fnGetColumns: _fnGetColumns, _fnColumnTypes: _fnColumnTypes, _fnApplyColumnDefs: _fnApplyColumnDefs, _fnHungarianMap: _fnHungarianMap, _fnCamelToHungarian: _fnCamelToHungarian, _fnLanguageCompat: _fnLanguageCompat, _fnBrowserDetect: _fnBrowserDetect, _fnAddData: _fnAddData, _fnAddTr: _fnAddTr, _fnNodeToDataIndex: _fnNodeToDataIndex, _fnNodeToColumnIndex: _fnNodeToColumnIndex, _fnGetCellData: _fnGetCellData, _fnSetCellData: _fnSetCellData, _fnSplitObjNotation: _fnSplitObjNotation, _fnGetObjectDataFn: _fnGetObjectDataFn, _fnSetObjectDataFn: _fnSetObjectDataFn, _fnGetDataMaster: _fnGetDataMaster, _fnClearTable: _fnClearTable, _fnDeleteIndex: _fnDeleteIndex, _fnInvalidate: _fnInvalidate, _fnGetRowElements: _fnGetRowElements, _fnCreateTr: _fnCreateTr, _fnBuildHead: _fnBuildHead, _fnDrawHead: _fnDrawHead, _fnDraw: _fnDraw, _fnReDraw: _fnReDraw, _fnAddOptionsHtml: _fnAddOptionsHtml, _fnDetectHeader: _fnDetectHeader, _fnGetUniqueThs: _fnGetUniqueThs, _fnFeatureHtmlFilter: _fnFeatureHtmlFilter, _fnFilterComplete: _fnFilterComplete, _fnFilterCustom: _fnFilterCustom, _fnFilterColumn: _fnFilterColumn, _fnFilter: _fnFilter, _fnFilterCreateSearch: _fnFilterCreateSearch, _fnEscapeRegex: _fnEscapeRegex, _fnFilterData: _fnFilterData, _fnFeatureHtmlInfo: _fnFeatureHtmlInfo, _fnUpdateInfo: _fnUpdateInfo, _fnInfoMacros: _fnInfoMacros, _fnInitialise: _fnInitialise, _fnInitComplete: _fnInitComplete, _fnLengthChange: _fnLengthChange, _fnFeatureHtmlLength: _fnFeatureHtmlLength, _fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate, _fnPageChange: _fnPageChange, _fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing, _fnProcessingDisplay: _fnProcessingDisplay, _fnFeatureHtmlTable: _fnFeatureHtmlTable, _fnScrollDraw: _fnScrollDraw, _fnApplyToChildren: _fnApplyToChildren, _fnCalculateColumnWidths: _fnCalculateColumnWidths, _fnThrottle: _fnThrottle, _fnConvertToWidth: _fnConvertToWidth, _fnScrollingWidthAdjust: _fnScrollingWidthAdjust, _fnGetWidestNode: _fnGetWidestNode, _fnGetMaxLenString: _fnGetMaxLenString, _fnStringToCss: _fnStringToCss, _fnScrollBarWidth: _fnScrollBarWidth, _fnSortFlatten: _fnSortFlatten, _fnSort: _fnSort, _fnSortAria: _fnSortAria, _fnSortListener: _fnSortListener, _fnSortAttachListener: _fnSortAttachListener, _fnSortingClasses: _fnSortingClasses, _fnSortData: _fnSortData, _fnSaveState: _fnSaveState, _fnLoadState: _fnLoadState, _fnSettingsFromNode: _fnSettingsFromNode, _fnLog: _fnLog, _fnMap: _fnMap, _fnBindAction: _fnBindAction, _fnCallbackReg: _fnCallbackReg, _fnCallbackFire: _fnCallbackFire, _fnLengthOverflow: _fnLengthOverflow, _fnRenderer: _fnRenderer, _fnDataSource: _fnDataSource, _fnRowAttributes: _fnRowAttributes, _fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant // in 1.10, so this dead-end function is // added to prevent errors } ); // jQuery access $.fn.dataTable = DataTable; // Legacy aliases $.fn.dataTableSettings = DataTable.settings; $.fn.dataTableExt = DataTable.ext; // With a capital `D` we return a DataTables API instance rather than a // jQuery object $.fn.DataTable = function ( opts ) { return $(this).dataTable( opts ).api(); }; // All properties that are available to $.fn.dataTable should also be // available on $.fn.DataTable $.each( DataTable, function ( prop, val ) { $.fn.DataTable[ prop ] = val; } ); // Information about events fired by DataTables - for documentation. /** * Draw event, fired whenever the table is redrawn on the page, at the same * point as fnDrawCallback. This may be useful for binding events or * performing calculations when the table is altered at all. * @name DataTable#draw.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Search event, fired when the searching applied to the table (using the * built-in global search, or column filters) is altered. * @name DataTable#search.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Page change event, fired when the paging of the table is altered. * @name DataTable#page.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Order event, fired when the ordering applied to the table is altered. * @name DataTable#order.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * DataTables initialisation complete event, fired when the table is fully * drawn, including Ajax data loaded, if Ajax data is required. * @name DataTable#init.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The JSON object request from the server - only * present if client-side Ajax sourced data is used</li></ol> */ /** * State save event, fired when the table has changed state a new state save * is required. This event allows modification of the state saving object * prior to actually doing the save, including addition or other state * properties (for plug-ins) or modification of a DataTables core property. * @name DataTable#stateSaveParams.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The state information to be saved */ /** * State load event, fired when the table is loading state from the stored * data, but prior to the settings object being modified by the saved state * - allowing modification of the saved state is required or loading of * state for a plug-in. * @name DataTable#stateLoadParams.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The saved state information */ /** * State loaded event, fired when state has been loaded from stored data and * the settings object has been modified by the loaded data. * @name DataTable#stateLoaded.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {object} json The saved state information */ /** * Processing event, fired when DataTables is doing some kind of processing * (be it, order, searcg or anything else). It can be used to indicate to * the end user that there is something happening, or that something has * finished. * @name DataTable#processing.dt * @event * @param {event} e jQuery event object * @param {object} oSettings DataTables settings object * @param {boolean} bShow Flag for if DataTables is doing processing or not */ /** * Ajax (XHR) event, fired whenever an Ajax request is completed from a * request to made to the server for new data. This event is called before * DataTables processed the returned data, so it can also be used to pre- * process the data returned from the server, if needed. * * Note that this trigger is called in `fnServerData`, if you override * `fnServerData` and which to use this event, you need to trigger it in you * success function. * @name DataTable#xhr.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {object} json JSON returned from the server * * @example * // Use a custom property returned from the server in another DOM element * $('#table').dataTable().on('xhr.dt', function (e, settings, json) { * $('#status').html( json.status ); * } ); * * @example * // Pre-process the data returned from the server * $('#table').dataTable().on('xhr.dt', function (e, settings, json) { * for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) { * json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two; * } * // Note no return - manipulate the data directly in the JSON object. * } ); */ /** * Destroy event, fired when the DataTable is destroyed by calling fnDestroy * or passing the bDestroy:true parameter in the initialisation object. This * can be used to remove bound events, added DOM nodes, etc. * @name DataTable#destroy.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Page length change event, fired when number of records to show on each * page (the length) is changed. * @name DataTable#length.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {integer} len New length */ /** * Column sizing has changed. * @name DataTable#column-sizing.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} */ /** * Column visibility has changed. * @name DataTable#column-visibility.dt * @event * @param {event} e jQuery event object * @param {object} o DataTables settings object {@link DataTable.models.oSettings} * @param {int} column Column index * @param {bool} vis `false` if column now hidden, or `true` if visible */ return $.fn.dataTable; })); }(window, document)); /* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ ?¤??? ?????", "oPaginate":{"sPrevious":"?????", "sNext":"?????"}, "sSearch":"???" } } ); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).addClass('pagination').append( '<ul>'+ '<li class="prev disabled"><a href="#">← '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' → </a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); } /* Table initialisation */ /*$(document).ready(function() { $('#example').dataTable( { "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ ?¤??? ?????" } } ); } );*/ // by ?????? https://github.com/RubyLouvre/mass-Framework/blob/master/browers/lang.js var DONT_ENUM = "propertyIsEnumerable, isPrototypeOf, hasOwnProperty, toLocaleString, toString, valueOf, constructor".split(","), hasOwn = ({}).hasOwnProperty; for (var i in { toString: 1 }){ DONT_ENUM =false; } Object.keys = Object.keys || function(obj){ var result =[]; for(var key in obj) if(hasOwn.call(obj, key)){ result.push(key) } if(DONT_ENUM && obj){ for(var i = 0; key = DONT_ENUM[i++];){ if(hasOwn.call(obj, key)){ reslut.push(key); } } } return result; }; function PostMan(config) { var win = config.target; if (typeof win == "string") { win = $(win).get(0); if (win && win.tagName === "IFRAME") { win = win.contentWindow; } } else { win = parent; } this.win = win; this._callbacks = []; var mode = document.documentMode; if (mode === 8 || mode === 9) { this.hack = true; } if (typeof config.onmessage === "function") { this.receive(config.onmessage); } this.init(); }; PostMan.prototype = { init: function () { var me = this; me._callback = function (event) { if (event.originalEvent.source != me.win) { return; } var data = event.originalEvent.data; //event.originalEvent.data for jquery when event is postMessage if (typeof data === "string" && data.indexOf("__hack__") === 0) { data = data.replace("__hack__", ""); data = JSON.parse(data, function (k, v) { if (v.indexOf && v.indexOf('function') > -1) { return eval("(function(){return " + v + "})()"); } return v; }); } for (var i = 0, fn; fn = me._callbacks[i++];) { fn.call(me, data); } } //$(window).on("message", me._callback); $(window).bind( "message", me._callback); }, receive: function (fn) { fn.win = this.win; this._callbacks.push(fn); }, send: function (data) { var str = data, hack = false; if (!this.hack && typeof data == "object") { for (var i in data) { if (data.hasOwnProperty(i) && typeof data[i] === "function") { hack = true break; } } } if (hack || (this.hack && typeof str !== "string")) { str = JSON.stringify(str, function (k, v) { if (typeof v === 'function') { return v + ''; } return v; }); data = "__hack__" + str; } console.log("send message ", data); this.win.postMessage(data, '*');//* targetOrgin URI }, destroy: function () { if (this._callback) { $.unbind(this.win, "message", this._callback); } if (document.detachEvent && this._dataavailable) { document.detachEvent('ondataavailable', this._dataavailable); } for (var p in this) { if (this.hasOwnProperty(p)) { delete this[p]; } } navigator.messages = void 0; } }; if (!"1"[0]) {// ie6 ,ie7 PostMan.prototype.init = function () { var isSameOrigin = false; try { isSameOrigin = !!this.win.locaction.href; } catch (e) { } if (isSameOrigin) { this.initForSameOrigin(); } else { this.initForCrossDomain(); } }; PostMan.prototype.initForCrossDomain = function () { var fns = navigator.messages = navigator.messages || []; var me = this; for (var i = 0, fn; fn = this._callbacks[i++];) { fns.push(fn); } this.receive = function (fn) { fn.win = this.win; fns.push(fn); }; this.send = function (data) { setTimeout(function () { for (var i = 0, fn; fn = fns[i++];) { if (fn.win != me.win) { fn.call(me.data); } } }); }; }; PostMan.prototype.initForSameOrigin = function () { var me = this; this.send = function (data) { setTimeout(function () { var event = me.win.document.createEventObject(); event.eventType = 'message'; event.eventSource = window; event.eventData = data; me.win.document.fireEvent('ondataavailable', event); }); }; this._dataavailable = function (event) { if (event.eventType !== 'message' || event.eventSource != me.win) { return; } for (var i = 0, fn; fn = me._callbacks[i++];) { fn.call(me, event.eventData); } }; document.attachEvent('ondataavailable', this._dataavailable); } }; // Tell IE9 to use its built-in console if (Function.prototype.bind && console && typeof console.log == "object") { ["log","info","warn","error","assert","dir","clear","profile","profileEnd"] .forEach(function (method) { console[method] = this.call(console[method], console); }, Function.prototype.bind); } // log() -- The complete, cross-browser (we don't judge!) console.log wrapper for his or her logging pleasure if (!window.log) { window.log = function () { log.history = log.history || []; // store logs to an array for reference log.history.push(arguments); // Modern browsers if (typeof console != 'undefined' && typeof console.log == 'function') { // Opera 11 if (window.opera) { var i = 0; while (i < arguments.length) { console.log("Item " + (i+1) + ": " + arguments[i]); i++; } } // All other modern browsers else if ((Array.prototype.slice.call(arguments)).length == 1 && typeof Array.prototype.slice.call(arguments)[0] == 'string') { console.log( (Array.prototype.slice.call(arguments)).toString() ); } else { console.log( Array.prototype.slice.call(arguments) ); } } // IE8 else if (!Function.prototype.bind && typeof console != 'undefined' && typeof console.log == 'object') { Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments)); } // IE7 and lower, and other old browsers else { // Inject Firebug lite if (!document.getElementById('firebug-lite')) { // Include the script var script = document.createElement('script'); script.type = "text/javascript"; script.id = 'firebug-lite'; // If you run the script locally, point to /path/to/firebug-lite/build/firebug-lite.js script.src = 'https://getfirebug.com/firebug-lite.js'; // If you want to expand the console window by default, uncomment this line //document.getElementsByTagName('HTML')[0].setAttribute('debug','true'); document.getElementsByTagName('HEAD')[0].appendChild(script); setTimeout(function () { log( Array.prototype.slice.call(arguments) ); }, 2000); } else { // FBL was included but it hasn't finished loading yet, so try again momentarily setTimeout(function () { log( Array.prototype.slice.call(arguments) ); }, 500); } } } } ; (function($) { // Useage: /* $("#player_wrapper").finale({ jwplayerID:"player", videoGUID:"hhhhh", userID: "hahah", onBeforePlay:function(pos){ console.log("onBeforePlay: "+pos); }, onBeforeClose: function(pos){ console.log("do nothing"); } }); $(window).finale({ onUpdateAll:function(storeObject){ }); */ if (!store.enabled) { console.log('Local storage is not supported by your browser. Please disable "Private Mode", or upgrade to a modern browser.') return; } (function() { var cache = {}; this.tmpl = function tmpl(str, data) { // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). /*jshint -W054 */ new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn(data) : fn; }; })(); var settings = { jwplayerID: null, videoGUID: "", position:-1, userID: "anonymous", onBeforePlay: function() {}, onBeforeClose: function(){}, onCompletePlay: function(){}, onUpdateAll:function(){} } var tooltips = tmpl( '<div class=" finale-panel ">' + '<p class="">???????? <%= position %> <a href="#" class="jump-to-play-btn" data-timestap="<%= timestap %>">?????????</a></p></div>' ); // $("jwplayerID_wrapper").finale({jwplayerID:"", videoGUID:""}) var string2Digit = function(n) { var h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = parseInt((n % 3600) % 60); if (h < 10) h = "0" + h; if (m < 10) m = "0" + m; return h + ":" + m + ":" + s; }; $.fn.extend({ finale: function(options) { this.settings = $.extend(settings, options); var me = this, STOREKEY = 'finale_store'; me.timestapArr = []; this.findOne = function(uid, vid, cb) { var isNewUser = true, isLogined = uid !== 'anonymous' ? true : false, isStored = false, isNewVideo = true timestapArr = me.timestapArr = store.get(STOREKEY) || []; if (timestapArr.length > 0) { for (var i = 0, item; item = timestapArr[i++];) { if (isLogined & item.user == uid) { if (item.video == vid) { // have record isNewVideo = false; isNewUser = false; cb(item); break; } } else { // anonymous if (item.video == vid) { isNewVideo = false; cb(item); break; } } } isStored = true; } // no record if (!isStored || isNewVideo || (isLogined & isNewUser)) { me.timestapArr.push({ video: vid, user: uid, position: -1, date: new Date() }); store.set(STOREKEY, me.timestapArr); cb(me.timestapArr[0]); } }; this.getAll = function(){ return store.get(STOREKEY); } this.save = function(vid, uid, position) { me.findOne(vid, uid, function(item) { item.position = position; item.date = new Date(); }); store.set(STOREKEY, me.timestapArr); }; return this.each(function(idx, elem) { if(elem == $(window)){ (function() { return onUpdateAll(me.getAll()); })(); return; } var vid = me.settings.videoGUID, jid = me.settings.jwplayerID, uid = me.settings.userID, position = -1, onBeforePlay = me.settings.onBeforePlay, onCompletePlay = me.settings.onCompletePlay, onBeforeClose = me.settings.onBeforeClose; if(me.settings.position !== -1){ $(tooltips({ position: string2Digit(item.position), timestap: item.position })).appendTo(elem); (function() { return onBeforePlay(item.position); })(); } me.findOne(vid, uid, function(item) { if (item.position !== -1) { $(tooltips({ position: string2Digit(item.position), timestap: item.position })).appendTo(elem); (function() { return onBeforePlay(item.position); })(); } }); setTimeout(function(){ $(elem).find(".finale-panel").fadeOut('slow'); },15000) $('.jump-to-play-btn').on("click", function(e){ var pos = $(e.target).attr("data-timestap"); jwplayer(jid).play(); jwplayer(jid).seek(pos); $(elem).find(".finale-panel").hide(); }); jwplayer(jid).onTime(function(e) { // console.log(e.position, e.duration) position = e.position; }); jwplayer(jid).onComplete(function(e) { //var playlist = jwplayer(jid).getPlaylist(); // console.log(e.position, e.duration) // if(playlist && playlist >0){ // }else{ // } (function() { var duration = jwplayer(jid).getDuration(); return onCompletePlay(duration); })(); }); $(window).bind("beforeunload", function() { me.save(vid, uid, position); (function() { var duration = jwplayer(jid).getDuration(); return onBeforeClose(position,duration); })(); }); }); } }); })(jQuery); /*! * bootstrap-calendar plugin * Original author: @ahmontero * Licensed under the MIT license * * jQuery lightweight plugin boilerplate * Original author: @ajpiano * Further changes, comments: @addyosmani * Licensed under the MIT license */ // the semi-colon before the function invocation is a safety // net against concatenated scripts and/or other plugins // that are not closed properly. ;(function ($, window, document, undefined) { (function () { var cache = {}; this.tmpl = function tmpl(str, data) { // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). /*jshint -W054 */ new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn(data) : fn; }; })(); var pluginName = 'LiveScheduler', defaults = { weekStart: 1, msg_days: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], msg_months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], msg_today: 'Today', msg_events_today: 'Events Today', // when today click. url: "", currentday:null, events: null },// .aweek.btn-group>operator+date_id timeline_template = tmpl( '<div class=" timeline ">' + '<div class="operator"><ul class="nav nav-pills">' + '<li class="fast pre">' + '<a href="#" class="">?????</a>' + '</li>' + '<li class="pre">' + '<a href="#" class=""><</a>' + '</li>' + '<li class="next">' + '<a href="#" class="">></a>' + '</li>' + '<li class="fast next">' + '<a href="#" class="">?????</a>' + '</li></ul></div></div>'), days_template = tmpl( '<ul class="nav nav-tabs" id="days_tabs">'+ '<% for (var i = 0, length = seven_day.length; i < length; i ++) { %>' + '<li class="select_day select_by_<%= seven_day[i].format("D") %>" >' + '<a href="#d<%= seven_day[i].format("D") %>" data-toggle="tab"><%= seven_day[i].format("dddd") %><br/> <%= seven_day[i].format("MM-DD") %></a>' + '</li>' + '<% } %>' + '</ul>'+ '</ul>' ), events_list_template = '<div class="tab-content" id="accordion_event_table" >' + '<% for (var ix = 0, lengthx = seven_day_events.length; ix < lengthx; ix ++) { %>' + '<div class="tab-pane" id="d<%= r_days[ix].format("D") %>">' + '<% if (seven_day_events[ix].length>0){ %>' + '<table class="table live_table">'+ '<thead><tr><th>??????</th><th>???</th><th>??????</th><th>??????</th><th>????</th><th>???</th></tr></thead><tbody>' + '<% for (var jx = 0 ,sde=seven_day_events[ix][0], lengthy = seven_day_events[ix][0].LiveInfo.length; jx < lengthy; jx ++) { %>' + ' <tr class="event">' + '<td class="event_title">' + '<% if (sde.LiveInfo[jx].url ){%><a href="' + '<%= sde.LiveInfo[jx].url%>"> <%= sde.LiveInfo[jx].title %></a> <%}else{%>' + '<%= sde.LiveInfo[jx].title %>'+ '<% }%>' + '<td class="event_course"><%= sde.LiveInfo[jx].course %></td>' + '</td>'+ '<td class="event_time"><%= sde.LiveInfo[jx].time%></td>' + '<td class="event_classroom"><%= sde.LiveInfo[jx].classroom%></td>' +//' <% if( sde.LiveInfo[jx].status !=null ){ %>'+ ' <td style="background-color:<%= sde.LiveInfo[jx].color %>;">' + ' <%= sde.LiveInfo[jx].status %>' + ' </td>' + '<td><a href="<%= sde.LiveInfo[jx].url ? sde.LiveInfo[jx].url : "#" %>"><%= sde.LiveInfo[jx].url_title %></a></td>' +//'<% } %>' + ' </tr>' + '<% } %>' + '</tbody></table>' +//'no data'+ '<% } else { %>'+'??????????????'+'<% }%>'+ '</div>'+ //end if '<% } %>',// end for daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], today = new Date(); // The actual plugin constructor function Plugin(element, options) { this.element = $(element); this.options = $.extend({}, defaults, options); this._defaults = defaults; this._name = pluginName; if(element) this.init(); } Plugin.prototype.init = function () { // Place initialization logic here // You already have access to the DOM element and // the options via the instance, e.g. this.element // and this.options var now = moment(); this.weekStart = this.options.weekStart || 1; this.othersParams = this.options.otherParams || '' ; this.url = this.options.url; this.paramsData = getParameters(this.options.otherParams); this.currentday = this.options.currentday ? this.options.currentday: now; // console.log(this.currentday); this.renderCalendar(getSevenDays(this.currentday)); }; Plugin.prototype.renderCalendar = function (daylist) { $(this.element).contents().remove(); var that = this; var elt = tmpl(events_list_template); this.calendar = $(days_template({ seven_day: daylist })).appendTo(this.element); this.timeline = $(timeline_template({})).appendTo(this.element).on({ click: $.proxy(this.click, this) }); this.calendar.on({click:$.proxy(this.click,this)}); this.paramsData.days = _.map(daylist, function (k) { return moment(k).utc().format(); }); $.ajax({ type: "POST", url: this.url, data: this.paramsData, // crossDomain:true, dataType: "json", jsonp: false }).done(function (results) { //console.log(results); //if(typeof results == "object"){ // var res_dates= results.result; // if (res_dates == undefined){return false;} //} //if(typeof results == "array"){ // var res_dates= results; //} var res_dates = results; if (res_dates.length > 0) { var req_days = _.map(daylist, function (k) { return moment(k).utc().format(); }); that.events = _.map(req_days, function (req_date) { return _.filter(res_dates, function (res) { res.date= moment(res.date); return res.date.date() == moment(req_date).date(); } ); }); var v = {seven_day_events: that.events,r_days:daylist} //console.log(v); $(elt(v)).appendTo(that.element) } $("#days_tabs .select_by_" + moment(this.currentday).format("D") + " a").tab("show"); //$("#d" + moment(this.currentday).format("D")).addClass("active"); }).fail(function (jqXHR, textStatus, errorThrown) { // console.log(textStatus); }); }; Plugin.prototype.click = function (e) { e.stopPropagation(); e.preventDefault(); var target = $(e.target).closest('li'); if (target.length == 1) { if (target.is('.pre')) { if (target.is('.fast')) { this.currentday = moment(this.currentday).subtract('d', 7); this.renderCalendar(getSevenDays(this.currentday)); } else { this.currentday = moment(this.currentday).subtract('d', 1); this.renderCalendar(getSevenDays(this.currentday)); } } else if (target.is('.next')) { if (target.is('.fast')) { this.currentday = moment(this.currentday).add('d', 7); this.renderCalendar(getSevenDays(this.currentday)); } else { this.currentday = moment(this.currentday).add('d', 1); this.renderCalendar(getSevenDays(this.currentday)); } } else if(target.is('.select_day')){ $(target).children('a').tab("show"); $($(target).children('a').attr("href")).children('.live_table').dataTable( { "initComplete": initComplete, //$('.live_table').dataTable( { "bRetrieve":true, "sDom": "<'row'<'span4'l><'span5 pull-right'f>r>t<'row'<'span4'i><'span5 pull-right'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "?????? _MENU_ ?¤???", "sZeroRecords": "????????????", "sInfoEmpty": "??????", "sInfoFiltered": "( ?? _MAX_ ?????????)" } } ); } } }; var getParameters = function(url){ var params = url.split("&"), i,val,resultes ={}; for(i = 0; i< params.length;i++){ val = params[i].split("="); resultes[val[0]] = escape(val[1]); } return resultes; }; var getSevenDays = function (middleDay) { var daylist = []; var startDay = moment(middleDay).subtract('d', 4); _(7).times(function (n) { var ss = startDay.add('d', 1);// daylist.push(moment(ss)); }); return daylist; }; var initComplete= function () { var api = this.api(); api.columns().indexes().flatten().each( function ( i ) { if(i==1){ var column = api.column( i ); var $headCell = $(".dataTables_length"); var select = $('<select ><option value="">???</option></select>') .appendTo( $('<label class="category_select">?????</label>').appendTo($headCell) ) .on( 'change', function () { // var val = $.fn.dataTable.util.escapeRegex( // $(this).val() // ); var val = $(this).val(); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } } ); }; // $.fn.dataTable.ext.search.push( // function( settings, data, dataIndex ) { // var min = parseInt( $('#min').val(), 10 ); // var max = parseInt( $('#max').val(), 10 ); // var age = parseFloat( data[3] ) || 0; // use data for the age column // if ( ( isNaN( min ) && isNaN( max ) ) || // ( isNaN( min ) && age <= max ) || // ( min <= age && isNaN( max ) ) || // ( min <= age && age <= max ) ) // { // return true; // } // return false; // } // ); $.fn[pluginName] = function (options) { return this.each(function () { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); } }); } })(jQuery, window, document);
Ms-Dos/Windows
Unix
Write backup
jsp File Browser version 1.2 by
www.vonloesch.de