PageRenderTime 146ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 3ms

/vendor/plugins/fluid-infusion/assets/infusion/InfusionAll.js

https://bitbucket.org/mediashelf/marpa-archive
JavaScript | 15107 lines | 11308 code | 1806 blank | 1993 comment | 1958 complexity | 1cdd0b4eead291512abf1becfa7c5800 MD5 | raw file
Possible License(s): LGPL-2.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, GPL-2.0, MIT, Apache-2.0
  1. /*!
  2. * jQuery JavaScript Library v1.3.2
  3. * http://jquery.com/
  4. *
  5. * Copyright (c) 2009 John Resig
  6. * Dual licensed under the MIT and GPL licenses.
  7. * http://docs.jquery.com/License
  8. *
  9. * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
  10. * Revision: 6246
  11. */
  12. (function(){
  13. var
  14. // Will speed up references to window, and allows munging its name.
  15. window = this,
  16. // Will speed up references to undefined, and allows munging its name.
  17. undefined,
  18. // Map over jQuery in case of overwrite
  19. _jQuery = window.jQuery,
  20. // Map over the $ in case of overwrite
  21. _$ = window.$,
  22. jQuery = window.jQuery = window.$ = function( selector, context ) {
  23. // The jQuery object is actually just the init constructor 'enhanced'
  24. return new jQuery.fn.init( selector, context );
  25. },
  26. // A simple way to check for HTML strings or ID strings
  27. // (both of which we optimize for)
  28. quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
  29. // Is it a simple selector
  30. isSimple = /^.[^:#\[\.,]*$/;
  31. jQuery.fn = jQuery.prototype = {
  32. init: function( selector, context ) {
  33. // Make sure that a selection was provided
  34. selector = selector || document;
  35. // Handle $(DOMElement)
  36. if ( selector.nodeType ) {
  37. this[0] = selector;
  38. this.length = 1;
  39. this.context = selector;
  40. return this;
  41. }
  42. // Handle HTML strings
  43. if ( typeof selector === "string" ) {
  44. // Are we dealing with HTML string or an ID?
  45. var match = quickExpr.exec( selector );
  46. // Verify a match, and that no context was specified for #id
  47. if ( match && (match[1] || !context) ) {
  48. // HANDLE: $(html) -> $(array)
  49. if ( match[1] )
  50. selector = jQuery.clean( [ match[1] ], context );
  51. // HANDLE: $("#id")
  52. else {
  53. var elem = document.getElementById( match[3] );
  54. // Handle the case where IE and Opera return items
  55. // by name instead of ID
  56. if ( elem && elem.id != match[3] )
  57. return jQuery().find( selector );
  58. // Otherwise, we inject the element directly into the jQuery object
  59. var ret = jQuery( elem || [] );
  60. ret.context = document;
  61. ret.selector = selector;
  62. return ret;
  63. }
  64. // HANDLE: $(expr, [context])
  65. // (which is just equivalent to: $(content).find(expr)
  66. } else
  67. return jQuery( context ).find( selector );
  68. // HANDLE: $(function)
  69. // Shortcut for document ready
  70. } else if ( jQuery.isFunction( selector ) )
  71. return jQuery( document ).ready( selector );
  72. // Make sure that old selector state is passed along
  73. if ( selector.selector && selector.context ) {
  74. this.selector = selector.selector;
  75. this.context = selector.context;
  76. }
  77. return this.setArray(jQuery.isArray( selector ) ?
  78. selector :
  79. jQuery.makeArray(selector));
  80. },
  81. // Start with an empty selector
  82. selector: "",
  83. // The current version of jQuery being used
  84. jquery: "1.3.2",
  85. // The number of elements contained in the matched element set
  86. size: function() {
  87. return this.length;
  88. },
  89. // Get the Nth element in the matched element set OR
  90. // Get the whole matched element set as a clean array
  91. get: function( num ) {
  92. return num === undefined ?
  93. // Return a 'clean' array
  94. Array.prototype.slice.call( this ) :
  95. // Return just the object
  96. this[ num ];
  97. },
  98. // Take an array of elements and push it onto the stack
  99. // (returning the new matched element set)
  100. pushStack: function( elems, name, selector ) {
  101. // Build a new jQuery matched element set
  102. var ret = jQuery( elems );
  103. // Add the old object onto the stack (as a reference)
  104. ret.prevObject = this;
  105. ret.context = this.context;
  106. if ( name === "find" )
  107. ret.selector = this.selector + (this.selector ? " " : "") + selector;
  108. else if ( name )
  109. ret.selector = this.selector + "." + name + "(" + selector + ")";
  110. // Return the newly-formed element set
  111. return ret;
  112. },
  113. // Force the current matched set of elements to become
  114. // the specified array of elements (destroying the stack in the process)
  115. // You should use pushStack() in order to do this, but maintain the stack
  116. setArray: function( elems ) {
  117. // Resetting the length to 0, then using the native Array push
  118. // is a super-fast way to populate an object with array-like properties
  119. this.length = 0;
  120. Array.prototype.push.apply( this, elems );
  121. return this;
  122. },
  123. // Execute a callback for every element in the matched set.
  124. // (You can seed the arguments with an array of args, but this is
  125. // only used internally.)
  126. each: function( callback, args ) {
  127. return jQuery.each( this, callback, args );
  128. },
  129. // Determine the position of an element within
  130. // the matched set of elements
  131. index: function( elem ) {
  132. // Locate the position of the desired element
  133. return jQuery.inArray(
  134. // If it receives a jQuery object, the first element is used
  135. elem && elem.jquery ? elem[0] : elem
  136. , this );
  137. },
  138. attr: function( name, value, type ) {
  139. var options = name;
  140. // Look for the case where we're accessing a style value
  141. if ( typeof name === "string" )
  142. if ( value === undefined )
  143. return this[0] && jQuery[ type || "attr" ]( this[0], name );
  144. else {
  145. options = {};
  146. options[ name ] = value;
  147. }
  148. // Check to see if we're setting style values
  149. return this.each(function(i){
  150. // Set all the styles
  151. for ( name in options )
  152. jQuery.attr(
  153. type ?
  154. this.style :
  155. this,
  156. name, jQuery.prop( this, options[ name ], type, i, name )
  157. );
  158. });
  159. },
  160. css: function( key, value ) {
  161. // ignore negative width and height values
  162. if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
  163. value = undefined;
  164. return this.attr( key, value, "curCSS" );
  165. },
  166. text: function( text ) {
  167. if ( typeof text !== "object" && text != null )
  168. return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
  169. var ret = "";
  170. jQuery.each( text || this, function(){
  171. jQuery.each( this.childNodes, function(){
  172. if ( this.nodeType != 8 )
  173. ret += this.nodeType != 1 ?
  174. this.nodeValue :
  175. jQuery.fn.text( [ this ] );
  176. });
  177. });
  178. return ret;
  179. },
  180. wrapAll: function( html ) {
  181. if ( this[0] ) {
  182. // The elements to wrap the target around
  183. var wrap = jQuery( html, this[0].ownerDocument ).clone();
  184. if ( this[0].parentNode )
  185. wrap.insertBefore( this[0] );
  186. wrap.map(function(){
  187. var elem = this;
  188. while ( elem.firstChild )
  189. elem = elem.firstChild;
  190. return elem;
  191. }).append(this);
  192. }
  193. return this;
  194. },
  195. wrapInner: function( html ) {
  196. return this.each(function(){
  197. jQuery( this ).contents().wrapAll( html );
  198. });
  199. },
  200. wrap: function( html ) {
  201. return this.each(function(){
  202. jQuery( this ).wrapAll( html );
  203. });
  204. },
  205. append: function() {
  206. return this.domManip(arguments, true, function(elem){
  207. if (this.nodeType == 1)
  208. this.appendChild( elem );
  209. });
  210. },
  211. prepend: function() {
  212. return this.domManip(arguments, true, function(elem){
  213. if (this.nodeType == 1)
  214. this.insertBefore( elem, this.firstChild );
  215. });
  216. },
  217. before: function() {
  218. return this.domManip(arguments, false, function(elem){
  219. this.parentNode.insertBefore( elem, this );
  220. });
  221. },
  222. after: function() {
  223. return this.domManip(arguments, false, function(elem){
  224. this.parentNode.insertBefore( elem, this.nextSibling );
  225. });
  226. },
  227. end: function() {
  228. return this.prevObject || jQuery( [] );
  229. },
  230. // For internal use only.
  231. // Behaves like an Array's method, not like a jQuery method.
  232. push: [].push,
  233. sort: [].sort,
  234. splice: [].splice,
  235. find: function( selector ) {
  236. if ( this.length === 1 ) {
  237. var ret = this.pushStack( [], "find", selector );
  238. ret.length = 0;
  239. jQuery.find( selector, this[0], ret );
  240. return ret;
  241. } else {
  242. return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
  243. return jQuery.find( selector, elem );
  244. })), "find", selector );
  245. }
  246. },
  247. clone: function( events ) {
  248. // Do the clone
  249. var ret = this.map(function(){
  250. if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
  251. // IE copies events bound via attachEvent when
  252. // using cloneNode. Calling detachEvent on the
  253. // clone will also remove the events from the orignal
  254. // In order to get around this, we use innerHTML.
  255. // Unfortunately, this means some modifications to
  256. // attributes in IE that are actually only stored
  257. // as properties will not be copied (such as the
  258. // the name attribute on an input).
  259. var html = this.outerHTML;
  260. if ( !html ) {
  261. var div = this.ownerDocument.createElement("div");
  262. div.appendChild( this.cloneNode(true) );
  263. html = div.innerHTML;
  264. }
  265. return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
  266. } else
  267. return this.cloneNode(true);
  268. });
  269. // Copy the events from the original to the clone
  270. if ( events === true ) {
  271. var orig = this.find("*").andSelf(), i = 0;
  272. ret.find("*").andSelf().each(function(){
  273. if ( this.nodeName !== orig[i].nodeName )
  274. return;
  275. var events = jQuery.data( orig[i], "events" );
  276. for ( var type in events ) {
  277. for ( var handler in events[ type ] ) {
  278. jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
  279. }
  280. }
  281. i++;
  282. });
  283. }
  284. // Return the cloned set
  285. return ret;
  286. },
  287. filter: function( selector ) {
  288. return this.pushStack(
  289. jQuery.isFunction( selector ) &&
  290. jQuery.grep(this, function(elem, i){
  291. return selector.call( elem, i );
  292. }) ||
  293. jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
  294. return elem.nodeType === 1;
  295. }) ), "filter", selector );
  296. },
  297. closest: function( selector ) {
  298. var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
  299. closer = 0;
  300. return this.map(function(){
  301. var cur = this;
  302. while ( cur && cur.ownerDocument ) {
  303. if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
  304. jQuery.data(cur, "closest", closer);
  305. return cur;
  306. }
  307. cur = cur.parentNode;
  308. closer++;
  309. }
  310. });
  311. },
  312. not: function( selector ) {
  313. if ( typeof selector === "string" )
  314. // test special case where just one selector is passed in
  315. if ( isSimple.test( selector ) )
  316. return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
  317. else
  318. selector = jQuery.multiFilter( selector, this );
  319. var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
  320. return this.filter(function() {
  321. return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
  322. });
  323. },
  324. add: function( selector ) {
  325. return this.pushStack( jQuery.unique( jQuery.merge(
  326. this.get(),
  327. typeof selector === "string" ?
  328. jQuery( selector ) :
  329. jQuery.makeArray( selector )
  330. )));
  331. },
  332. is: function( selector ) {
  333. return !!selector && jQuery.multiFilter( selector, this ).length > 0;
  334. },
  335. hasClass: function( selector ) {
  336. return !!selector && this.is( "." + selector );
  337. },
  338. val: function( value ) {
  339. if ( value === undefined ) {
  340. var elem = this[0];
  341. if ( elem ) {
  342. if( jQuery.nodeName( elem, 'option' ) )
  343. return (elem.attributes.value || {}).specified ? elem.value : elem.text;
  344. // We need to handle select boxes special
  345. if ( jQuery.nodeName( elem, "select" ) ) {
  346. var index = elem.selectedIndex,
  347. values = [],
  348. options = elem.options,
  349. one = elem.type == "select-one";
  350. // Nothing was selected
  351. if ( index < 0 )
  352. return null;
  353. // Loop through all the selected options
  354. for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
  355. var option = options[ i ];
  356. if ( option.selected ) {
  357. // Get the specifc value for the option
  358. value = jQuery(option).val();
  359. // We don't need an array for one selects
  360. if ( one )
  361. return value;
  362. // Multi-Selects return an array
  363. values.push( value );
  364. }
  365. }
  366. return values;
  367. }
  368. // Everything else, we just grab the value
  369. return (elem.value || "").replace(/\r/g, "");
  370. }
  371. return undefined;
  372. }
  373. if ( typeof value === "number" )
  374. value += '';
  375. return this.each(function(){
  376. if ( this.nodeType != 1 )
  377. return;
  378. if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
  379. this.checked = (jQuery.inArray(this.value, value) >= 0 ||
  380. jQuery.inArray(this.name, value) >= 0);
  381. else if ( jQuery.nodeName( this, "select" ) ) {
  382. var values = jQuery.makeArray(value);
  383. jQuery( "option", this ).each(function(){
  384. this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
  385. jQuery.inArray( this.text, values ) >= 0);
  386. });
  387. if ( !values.length )
  388. this.selectedIndex = -1;
  389. } else
  390. this.value = value;
  391. });
  392. },
  393. html: function( value ) {
  394. return value === undefined ?
  395. (this[0] ?
  396. this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
  397. null) :
  398. this.empty().append( value );
  399. },
  400. replaceWith: function( value ) {
  401. return this.after( value ).remove();
  402. },
  403. eq: function( i ) {
  404. return this.slice( i, +i + 1 );
  405. },
  406. slice: function() {
  407. return this.pushStack( Array.prototype.slice.apply( this, arguments ),
  408. "slice", Array.prototype.slice.call(arguments).join(",") );
  409. },
  410. map: function( callback ) {
  411. return this.pushStack( jQuery.map(this, function(elem, i){
  412. return callback.call( elem, i, elem );
  413. }));
  414. },
  415. andSelf: function() {
  416. return this.add( this.prevObject );
  417. },
  418. domManip: function( args, table, callback ) {
  419. if ( this[0] ) {
  420. var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
  421. scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
  422. first = fragment.firstChild;
  423. if ( first )
  424. for ( var i = 0, l = this.length; i < l; i++ )
  425. callback.call( root(this[i], first), this.length > 1 || i > 0 ?
  426. fragment.cloneNode(true) : fragment );
  427. if ( scripts )
  428. jQuery.each( scripts, evalScript );
  429. }
  430. return this;
  431. function root( elem, cur ) {
  432. return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
  433. (elem.getElementsByTagName("tbody")[0] ||
  434. elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
  435. elem;
  436. }
  437. }
  438. };
  439. // Give the init function the jQuery prototype for later instantiation
  440. jQuery.fn.init.prototype = jQuery.fn;
  441. function evalScript( i, elem ) {
  442. if ( elem.src )
  443. jQuery.ajax({
  444. url: elem.src,
  445. async: false,
  446. dataType: "script"
  447. });
  448. else
  449. jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
  450. if ( elem.parentNode )
  451. elem.parentNode.removeChild( elem );
  452. }
  453. function now(){
  454. return +new Date;
  455. }
  456. jQuery.extend = jQuery.fn.extend = function() {
  457. // copy reference to target object
  458. var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
  459. // Handle a deep copy situation
  460. if ( typeof target === "boolean" ) {
  461. deep = target;
  462. target = arguments[1] || {};
  463. // skip the boolean and the target
  464. i = 2;
  465. }
  466. // Handle case when target is a string or something (possible in deep copy)
  467. if ( typeof target !== "object" && !jQuery.isFunction(target) )
  468. target = {};
  469. // extend jQuery itself if only one argument is passed
  470. if ( length == i ) {
  471. target = this;
  472. --i;
  473. }
  474. for ( ; i < length; i++ )
  475. // Only deal with non-null/undefined values
  476. if ( (options = arguments[ i ]) != null )
  477. // Extend the base object
  478. for ( var name in options ) {
  479. var src = target[ name ], copy = options[ name ];
  480. // Prevent never-ending loop
  481. if ( target === copy )
  482. continue;
  483. // Recurse if we're merging object values
  484. if ( deep && copy && typeof copy === "object" && !copy.nodeType )
  485. target[ name ] = jQuery.extend( deep,
  486. // Never move original objects, clone them
  487. src || ( copy.length != null ? [ ] : { } )
  488. , copy );
  489. // Don't bring in undefined values
  490. else if ( copy !== undefined )
  491. target[ name ] = copy;
  492. }
  493. // Return the modified object
  494. return target;
  495. };
  496. // exclude the following css properties to add px
  497. var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
  498. // cache defaultView
  499. defaultView = document.defaultView || {},
  500. toString = Object.prototype.toString;
  501. jQuery.extend({
  502. noConflict: function( deep ) {
  503. window.$ = _$;
  504. if ( deep )
  505. window.jQuery = _jQuery;
  506. return jQuery;
  507. },
  508. // See test/unit/core.js for details concerning isFunction.
  509. // Since version 1.3, DOM methods and functions like alert
  510. // aren't supported. They return false on IE (#2968).
  511. isFunction: function( obj ) {
  512. return toString.call(obj) === "[object Function]";
  513. },
  514. isArray: function( obj ) {
  515. return toString.call(obj) === "[object Array]";
  516. },
  517. // check if an element is in a (or is an) XML document
  518. isXMLDoc: function( elem ) {
  519. return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
  520. !!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
  521. },
  522. // Evalulates a script in a global context
  523. globalEval: function( data ) {
  524. if ( data && /\S/.test(data) ) {
  525. // Inspired by code by Andrea Giammarchi
  526. // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
  527. var head = document.getElementsByTagName("head")[0] || document.documentElement,
  528. script = document.createElement("script");
  529. script.type = "text/javascript";
  530. if ( jQuery.support.scriptEval )
  531. script.appendChild( document.createTextNode( data ) );
  532. else
  533. script.text = data;
  534. // Use insertBefore instead of appendChild to circumvent an IE6 bug.
  535. // This arises when a base node is used (#2709).
  536. head.insertBefore( script, head.firstChild );
  537. head.removeChild( script );
  538. }
  539. },
  540. nodeName: function( elem, name ) {
  541. return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
  542. },
  543. // args is for internal usage only
  544. each: function( object, callback, args ) {
  545. var name, i = 0, length = object.length;
  546. if ( args ) {
  547. if ( length === undefined ) {
  548. for ( name in object )
  549. if ( callback.apply( object[ name ], args ) === false )
  550. break;
  551. } else
  552. for ( ; i < length; )
  553. if ( callback.apply( object[ i++ ], args ) === false )
  554. break;
  555. // A special, fast, case for the most common use of each
  556. } else {
  557. if ( length === undefined ) {
  558. for ( name in object )
  559. if ( callback.call( object[ name ], name, object[ name ] ) === false )
  560. break;
  561. } else
  562. for ( var value = object[0];
  563. i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
  564. }
  565. return object;
  566. },
  567. prop: function( elem, value, type, i, name ) {
  568. // Handle executable functions
  569. if ( jQuery.isFunction( value ) )
  570. value = value.call( elem, i );
  571. // Handle passing in a number to a CSS property
  572. return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
  573. value + "px" :
  574. value;
  575. },
  576. className: {
  577. // internal only, use addClass("class")
  578. add: function( elem, classNames ) {
  579. jQuery.each((classNames || "").split(/\s+/), function(i, className){
  580. if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
  581. elem.className += (elem.className ? " " : "") + className;
  582. });
  583. },
  584. // internal only, use removeClass("class")
  585. remove: function( elem, classNames ) {
  586. if (elem.nodeType == 1)
  587. elem.className = classNames !== undefined ?
  588. jQuery.grep(elem.className.split(/\s+/), function(className){
  589. return !jQuery.className.has( classNames, className );
  590. }).join(" ") :
  591. "";
  592. },
  593. // internal only, use hasClass("class")
  594. has: function( elem, className ) {
  595. return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
  596. }
  597. },
  598. // A method for quickly swapping in/out CSS properties to get correct calculations
  599. swap: function( elem, options, callback ) {
  600. var old = {};
  601. // Remember the old values, and insert the new ones
  602. for ( var name in options ) {
  603. old[ name ] = elem.style[ name ];
  604. elem.style[ name ] = options[ name ];
  605. }
  606. callback.call( elem );
  607. // Revert the old values
  608. for ( var name in options )
  609. elem.style[ name ] = old[ name ];
  610. },
  611. css: function( elem, name, force, extra ) {
  612. if ( name == "width" || name == "height" ) {
  613. var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
  614. function getWH() {
  615. val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
  616. if ( extra === "border" )
  617. return;
  618. jQuery.each( which, function() {
  619. if ( !extra )
  620. val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
  621. if ( extra === "margin" )
  622. val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
  623. else
  624. val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
  625. });
  626. }
  627. if ( elem.offsetWidth !== 0 )
  628. getWH();
  629. else
  630. jQuery.swap( elem, props, getWH );
  631. return Math.max(0, Math.round(val));
  632. }
  633. return jQuery.curCSS( elem, name, force );
  634. },
  635. curCSS: function( elem, name, force ) {
  636. var ret, style = elem.style;
  637. // We need to handle opacity special in IE
  638. if ( name == "opacity" && !jQuery.support.opacity ) {
  639. ret = jQuery.attr( style, "opacity" );
  640. return ret == "" ?
  641. "1" :
  642. ret;
  643. }
  644. // Make sure we're using the right name for getting the float value
  645. if ( name.match( /float/i ) )
  646. name = styleFloat;
  647. if ( !force && style && style[ name ] )
  648. ret = style[ name ];
  649. else if ( defaultView.getComputedStyle ) {
  650. // Only "float" is needed here
  651. if ( name.match( /float/i ) )
  652. name = "float";
  653. name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
  654. var computedStyle = defaultView.getComputedStyle( elem, null );
  655. if ( computedStyle )
  656. ret = computedStyle.getPropertyValue( name );
  657. // We should always get a number back from opacity
  658. if ( name == "opacity" && ret == "" )
  659. ret = "1";
  660. } else if ( elem.currentStyle ) {
  661. var camelCase = name.replace(/\-(\w)/g, function(all, letter){
  662. return letter.toUpperCase();
  663. });
  664. ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
  665. // From the awesome hack by Dean Edwards
  666. // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
  667. // If we're not dealing with a regular pixel number
  668. // but a number that has a weird ending, we need to convert it to pixels
  669. if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
  670. // Remember the original values
  671. var left = style.left, rsLeft = elem.runtimeStyle.left;
  672. // Put in the new values to get a computed value out
  673. elem.runtimeStyle.left = elem.currentStyle.left;
  674. style.left = ret || 0;
  675. ret = style.pixelLeft + "px";
  676. // Revert the changed values
  677. style.left = left;
  678. elem.runtimeStyle.left = rsLeft;
  679. }
  680. }
  681. return ret;
  682. },
  683. clean: function( elems, context, fragment ) {
  684. context = context || document;
  685. // !context.createElement fails in IE with an error but returns typeof 'object'
  686. if ( typeof context.createElement === "undefined" )
  687. context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
  688. // If a single string is passed in and it's a single tag
  689. // just do a createElement and skip the rest
  690. if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
  691. var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
  692. if ( match )
  693. return [ context.createElement( match[1] ) ];
  694. }
  695. var ret = [], scripts = [], div = context.createElement("div");
  696. jQuery.each(elems, function(i, elem){
  697. if ( typeof elem === "number" )
  698. elem += '';
  699. if ( !elem )
  700. return;
  701. // Convert html string into DOM nodes
  702. if ( typeof elem === "string" ) {
  703. // Fix "XHTML"-style tags in all browsers
  704. elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
  705. return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
  706. all :
  707. front + "></" + tag + ">";
  708. });
  709. // Trim whitespace, otherwise indexOf won't work as expected
  710. var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
  711. var wrap =
  712. // option or optgroup
  713. !tags.indexOf("<opt") &&
  714. [ 1, "<select multiple='multiple'>", "</select>" ] ||
  715. !tags.indexOf("<leg") &&
  716. [ 1, "<fieldset>", "</fieldset>" ] ||
  717. tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
  718. [ 1, "<table>", "</table>" ] ||
  719. !tags.indexOf("<tr") &&
  720. [ 2, "<table><tbody>", "</tbody></table>" ] ||
  721. // <thead> matched above
  722. (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
  723. [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
  724. !tags.indexOf("<col") &&
  725. [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
  726. // IE can't serialize <link> and <script> tags normally
  727. !jQuery.support.htmlSerialize &&
  728. [ 1, "div<div>", "</div>" ] ||
  729. [ 0, "", "" ];
  730. // Go to html and back, then peel off extra wrappers
  731. div.innerHTML = wrap[1] + elem + wrap[2];
  732. // Move to the right depth
  733. while ( wrap[0]-- )
  734. div = div.lastChild;
  735. // Remove IE's autoinserted <tbody> from table fragments
  736. if ( !jQuery.support.tbody ) {
  737. // String was a <table>, *may* have spurious <tbody>
  738. var hasBody = /<tbody/i.test(elem),
  739. tbody = !tags.indexOf("<table") && !hasBody ?
  740. div.firstChild && div.firstChild.childNodes :
  741. // String was a bare <thead> or <tfoot>
  742. wrap[1] == "<table>" && !hasBody ?
  743. div.childNodes :
  744. [];
  745. for ( var j = tbody.length - 1; j >= 0 ; --j )
  746. if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
  747. tbody[ j ].parentNode.removeChild( tbody[ j ] );
  748. }
  749. // IE completely kills leading whitespace when innerHTML is used
  750. if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
  751. div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
  752. elem = jQuery.makeArray( div.childNodes );
  753. }
  754. if ( elem.nodeType )
  755. ret.push( elem );
  756. else
  757. ret = jQuery.merge( ret, elem );
  758. });
  759. if ( fragment ) {
  760. for ( var i = 0; ret[i]; i++ ) {
  761. if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
  762. scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
  763. } else {
  764. if ( ret[i].nodeType === 1 )
  765. ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
  766. fragment.appendChild( ret[i] );
  767. }
  768. }
  769. return scripts;
  770. }
  771. return ret;
  772. },
  773. attr: function( elem, name, value ) {
  774. // don't set attributes on text and comment nodes
  775. if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
  776. return undefined;
  777. var notxml = !jQuery.isXMLDoc( elem ),
  778. // Whether we are setting (or getting)
  779. set = value !== undefined;
  780. // Try to normalize/fix the name
  781. name = notxml && jQuery.props[ name ] || name;
  782. // Only do all the following if this is a node (faster for style)
  783. // IE elem.getAttribute passes even for style
  784. if ( elem.tagName ) {
  785. // These attributes require special treatment
  786. var special = /href|src|style/.test( name );
  787. // Safari mis-reports the default selected property of a hidden option
  788. // Accessing the parent's selectedIndex property fixes it
  789. if ( name == "selected" && elem.parentNode )
  790. elem.parentNode.selectedIndex;
  791. // If applicable, access the attribute via the DOM 0 way
  792. if ( name in elem && notxml && !special ) {
  793. if ( set ){
  794. // We can't allow the type property to be changed (since it causes problems in IE)
  795. if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
  796. throw "type property can't be changed";
  797. elem[ name ] = value;
  798. }
  799. // browsers index elements by id/name on forms, give priority to attributes.
  800. if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
  801. return elem.getAttributeNode( name ).nodeValue;
  802. // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
  803. // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
  804. if ( name == "tabIndex" ) {
  805. var attributeNode = elem.getAttributeNode( "tabIndex" );
  806. return attributeNode && attributeNode.specified
  807. ? attributeNode.value
  808. : elem.nodeName.match(/(button|input|object|select|textarea)/i)
  809. ? 0
  810. : elem.nodeName.match(/^(a|area)$/i) && elem.href
  811. ? 0
  812. : undefined;
  813. }
  814. return elem[ name ];
  815. }
  816. if ( !jQuery.support.style && notxml && name == "style" )
  817. return jQuery.attr( elem.style, "cssText", value );
  818. if ( set )
  819. // convert the value to a string (all browsers do this but IE) see #1070
  820. elem.setAttribute( name, "" + value );
  821. var attr = !jQuery.support.hrefNormalized && notxml && special
  822. // Some attributes require a special call on IE
  823. ? elem.getAttribute( name, 2 )
  824. : elem.getAttribute( name );
  825. // Non-existent attributes return null, we normalize to undefined
  826. return attr === null ? undefined : attr;
  827. }
  828. // elem is actually elem.style ... set the style
  829. // IE uses filters for opacity
  830. if ( !jQuery.support.opacity && name == "opacity" ) {
  831. if ( set ) {
  832. // IE has trouble with opacity if it does not have layout
  833. // Force it by setting the zoom level
  834. elem.zoom = 1;
  835. // Set the alpha filter to set the opacity
  836. elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
  837. (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
  838. }
  839. return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
  840. (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
  841. "";
  842. }
  843. name = name.replace(/-([a-z])/ig, function(all, letter){
  844. return letter.toUpperCase();
  845. });
  846. if ( set )
  847. elem[ name ] = value;
  848. return elem[ name ];
  849. },
  850. trim: function( text ) {
  851. return (text || "").replace( /^\s+|\s+$/g, "" );
  852. },
  853. makeArray: function( array ) {
  854. var ret = [];
  855. if( array != null ){
  856. var i = array.length;
  857. // The window, strings (and functions) also have 'length'
  858. if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
  859. ret[0] = array;
  860. else
  861. while( i )
  862. ret[--i] = array[i];
  863. }
  864. return ret;
  865. },
  866. inArray: function( elem, array ) {
  867. for ( var i = 0, length = array.length; i < length; i++ )
  868. // Use === because on IE, window == document
  869. if ( array[ i ] === elem )
  870. return i;
  871. return -1;
  872. },
  873. merge: function( first, second ) {
  874. // We have to loop this way because IE & Opera overwrite the length
  875. // expando of getElementsByTagName
  876. var i = 0, elem, pos = first.length;
  877. // Also, we need to make sure that the correct elements are being returned
  878. // (IE returns comment nodes in a '*' query)
  879. if ( !jQuery.support.getAll ) {
  880. while ( (elem = second[ i++ ]) != null )
  881. if ( elem.nodeType != 8 )
  882. first[ pos++ ] = elem;
  883. } else
  884. while ( (elem = second[ i++ ]) != null )
  885. first[ pos++ ] = elem;
  886. return first;
  887. },
  888. unique: function( array ) {
  889. var ret = [], done = {};
  890. try {
  891. for ( var i = 0, length = array.length; i < length; i++ ) {
  892. var id = jQuery.data( array[ i ] );
  893. if ( !done[ id ] ) {
  894. done[ id ] = true;
  895. ret.push( array[ i ] );
  896. }
  897. }
  898. } catch( e ) {
  899. ret = array;
  900. }
  901. return ret;
  902. },
  903. grep: function( elems, callback, inv ) {
  904. var ret = [];
  905. // Go through the array, only saving the items
  906. // that pass the validator function
  907. for ( var i = 0, length = elems.length; i < length; i++ )
  908. if ( !inv != !callback( elems[ i ], i ) )
  909. ret.push( elems[ i ] );
  910. return ret;
  911. },
  912. map: function( elems, callback ) {
  913. var ret = [];
  914. // Go through the array, translating each of the items to their
  915. // new value (or values).
  916. for ( var i = 0, length = elems.length; i < length; i++ ) {
  917. var value = callback( elems[ i ], i );
  918. if ( value != null )
  919. ret[ ret.length ] = value;
  920. }
  921. return ret.concat.apply( [], ret );
  922. }
  923. });
  924. // Use of jQuery.browser is deprecated.
  925. // It's included for backwards compatibility and plugins,
  926. // although they should work to migrate away.
  927. var userAgent = navigator.userAgent.toLowerCase();
  928. // Figure out what browser is being used
  929. jQuery.browser = {
  930. version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
  931. safari: /webkit/.test( userAgent ),
  932. opera: /opera/.test( userAgent ),
  933. msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
  934. mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
  935. };
  936. jQuery.each({
  937. parent: function(elem){return elem.parentNode;},
  938. parents: function(elem){return jQuery.dir(elem,"parentNode");},
  939. next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
  940. prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
  941. nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
  942. prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
  943. siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
  944. children: function(elem){return jQuery.sibling(elem.firstChild);},
  945. contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
  946. }, function(name, fn){
  947. jQuery.fn[ name ] = function( selector ) {
  948. var ret = jQuery.map( this, fn );
  949. if ( selector && typeof selector == "string" )
  950. ret = jQuery.multiFilter( selector, ret );
  951. return this.pushStack( jQuery.unique( ret ), name, selector );
  952. };
  953. });
  954. jQuery.each({
  955. appendTo: "append",
  956. prependTo: "prepend",
  957. insertBefore: "before",
  958. insertAfter: "after",
  959. replaceAll: "replaceWith"
  960. }, function(name, original){
  961. jQuery.fn[ name ] = function( selector ) {
  962. var ret = [], insert = jQuery( selector );
  963. for ( var i = 0, l = insert.length; i < l; i++ ) {
  964. var elems = (i > 0 ? this.clone(true) : this).get();
  965. jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
  966. ret = ret.concat( elems );
  967. }
  968. return this.pushStack( ret, name, selector );
  969. };
  970. });
  971. jQuery.each({
  972. removeAttr: function( name ) {
  973. jQuery.attr( this, name, "" );
  974. if (this.nodeType == 1)
  975. this.removeAttribute( name );
  976. },
  977. addClass: function( classNames ) {
  978. jQuery.className.add( this, classNames );
  979. },
  980. removeClass: function( classNames ) {
  981. jQuery.className.remove( this, classNames );
  982. },
  983. toggleClass: function( classNames, state ) {
  984. if( typeof state !== "boolean" )
  985. state = !jQuery.className.has( this, classNames );
  986. jQuery.className[ state ? "add" : "remove" ]( this, classNames );
  987. },
  988. remove: function( selector ) {
  989. if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
  990. // Prevent memory leaks
  991. jQuery( "*", this ).add([this]).each(function(){
  992. jQuery.event.remove(this);
  993. jQuery.removeData(this);
  994. });
  995. if (this.parentNode)
  996. this.parentNode.removeChild( this );
  997. }
  998. },
  999. empty: function() {
  1000. // Remove element nodes and prevent memory leaks
  1001. jQuery(this).children().remove();
  1002. // Remove any remaining nodes
  1003. while ( this.firstChild )
  1004. this.removeChild( this.firstChild );
  1005. }
  1006. }, function(name, fn){
  1007. jQuery.fn[ name ] = function(){
  1008. return this.each( fn, arguments );
  1009. };
  1010. });
  1011. // Helper function used by the dimensions and offset modules
  1012. function num(elem, prop) {
  1013. return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
  1014. }
  1015. var expando = "jQuery" + now(), uuid = 0, windowData = {};
  1016. jQuery.extend({
  1017. cache: {},
  1018. data: function( elem, name, data ) {
  1019. elem = elem == window ?
  1020. windowData :
  1021. elem;
  1022. var id = elem[ expando ];
  1023. // Compute a unique ID for the element
  1024. if ( !id )
  1025. id = elem[ expando ] = ++uuid;
  1026. // Only generate the data cache if we're
  1027. // trying to access or manipulate it
  1028. if ( name && !jQuery.cache[ id ] )
  1029. jQuery.cache[ id ] = {};
  1030. // Prevent overriding the named cache with undefined values
  1031. if ( data !== undefined )
  1032. jQuery.cache[ id ][ name ] = data;
  1033. // Return the named cache data, or the ID for the element
  1034. return name ?
  1035. jQuery.cache[ id ][ name ] :
  1036. id;
  1037. },
  1038. removeData: function( elem, name ) {
  1039. elem = elem == window ?
  1040. windowData :
  1041. elem;
  1042. var id = elem[ expando ];
  1043. // If we want to remove a specific section of the element's data
  1044. if ( name ) {
  1045. if ( jQuery.cache[ id ] ) {
  1046. // Remove the section of cache data
  1047. delete jQuery.cache[ id ][ name ];
  1048. // If we've removed all the data, remove the element's cache
  1049. name = "";
  1050. for ( name in jQuery.cache[ id ] )
  1051. break;
  1052. if ( !name )
  1053. jQuery.removeData( elem );
  1054. }
  1055. // Otherwise, we want to remove all of the element's data
  1056. } else {
  1057. // Clean up the element expando
  1058. try {
  1059. delete elem[ expando ];
  1060. } catch(e){
  1061. // IE has trouble directly removing the expando
  1062. // but it's ok with using removeAttribute
  1063. if ( elem.removeAttribute )
  1064. elem.removeAttribute( expando );
  1065. }
  1066. // Completely remove the data cache
  1067. delete jQuery.cache[ id ];
  1068. }
  1069. },
  1070. queue: function( elem, type, data ) {
  1071. if ( elem ){
  1072. type = (type || "fx") + "queue";
  1073. var q = jQuery.data( elem, type );
  1074. if ( !q || jQuery.isArray(data) )
  1075. q = jQuery.data( elem, type, jQuery.makeArray(data) );
  1076. else if( data )
  1077. q.push( data );
  1078. }
  1079. return q;
  1080. },
  1081. dequeue: function( elem, type ){
  1082. var queue = jQuery.queue( elem, type ),
  1083. fn = queue.shift();
  1084. if( !type || type === "fx" )
  1085. fn = queue[0];
  1086. if( fn !== undefined )
  1087. fn.call(elem);
  1088. }
  1089. });
  1090. jQuery.fn.extend({
  1091. data: function( key, value ){
  1092. var parts = key.split(".");
  1093. parts[1] = parts[1] ? "." + parts[1] : "";
  1094. if ( value === undefined ) {
  1095. var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
  1096. if ( data === undefined && this.length )
  1097. data = jQuery.data( this[0], key );
  1098. return data === undefined && parts[1] ?
  1099. this.data( parts[0] ) :
  1100. data;
  1101. } else
  1102. return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
  1103. jQuery.data( this, key, value );
  1104. });
  1105. },
  1106. removeData: function( key ){
  1107. return this.each(function(){
  1108. jQuery.removeData( this, key );
  1109. });
  1110. },
  1111. queue: function(type, data){
  1112. if ( typeof type !== "string" ) {
  1113. data = type;
  1114. type = "fx";
  1115. }
  1116. if ( data === undefined )
  1117. return jQuery.queue( this[0], type );
  1118. return this.each(function(){
  1119. var queue = jQuery.queue( this, type, data );
  1120. if( type == "fx" && queue.length == 1 )
  1121. queue[0].call(this);
  1122. });
  1123. },
  1124. dequeue: function(type){
  1125. return this.each(function(){
  1126. jQuery.dequeue( this, type );
  1127. });
  1128. }
  1129. });/*!
  1130. * Sizzle CSS Selector Engine - v0.9.3
  1131. * Copyright 2009, The Dojo Foundation
  1132. * Released under the MIT, BSD, and GPL Licenses.
  1133. * More information: http://sizzlejs.com/
  1134. */
  1135. (function(){
  1136. var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
  1137. done = 0,
  1138. toString = Object.prototype.toString;
  1139. var Sizzle = function(selector, context, results, seed) {
  1140. results = results || [];
  1141. context = context || document;
  1142. if ( context.nodeType !== 1 && context.nodeType !== 9 )
  1143. return [];
  1144. if ( !selector || typeof selector !== "string" ) {
  1145. return results;
  1146. }
  1147. var parts = [], m, set, checkSet, check, mode, extra, prune = true;
  1148. // Reset the position of the chunker regexp (start from head)
  1149. chunker.lastIndex = 0;
  1150. while ( (m = chunker.exec(selector)) !== null ) {
  1151. parts.push( m[1] );
  1152. if ( m[2] ) {
  1153. extra = RegExp.rightContext;
  1154. break;
  1155. }
  1156. }
  1157. if ( parts.length > 1 && origPOS.exec( selector ) ) {
  1158. if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
  1159. set = posProcess( parts[0] + parts[1], context );
  1160. } else {
  1161. set = Expr.relative[ parts[0] ] ?
  1162. [ context ] :
  1163. Sizzle( parts.shift(), context );
  1164. while ( parts.length ) {
  1165. selector = parts.shift();
  1166. if ( Expr.relative[ selector ] )
  1167. selector += parts.shift();
  1168. set = posProcess( selector, set );
  1169. }
  1170. }
  1171. } else {
  1172. var ret = seed ?
  1173. { expr: parts.pop(), set: makeArray(seed) } :
  1174. Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
  1175. set = Sizzle.filter( ret.expr, ret.set );
  1176. if ( parts.length > 0 ) {
  1177. checkSet = makeArray(set);
  1178. } else {
  1179. prune = false;
  1180. }
  1181. while ( parts.length ) {
  1182. var cur = parts.pop(), pop = cur;
  1183. if ( !Expr.relative[ cur ] ) {
  1184. cur = "";
  1185. } else {
  1186. pop = parts.pop();
  1187. }
  1188. if ( pop == null ) {
  1189. pop = context;
  1190. }
  1191. Expr.relative[ cur ]( checkSet, pop, isXML(context) );
  1192. }
  1193. }
  1194. if ( !checkSet ) {
  1195. checkSet = set;
  1196. }
  1197. if ( !checkSet ) {
  1198. throw "Syntax error, unrecognized expression: " + (cur || selector);
  1199. }
  1200. if ( toString.call(checkSet) === "[object Array]" ) {
  1201. if ( !prune ) {
  1202. results.push.apply( results, checkSet );
  1203. } else if ( context.nodeType === 1 ) {
  1204. for ( var i = 0; checkSet[i] != null; i++ ) {
  1205. if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
  1206. results.push( set[i] );
  1207. }
  1208. }
  1209. } else {
  1210. for ( var i = 0; checkSet[i] != null; i++ ) {
  1211. if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
  1212. results.push( set[i] );
  1213. }
  1214. }
  1215. }
  1216. } else {
  1217. makeArray( checkSet, results );
  1218. }
  1219. if ( extra ) {
  1220. Sizzle( extra, context, results, seed );
  1221. if ( sortOrder ) {
  1222. hasDuplicate = false;
  1223. results.sort(sortOrder);
  1224. if ( hasDuplicate ) {
  1225. for ( var i = 1; i < results.length; i++ ) {
  1226. if ( results[i] === results[i-1] ) {
  1227. results.splice(i--, 1);
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. return results;
  1234. };
  1235. Sizzle.matches = function(expr, set){
  1236. return Sizzle(expr, null, null, set);
  1237. };
  1238. Sizzle.find = function(expr, context, isXML){
  1239. var set, match;
  1240. if ( !expr ) {
  1241. return [];
  1242. }
  1243. for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
  1244. var type = Expr.order[i], match;
  1245. if ( (match = Expr.match[ type ].exec( expr )) ) {
  1246. var left = RegExp.leftContext;
  1247. if ( left.substr( left.length - 1 ) !== "\\" ) {
  1248. match[1] = (match[1] || "").replace(/\\/g, "");
  1249. set = Expr.find[ type ]( match, context, isXML );
  1250. if ( set != null ) {
  1251. expr = expr.replace( Expr.match[ type ], "" );
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. }
  1257. if ( !set ) {
  1258. set = context.getElementsByTagName("*");
  1259. }
  1260. return {set: set, expr: expr};
  1261. };
  1262. Sizzle.filter = function(expr, set, inplace, not){
  1263. var old = expr, result = [], curLoop = set, match, anyFound,
  1264. isXMLFilter = set && set[0] && isXML(set[0]);
  1265. while ( expr && set.length ) {
  1266. for ( var type in Expr.filter ) {
  1267. if ( (match = Expr.match[ type ].exec( expr )) != null ) {
  1268. var filter = Expr.filter[ type ], found, item;
  1269. anyFound = false;
  1270. if ( curLoop == result ) {
  1271. result = [];
  1272. }
  1273. if ( Expr.preFilter[ type ] ) {
  1274. match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
  1275. if ( !match ) {
  1276. anyFound = found = true;
  1277. } else if ( match === true ) {
  1278. continue;
  1279. }
  1280. }
  1281. if ( match ) {
  1282. for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
  1283. if ( item ) {
  1284. found = filter( item, match, i, curLoop );
  1285. var pass = not ^ !!found;
  1286. if ( inplace && found != null ) {
  1287. if ( pass ) {
  1288. anyFound = true;
  1289. } else {
  1290. curLoop[i] = false;
  1291. }
  1292. } else if ( pass ) {
  1293. result.push( item );
  1294. anyFound = true;
  1295. }
  1296. }
  1297. }
  1298. }
  1299. if ( found !== undefined ) {
  1300. if ( !inplace ) {
  1301. curLoop = result;
  1302. }
  1303. expr = expr.replace( Expr.match[ type ], "" );
  1304. if ( !anyFound ) {
  1305. return [];
  1306. }
  1307. break;
  1308. }
  1309. }
  1310. }
  1311. // Improper expression
  1312. if ( expr == old ) {
  1313. if ( anyFound == null ) {
  1314. throw "Syntax error, unrecognized expression: " + expr;
  1315. } else {
  1316. break;
  1317. }
  1318. }
  1319. old = expr;
  1320. }
  1321. return curLoop;
  1322. };
  1323. var Expr = Sizzle.selectors = {
  1324. order: [ "ID", "NAME", "TAG" ],
  1325. match: {
  1326. ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
  1327. CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
  1328. NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
  1329. ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
  1330. TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
  1331. CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
  1332. POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
  1333. PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
  1334. },
  1335. attrMap: {
  1336. "class": "className",
  1337. "for": "htmlFor"
  1338. },
  1339. attrHandle: {
  1340. href: function(elem){
  1341. return elem.getAttribute("href");
  1342. }
  1343. },
  1344. relative: {
  1345. "+": function(checkSet, part, isXML){
  1346. var isPartStr = typeof part === "string",
  1347. isTag = isPartStr && !/\W/.test(part),
  1348. isPartStrNotTag = isPartStr && !isTag;
  1349. if ( isTag && !isXML ) {
  1350. part = part.toUpperCase();
  1351. }
  1352. for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
  1353. if ( (elem = checkSet[i]) ) {
  1354. while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
  1355. checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
  1356. elem || false :
  1357. elem === part;
  1358. }
  1359. }
  1360. if ( isPartStrNotTag ) {
  1361. Sizzle.filter( part, checkSet, true );
  1362. }
  1363. },
  1364. ">": function(checkSet, part, isXML){
  1365. var isPartStr = typeof part === "string";
  1366. if ( isPartStr && !/\W/.test(part) ) {
  1367. part = isXML ? part : part.toUpperCase();
  1368. for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  1369. var elem = checkSet[i];
  1370. if ( elem ) {
  1371. var parent = elem.parentNode;
  1372. checkSet[i] = parent.nodeName === part ? parent : false;
  1373. }
  1374. }
  1375. } else {
  1376. for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  1377. var elem = checkSet[i];
  1378. if ( elem ) {
  1379. checkSet[i] = isPartStr ?
  1380. elem.parentNode :
  1381. elem.parentNode === part;
  1382. }
  1383. }
  1384. if ( isPartStr ) {
  1385. Sizzle.filter( part, checkSet, true );
  1386. }
  1387. }
  1388. },
  1389. "": function(checkSet, part, isXML){
  1390. var doneName = done++, checkFn = dirCheck;
  1391. if ( !part.match(/\W/) ) {
  1392. var nodeCheck = part = isXML ? part : part.toUpperCase();
  1393. checkFn = dirNodeCheck;
  1394. }
  1395. checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
  1396. },
  1397. "~": function(checkSet, part, isXML){
  1398. var doneName = done++, checkFn = dirCheck;
  1399. if ( typeof part === "string" && !part.match(/\W/) ) {
  1400. var nodeCheck = part = isXML ? part : part.toUpperCase();
  1401. checkFn = dirNodeCheck;
  1402. }
  1403. checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
  1404. }
  1405. },
  1406. find: {
  1407. ID: function(match, context, isXML){
  1408. if ( typeof context.getElementById !== "undefined" && !isXML ) {
  1409. var m = context.getElementById(match[1]);
  1410. return m ? [m] : [];
  1411. }
  1412. },
  1413. NAME: function(match, context, isXML){
  1414. if ( typeof context.getElementsByName !== "undefined" ) {
  1415. var ret = [], results = context.getElementsByName(match[1]);
  1416. for ( var i = 0, l = results.length; i < l; i++ ) {
  1417. if ( results[i].getAttribute("name") === match[1] ) {
  1418. ret.push( results[i] );
  1419. }
  1420. }
  1421. return ret.length === 0 ? null : ret;
  1422. }
  1423. },
  1424. TAG: function(match, context){
  1425. return context.getElementsByTagName(match[1]);
  1426. }
  1427. },
  1428. preFilter: {
  1429. CLASS: function(match, curLoop, inplace, result, not, isXML){
  1430. match = " " + match[1].replace(/\\/g, "") + " ";
  1431. if ( isXML ) {
  1432. return match;
  1433. }
  1434. for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
  1435. if ( elem ) {
  1436. if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
  1437. if ( !inplace )
  1438. result.push( elem );
  1439. } else if ( inplace ) {
  1440. curLoop[i] = false;
  1441. }
  1442. }
  1443. }
  1444. return false;
  1445. },
  1446. ID: function(match){
  1447. return match[1].replace(/\\/g, "");
  1448. },
  1449. TAG: function(match, curLoop){
  1450. for ( var i = 0; curLoop[i] === false; i++ ){}
  1451. return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
  1452. },
  1453. CHILD: function(match){
  1454. if ( match[1] == "nth" ) {
  1455. // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
  1456. var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
  1457. match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
  1458. !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
  1459. // calculate the numbers (first)n+(last) including if they are negative
  1460. match[2] = (test[1] + (test[2] || 1)) - 0;
  1461. match[3] = test[3] - 0;
  1462. }
  1463. // TODO: Move to normal caching system
  1464. match[0] = done++;
  1465. return match;
  1466. },
  1467. ATTR: function(match, curLoop, inplace, result, not, isXML){
  1468. var name = match[1].replace(/\\/g, "");
  1469. if ( !isXML && Expr.attrMap[name] ) {
  1470. match[1] = Expr.attrMap[name];
  1471. }
  1472. if ( match[2] === "~=" ) {
  1473. match[4] = " " + match[4] + " ";
  1474. }
  1475. return match;
  1476. },
  1477. PSEUDO: function(match, curLoop, inplace, result, not){
  1478. if ( match[1] === "not" ) {
  1479. // If we're dealing with a complex expression, or a simple one
  1480. if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
  1481. match[3] = Sizzle(match[3], null, null, curLoop);
  1482. } else {
  1483. var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
  1484. if ( !inplace ) {
  1485. result.push.apply( result, ret );
  1486. }
  1487. return false;
  1488. }
  1489. } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
  1490. return true;
  1491. }
  1492. return match;
  1493. },
  1494. POS: function(match){
  1495. match.unshift( true );
  1496. return match;
  1497. }
  1498. },
  1499. filters: {
  1500. enabled: function(elem){
  1501. return elem.disabled === false && elem.type !== "hidden";
  1502. },
  1503. disabled: function(elem){
  1504. return elem.disabled === true;
  1505. },
  1506. checked: function(elem){
  1507. return elem.checked === true;
  1508. },
  1509. selected: function(elem){
  1510. // Accessing this property makes selected-by-default
  1511. // options in Safari work properly
  1512. elem.parentNode.selectedIndex;
  1513. return elem.selected === true;
  1514. },
  1515. parent: function(elem){
  1516. return !!elem.firstChild;
  1517. },
  1518. empty: function(elem){
  1519. return !elem.firstChild;
  1520. },
  1521. has: function(elem, i, match){
  1522. return !!Sizzle( match[3], elem ).length;
  1523. },
  1524. header: function(elem){
  1525. return /h\d/i.test( elem.nodeName );
  1526. },
  1527. text: function(elem){
  1528. return "text" === elem.type;
  1529. },
  1530. radio: function(elem){
  1531. return "radio" === elem.type;
  1532. },
  1533. checkbox: function(elem){
  1534. return "checkbox" === elem.type;
  1535. },
  1536. file: function(elem){
  1537. return "file" === elem.type;
  1538. },
  1539. password: function(elem){
  1540. return "password" === elem.type;
  1541. },
  1542. submit: function(elem){
  1543. return "submit" === elem.type;
  1544. },
  1545. image: function(elem){
  1546. return "image" === elem.type;
  1547. },
  1548. reset: function(elem){
  1549. return "reset" === elem.type;
  1550. },
  1551. button: function(elem){
  1552. return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
  1553. },
  1554. input: function(elem){
  1555. return /input|select|textarea|button/i.test(elem.nodeName);
  1556. }
  1557. },
  1558. setFilters: {
  1559. first: function(elem, i){
  1560. return i === 0;
  1561. },
  1562. last: function(elem, i, match, array){
  1563. return i === array.length - 1;
  1564. },
  1565. even: function(elem, i){
  1566. return i % 2 === 0;
  1567. },
  1568. odd: function(elem, i){
  1569. return i % 2 === 1;
  1570. },
  1571. lt: function(elem, i, match){
  1572. return i < match[3] - 0;
  1573. },
  1574. gt: function(elem, i, match){
  1575. return i > match[3] - 0;
  1576. },
  1577. nth: function(elem, i, match){
  1578. return match[3] - 0 == i;
  1579. },
  1580. eq: function(elem, i, match){
  1581. return match[3] - 0 == i;
  1582. }
  1583. },
  1584. filter: {
  1585. PSEUDO: function(elem, match, i, array){
  1586. var name = match[1], filter = Expr.filters[ name ];
  1587. if ( filter ) {
  1588. return filter( elem, i, match, array );
  1589. } else if ( name === "contains" ) {
  1590. return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
  1591. } else if ( name === "not" ) {
  1592. var not = match[3];
  1593. for ( var i = 0, l = not.length; i < l; i++ ) {
  1594. if ( not[i] === elem ) {
  1595. return false;
  1596. }
  1597. }
  1598. return true;
  1599. }
  1600. },
  1601. CHILD: function(elem, match){
  1602. var type = match[1], node = elem;
  1603. switch (type) {
  1604. case 'only':
  1605. case 'first':
  1606. while (node = node.previousSibling) {
  1607. if ( node.nodeType === 1 ) return false;
  1608. }
  1609. if ( type == 'first') return true;
  1610. node = elem;
  1611. case 'last':
  1612. while (node = node.nextSibling) {
  1613. if ( node.nodeType === 1 ) return false;
  1614. }
  1615. return true;
  1616. case 'nth':
  1617. var first = match[2], last = match[3];
  1618. if ( first == 1 && last == 0 ) {
  1619. return true;
  1620. }
  1621. var doneName = match[0],
  1622. parent = elem.parentNode;
  1623. if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
  1624. var count = 0;
  1625. for ( node = parent.firstChild; node; node = node.nextSibling ) {
  1626. if ( node.nodeType === 1 ) {
  1627. node.nodeIndex = ++count;
  1628. }
  1629. }
  1630. parent.sizcache = doneName;
  1631. }
  1632. var diff = elem.nodeIndex - last;
  1633. if ( first == 0 ) {
  1634. return diff == 0;
  1635. } else {
  1636. return ( diff % first == 0 && diff / first >= 0 );
  1637. }
  1638. }
  1639. },
  1640. ID: function(elem, match){
  1641. return elem.nodeType === 1 && elem.getAttribute("id") === match;
  1642. },
  1643. TAG: function(elem, match){
  1644. return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
  1645. },
  1646. CLASS: function(elem, match){
  1647. return (" " + (elem.className || elem.getAttribute("class")) + " ")
  1648. .indexOf( match ) > -1;
  1649. },
  1650. ATTR: function(elem, match){
  1651. var name = match[1],
  1652. result = Expr.attrHandle[ name ] ?
  1653. Expr.attrHandle[ name ]( elem ) :
  1654. elem[ name ] != null ?
  1655. elem[ name ] :
  1656. elem.getAttribute( name ),
  1657. value = result + "",
  1658. type = match[2],
  1659. check = match[4];
  1660. return result == null ?
  1661. type === "!=" :
  1662. type === "=" ?
  1663. value === check :
  1664. type === "*=" ?
  1665. value.indexOf(check) >= 0 :
  1666. type === "~=" ?
  1667. (" " + value + " ").indexOf(check) >= 0 :
  1668. !check ?
  1669. value && result !== false :
  1670. type === "!=" ?
  1671. value != check :
  1672. type === "^=" ?
  1673. value.indexOf(check) === 0 :
  1674. type === "$=" ?
  1675. value.substr(value.length - check.length) === check :
  1676. type === "|=" ?
  1677. value === check || value.substr(0, check.length + 1) === check + "-" :
  1678. false;
  1679. },
  1680. POS: function(elem, match, i, array){
  1681. var name = match[2], filter = Expr.setFilters[ name ];
  1682. if ( filter ) {
  1683. return filter( elem, i, match, array );
  1684. }
  1685. }
  1686. }
  1687. };
  1688. var origPOS = Expr.match.POS;
  1689. for ( var type in Expr.match ) {
  1690. Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
  1691. }
  1692. var makeArray = function(array, results) {
  1693. array = Array.prototype.slice.call( array );
  1694. if ( results ) {
  1695. results.push.apply( results, array );
  1696. return results;
  1697. }
  1698. return array;
  1699. };
  1700. // Perform a simple check to determine if the browser is capable of
  1701. // converting a NodeList to an array using builtin methods.
  1702. try {
  1703. Array.prototype.slice.call( document.documentElement.childNodes );
  1704. // Provide a fallback method if it does not work
  1705. } catch(e){
  1706. makeArray = function(array, results) {
  1707. var ret = results || [];
  1708. if ( toString.call(array) === "[object Array]" ) {
  1709. Array.prototype.push.apply( ret, array );
  1710. } else {
  1711. if ( typeof array.length === "number" ) {
  1712. for ( var i = 0, l = array.length; i < l; i++ ) {
  1713. ret.push( array[i] );
  1714. }
  1715. } else {
  1716. for ( var i = 0; array[i]; i++ ) {
  1717. ret.push( array[i] );
  1718. }
  1719. }
  1720. }
  1721. return ret;
  1722. };
  1723. }
  1724. var sortOrder;
  1725. if ( document.documentElement.compareDocumentPosition ) {
  1726. sortOrder = function( a, b ) {
  1727. var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
  1728. if ( ret === 0 ) {
  1729. hasDuplicate = true;
  1730. }
  1731. return ret;
  1732. };
  1733. } else if ( "sourceIndex" in document.documentElement ) {
  1734. sortOrder = function( a, b ) {
  1735. var ret = a.sourceIndex - b.sourceIndex;
  1736. if ( ret === 0 ) {
  1737. hasDuplicate = true;
  1738. }
  1739. return ret;
  1740. };
  1741. } else if ( document.createRange ) {
  1742. sortOrder = function( a, b ) {
  1743. var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
  1744. aRange.selectNode(a);
  1745. aRange.collapse(true);
  1746. bRange.selectNode(b);
  1747. bRange.collapse(true);
  1748. var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
  1749. if ( ret === 0 ) {
  1750. hasDuplicate = true;
  1751. }
  1752. return ret;
  1753. };
  1754. }
  1755. // Check to see if the browser returns elements by name when
  1756. // querying by getElementById (and provide a workaround)
  1757. (function(){
  1758. // We're going to inject a fake input element with a specified name
  1759. var form = document.createElement("form"),
  1760. id = "script" + (new Date).getTime();
  1761. form.innerHTML = "<input name='" + id + "'/>";
  1762. // Inject it into the root element, check its status, and remove it quickly
  1763. var root = document.documentElement;
  1764. root.insertBefore( form, root.firstChild );
  1765. // The workaround has to do additional checks after a getElementById
  1766. // Which slows things down for other browsers (hence the branching)
  1767. if ( !!document.getElementById( id ) ) {
  1768. Expr.find.ID = function(match, context, isXML){
  1769. if ( typeof context.getElementById !== "undefined" && !isXML ) {
  1770. var m = context.getElementById(match[1]);
  1771. return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
  1772. }
  1773. };
  1774. Expr.filter.ID = function(elem, match){
  1775. var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
  1776. return elem.nodeType === 1 && node && node.nodeValue === match;
  1777. };
  1778. }
  1779. root.removeChild( form );
  1780. })();
  1781. (function(){
  1782. // Check to see if the browser returns only elements
  1783. // when doing getElementsByTagName("*")
  1784. // Create a fake element
  1785. var div = document.createElement("div");
  1786. div.appendChild( document.createComment("") );
  1787. // Make sure no comments are found
  1788. if ( div.getElementsByTagName("*").length > 0 ) {
  1789. Expr.find.TAG = function(match, context){
  1790. var results = context.getElementsByTagName(match[1]);
  1791. // Filter out possible comments
  1792. if ( match[1] === "*" ) {
  1793. var tmp = [];
  1794. for ( var i = 0; results[i]; i++ ) {
  1795. if ( results[i].nodeType === 1 ) {
  1796. tmp.push( results[i] );
  1797. }
  1798. }
  1799. results = tmp;
  1800. }
  1801. return results;
  1802. };
  1803. }
  1804. // Check to see if an attribute returns normalized href attributes
  1805. div.innerHTML = "<a href='#'></a>";
  1806. if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
  1807. div.firstChild.getAttribute("href") !== "#" ) {
  1808. Expr.attrHandle.href = function(elem){
  1809. return elem.getAttribute("href", 2);
  1810. };
  1811. }
  1812. })();
  1813. if ( document.querySelectorAll ) (function(){
  1814. var oldSizzle = Sizzle, div = document.createElement("div");
  1815. div.innerHTML = "<p class='TEST'></p>";
  1816. // Safari can't handle uppercase or unicode characters when
  1817. // in quirks mode.
  1818. if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
  1819. return;
  1820. }
  1821. Sizzle = function(query, context, extra, seed){
  1822. context = context || document;
  1823. // Only use querySelectorAll on non-XML documents
  1824. // (ID selectors don't work in non-HTML documents)
  1825. if ( !seed && context.nodeType === 9 && !isXML(context) ) {
  1826. try {
  1827. return makeArray( context.querySelectorAll(query), extra );
  1828. } catch(e){}
  1829. }
  1830. return oldSizzle(query, context, extra, seed);
  1831. };
  1832. Sizzle.find = oldSizzle.find;
  1833. Sizzle.filter = oldSizzle.filter;
  1834. Sizzle.selectors = oldSizzle.selectors;
  1835. Sizzle.matches = oldSizzle.matches;
  1836. })();
  1837. if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
  1838. var div = document.createElement("div");
  1839. div.innerHTML = "<div class='test e'></div><div class='test'></div>";
  1840. // Opera can't find a second classname (in 9.6)
  1841. if ( div.getElementsByClassName("e").length === 0 )
  1842. return;
  1843. // Safari caches class attributes, doesn't catch changes (in 3.2)
  1844. div.lastChild.className = "e";
  1845. if ( div.getElementsByClassName("e").length === 1 )
  1846. return;
  1847. Expr.order.splice(1, 0, "CLASS");
  1848. Expr.find.CLASS = function(match, context, isXML) {
  1849. if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
  1850. return context.getElementsByClassName(match[1]);
  1851. }
  1852. };
  1853. })();
  1854. function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
  1855. var sibDir = dir == "previousSibling" && !isXML;
  1856. for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  1857. var elem = checkSet[i];
  1858. if ( elem ) {
  1859. if ( sibDir && elem.nodeType === 1 ){
  1860. elem.sizcache = doneName;
  1861. elem.sizset = i;
  1862. }
  1863. elem = elem[dir];
  1864. var match = false;
  1865. while ( elem ) {
  1866. if ( elem.sizcache === doneName ) {
  1867. match = checkSet[elem.sizset];
  1868. break;
  1869. }
  1870. if ( elem.nodeType === 1 && !isXML ){
  1871. elem.sizcache = doneName;
  1872. elem.sizset = i;
  1873. }
  1874. if ( elem.nodeName === cur ) {
  1875. match = elem;
  1876. break;
  1877. }
  1878. elem = elem[dir];
  1879. }
  1880. checkSet[i] = match;
  1881. }
  1882. }
  1883. }
  1884. function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
  1885. var sibDir = dir == "previousSibling" && !isXML;
  1886. for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  1887. var elem = checkSet[i];
  1888. if ( elem ) {
  1889. if ( sibDir && elem.nodeType === 1 ) {
  1890. elem.sizcache = doneName;
  1891. elem.sizset = i;
  1892. }
  1893. elem = elem[dir];
  1894. var match = false;
  1895. while ( elem ) {
  1896. if ( elem.sizcache === doneName ) {
  1897. match = checkSet[elem.sizset];
  1898. break;
  1899. }
  1900. if ( elem.nodeType === 1 ) {
  1901. if ( !isXML ) {
  1902. elem.sizcache = doneName;
  1903. elem.sizset = i;
  1904. }
  1905. if ( typeof cur !== "string" ) {
  1906. if ( elem === cur ) {
  1907. match = true;
  1908. break;
  1909. }
  1910. } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
  1911. match = elem;
  1912. break;
  1913. }
  1914. }
  1915. elem = elem[dir];
  1916. }
  1917. checkSet[i] = match;
  1918. }
  1919. }
  1920. }
  1921. var contains = document.compareDocumentPosition ? function(a, b){
  1922. return a.compareDocumentPosition(b) & 16;
  1923. } : function(a, b){
  1924. return a !== b && (a.contains ? a.contains(b) : true);
  1925. };
  1926. var isXML = function(elem){
  1927. return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
  1928. !!elem.ownerDocument && isXML( elem.ownerDocument );
  1929. };
  1930. var posProcess = function(selector, context){
  1931. var tmpSet = [], later = "", match,
  1932. root = context.nodeType ? [context] : context;
  1933. // Position selectors must be done after the filter
  1934. // And so must :not(positional) so we move all PSEUDOs to the end
  1935. while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
  1936. later += match[0];
  1937. selector = selector.replace( Expr.match.PSEUDO, "" );
  1938. }
  1939. selector = Expr.relative[selector] ? selector + "*" : selector;
  1940. for ( var i = 0, l = root.length; i < l; i++ ) {
  1941. Sizzle( selector, root[i], tmpSet );
  1942. }
  1943. return Sizzle.filter( later, tmpSet );
  1944. };
  1945. // EXPOSE
  1946. jQuery.find = Sizzle;
  1947. jQuery.filter = Sizzle.filter;
  1948. jQuery.expr = Sizzle.selectors;
  1949. jQuery.expr[":"] = jQuery.expr.filters;
  1950. Sizzle.selectors.filters.hidden = function(elem){
  1951. return elem.offsetWidth === 0 || elem.offsetHeight === 0;
  1952. };
  1953. Sizzle.selectors.filters.visible = function(elem){
  1954. return elem.offsetWidth > 0 || elem.offsetHeight > 0;
  1955. };
  1956. Sizzle.selectors.filters.animated = function(elem){
  1957. return jQuery.grep(jQuery.timers, function(fn){
  1958. return elem === fn.elem;
  1959. }).length;
  1960. };
  1961. jQuery.multiFilter = function( expr, elems, not ) {
  1962. if ( not ) {
  1963. expr = ":not(" + expr + ")";
  1964. }
  1965. return Sizzle.matches(expr, elems);
  1966. };
  1967. jQuery.dir = function( elem, dir ){
  1968. var matched = [], cur = elem[dir];
  1969. while ( cur && cur != document ) {
  1970. if ( cur.nodeType == 1 )
  1971. matched.push( cur );
  1972. cur = cur[dir];
  1973. }
  1974. return matched;
  1975. };
  1976. jQuery.nth = function(cur, result, dir, elem){
  1977. result = result || 1;
  1978. var num = 0;
  1979. for ( ; cur; cur = cur[dir] )
  1980. if ( cur.nodeType == 1 && ++num == result )
  1981. break;
  1982. return cur;
  1983. };
  1984. jQuery.sibling = function(n, elem){
  1985. var r = [];
  1986. for ( ; n; n = n.nextSibling ) {
  1987. if ( n.nodeType == 1 && n != elem )
  1988. r.push( n );
  1989. }
  1990. return r;
  1991. };
  1992. return;
  1993. window.Sizzle = Sizzle;
  1994. })();
  1995. /*
  1996. * A number of helper functions used for managing events.
  1997. * Many of the ideas behind this code originated from
  1998. * Dean Edwards' addEvent library.
  1999. */
  2000. jQuery.event = {
  2001. // Bind an event to an element
  2002. // Original by Dean Edwards
  2003. add: function(elem, types, handler, data) {
  2004. if ( elem.nodeType == 3 || elem.nodeType == 8 )
  2005. return;
  2006. // For whatever reason, IE has trouble passing the window object
  2007. // around, causing it to be cloned in the process
  2008. if ( elem.setInterval && elem != window )
  2009. elem = window;
  2010. // Make sure that the function being executed has a unique ID
  2011. if ( !handler.guid )
  2012. handler.guid = this.guid++;
  2013. // if data is passed, bind to handler
  2014. if ( data !== undefined ) {
  2015. // Create temporary function pointer to original handler
  2016. var fn = handler;
  2017. // Create unique handler function, wrapped around original handler
  2018. handler = this.proxy( fn );
  2019. // Store data in unique handler
  2020. handler.data = data;
  2021. }
  2022. // Init the element's event structure
  2023. var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
  2024. handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
  2025. // Handle the second event of a trigger and when
  2026. // an event is called after a page has unloaded
  2027. return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
  2028. jQuery.event.handle.apply(arguments.callee.elem, arguments) :
  2029. undefined;
  2030. });
  2031. // Add elem as a property of the handle function
  2032. // This is to prevent a memory leak with non-native
  2033. // event in IE.
  2034. handle.elem = elem;
  2035. // Handle multiple events separated by a space
  2036. // jQuery(...).bind("mouseover mouseout", fn);
  2037. jQuery.each(types.split(/\s+/), function(index, type) {
  2038. // Namespaced event handlers
  2039. var namespaces = type.split(".");
  2040. type = namespaces.shift();
  2041. handler.type = namespaces.slice().sort().join(".");
  2042. // Get the current list of functions bound to this event
  2043. var handlers = events[type];
  2044. if ( jQuery.event.specialAll[type] )
  2045. jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
  2046. // Init the event handler queue
  2047. if (!handlers) {
  2048. handlers = events[type] = {};
  2049. // Check for a special event handler
  2050. // Only use addEventListener/attachEvent if the special
  2051. // events handler returns false
  2052. if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
  2053. // Bind the global event handler to the element
  2054. if (elem.addEventListener)
  2055. elem.addEventListener(type, handle, false);
  2056. else if (elem.attachEvent)
  2057. elem.attachEvent("on" + type, handle);
  2058. }
  2059. }
  2060. // Add the function to the element's handler list
  2061. handlers[handler.guid] = handler;
  2062. // Keep track of which events have been used, for global triggering
  2063. jQuery.event.global[type] = true;
  2064. });
  2065. // Nullify elem to prevent memory leaks in IE
  2066. elem = null;
  2067. },
  2068. guid: 1,
  2069. global: {},
  2070. // Detach an event or set of events from an element
  2071. remove: function(elem, types, handler) {
  2072. // don't do events on text and comment nodes
  2073. if ( elem.nodeType == 3 || elem.nodeType == 8 )
  2074. return;
  2075. var events = jQuery.data(elem, "events"), ret, index;
  2076. if ( events ) {
  2077. // Unbind all events for the element
  2078. if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
  2079. for ( var type in events )
  2080. this.remove( elem, type + (types || "") );
  2081. else {
  2082. // types is actually an event object here
  2083. if ( types.type ) {
  2084. handler = types.handler;
  2085. types = types.type;
  2086. }
  2087. // Handle multiple events seperated by a space
  2088. // jQuery(...).unbind("mouseover mouseout", fn);
  2089. jQuery.each(types.split(/\s+/), function(index, type){
  2090. // Namespaced event handlers
  2091. var namespaces = type.split(".");
  2092. type = namespaces.shift();
  2093. var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
  2094. if ( events[type] ) {
  2095. // remove the given handler for the given type
  2096. if ( handler )
  2097. delete events[type][handler.guid];
  2098. // remove all handlers for the given type
  2099. else
  2100. for ( var handle in events[type] )
  2101. // Handle the removal of namespaced events
  2102. if ( namespace.test(events[type][handle].type) )
  2103. delete events[type][handle];
  2104. if ( jQuery.event.specialAll[type] )
  2105. jQuery.event.specialAll[type].teardown.call(elem, namespaces);
  2106. // remove generic event handler if no more handlers exist
  2107. for ( ret in events[type] ) break;
  2108. if ( !ret ) {
  2109. if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
  2110. if (elem.removeEventListener)
  2111. elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
  2112. else if (elem.detachEvent)
  2113. elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
  2114. }
  2115. ret = null;
  2116. delete events[type];
  2117. }
  2118. }
  2119. });
  2120. }
  2121. // Remove the expando if it's no longer used
  2122. for ( ret in events ) break;
  2123. if ( !ret ) {
  2124. var handle = jQuery.data( elem, "handle" );
  2125. if ( handle ) handle.elem = null;
  2126. jQuery.removeData( elem, "events" );
  2127. jQuery.removeData( elem, "handle" );
  2128. }
  2129. }
  2130. },
  2131. // bubbling is internal
  2132. trigger: function( event, data, elem, bubbling ) {
  2133. // Event object or event type
  2134. var type = event.type || event;
  2135. if( !bubbling ){
  2136. event = typeof event === "object" ?
  2137. // jQuery.Event object
  2138. event[expando] ? event :
  2139. // Object literal
  2140. jQuery.extend( jQuery.Event(type), event ) :
  2141. // Just the event type (string)
  2142. jQuery.Event(type);
  2143. if ( type.indexOf("!") >= 0 ) {
  2144. event.type = type = type.slice(0, -1);
  2145. event.exclusive = true;
  2146. }
  2147. // Handle a global trigger
  2148. if ( !elem ) {
  2149. // Don't bubble custom events when global (to avoid too much overhead)
  2150. event.stopPropagation();
  2151. // Only trigger if we've ever bound an event for it
  2152. if ( this.global[type] )
  2153. jQuery.each( jQuery.cache, function(){
  2154. if ( this.events && this.events[type] )
  2155. jQuery.event.trigger( event, data, this.handle.elem );
  2156. });
  2157. }
  2158. // Handle triggering a single element
  2159. // don't do events on text and comment nodes
  2160. if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
  2161. return undefined;
  2162. // Clean up in case it is reused
  2163. event.result = undefined;
  2164. event.target = elem;
  2165. // Clone the incoming data, if any
  2166. data = jQuery.makeArray(data);
  2167. data.unshift( event );
  2168. }
  2169. event.currentTarget = elem;
  2170. // Trigger the event, it is assumed that "handle" is a function
  2171. var handle = jQuery.data(elem, "handle");
  2172. if ( handle )
  2173. handle.apply( elem, data );
  2174. // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
  2175. if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
  2176. event.result = false;
  2177. // Trigger the native events (except for clicks on links)
  2178. if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
  2179. this.triggered = true;
  2180. try {
  2181. elem[ type ]();
  2182. // prevent IE from throwing an error for some hidden elements
  2183. } catch (e) {}
  2184. }
  2185. this.triggered = false;
  2186. if ( !event.isPropagationStopped() ) {
  2187. var parent = elem.parentNode || elem.ownerDocument;
  2188. if ( parent )
  2189. jQuery.event.trigger(event, data, parent, true);
  2190. }
  2191. },
  2192. handle: function(event) {
  2193. // returned undefined or false
  2194. var all, handlers;
  2195. event = arguments[0] = jQuery.event.fix( event || window.event );
  2196. event.currentTarget = this;
  2197. // Namespaced event handlers
  2198. var namespaces = event.type.split(".");
  2199. event.type = namespaces.shift();
  2200. // Cache this now, all = true means, any handler
  2201. all = !namespaces.length && !event.exclusive;
  2202. var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
  2203. handlers = ( jQuery.data(this, "events") || {} )[event.type];
  2204. for ( var j in handlers ) {
  2205. var handler = handlers[j];
  2206. // Filter the functions by class
  2207. if ( all || namespace.test(handler.type) ) {
  2208. // Pass in a reference to the handler function itself
  2209. // So that we can later remove it
  2210. event.handler = handler;
  2211. event.data = handler.data;
  2212. var ret = handler.apply(this, arguments);
  2213. if( ret !== undefined ){
  2214. event.result = ret;
  2215. if ( ret === false ) {
  2216. event.preventDefault();
  2217. event.stopPropagation();
  2218. }
  2219. }
  2220. if( event.isImmediatePropagationStopped() )
  2221. break;
  2222. }
  2223. }
  2224. },
  2225. props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
  2226. fix: function(event) {
  2227. if ( event[expando] )
  2228. return event;
  2229. // store a copy of the original event object
  2230. // and "clone" to set read-only properties
  2231. var originalEvent = event;
  2232. event = jQuery.Event( originalEvent );
  2233. for ( var i = this.props.length, prop; i; ){
  2234. prop = this.props[ --i ];
  2235. event[ prop ] = originalEvent[ prop ];
  2236. }
  2237. // Fix target property, if necessary
  2238. if ( !event.target )
  2239. event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
  2240. // check if target is a textnode (safari)
  2241. if ( event.target.nodeType == 3 )
  2242. event.target = event.target.parentNode;
  2243. // Add relatedTarget, if necessary
  2244. if ( !event.relatedTarget && event.fromElement )
  2245. event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
  2246. // Calculate pageX/Y if missing and clientX/Y available
  2247. if ( event.pageX == null && event.clientX != null ) {
  2248. var doc = document.documentElement, body = document.body;
  2249. event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
  2250. event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
  2251. }
  2252. // Add which for key events
  2253. if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
  2254. event.which = event.charCode || event.keyCode;
  2255. // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
  2256. if ( !event.metaKey && event.ctrlKey )
  2257. event.metaKey = event.ctrlKey;
  2258. // Add which for click: 1 == left; 2 == middle; 3 == right
  2259. // Note: button is not normalized, so don't use it
  2260. if ( !event.which && event.button )
  2261. event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
  2262. return event;
  2263. },
  2264. proxy: function( fn, proxy ){
  2265. proxy = proxy || function(){ return fn.apply(this, arguments); };
  2266. // Set the guid of unique handler to the same of original handler, so it can be removed
  2267. proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
  2268. // So proxy can be declared as an argument
  2269. return proxy;
  2270. },
  2271. special: {
  2272. ready: {
  2273. // Make sure the ready event is setup
  2274. setup: bindReady,
  2275. teardown: function() {}
  2276. }
  2277. },
  2278. specialAll: {
  2279. live: {
  2280. setup: function( selector, namespaces ){
  2281. jQuery.event.add( this, namespaces[0], liveHandler );
  2282. },
  2283. teardown: function( namespaces ){
  2284. if ( namespaces.length ) {
  2285. var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
  2286. jQuery.each( (jQuery.data(this, "events").live || {}), function(){
  2287. if ( name.test(this.type) )
  2288. remove++;
  2289. });
  2290. if ( remove < 1 )
  2291. jQuery.event.remove( this, namespaces[0], liveHandler );
  2292. }
  2293. }
  2294. }
  2295. }
  2296. };
  2297. jQuery.Event = function( src ){
  2298. // Allow instantiation without the 'new' keyword
  2299. if( !this.preventDefault )
  2300. return new jQuery.Event(src);
  2301. // Event object
  2302. if( src && src.type ){
  2303. this.originalEvent = src;
  2304. this.type = src.type;
  2305. // Event type
  2306. }else
  2307. this.type = src;
  2308. // timeStamp is buggy for some events on Firefox(#3843)
  2309. // So we won't rely on the native value
  2310. this.timeStamp = now();
  2311. // Mark it as fixed
  2312. this[expando] = true;
  2313. };
  2314. function returnFalse(){
  2315. return false;
  2316. }
  2317. function returnTrue(){
  2318. return true;
  2319. }
  2320. // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
  2321. // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  2322. jQuery.Event.prototype = {
  2323. preventDefault: function() {
  2324. this.isDefaultPrevented = returnTrue;
  2325. var e = this.originalEvent;
  2326. if( !e )
  2327. return;
  2328. // if preventDefault exists run it on the original event
  2329. if (e.preventDefault)
  2330. e.preventDefault();
  2331. // otherwise set the returnValue property of the original event to false (IE)
  2332. e.returnValue = false;
  2333. },
  2334. stopPropagation: function() {
  2335. this.isPropagationStopped = returnTrue;
  2336. var e = this.originalEvent;
  2337. if( !e )
  2338. return;
  2339. // if stopPropagation exists run it on the original event
  2340. if (e.stopPropagation)
  2341. e.stopPropagation();
  2342. // otherwise set the cancelBubble property of the original event to true (IE)
  2343. e.cancelBubble = true;
  2344. },
  2345. stopImmediatePropagation:function(){
  2346. this.isImmediatePropagationStopped = returnTrue;
  2347. this.stopPropagation();
  2348. },
  2349. isDefaultPrevented: returnFalse,
  2350. isPropagationStopped: returnFalse,
  2351. isImmediatePropagationStopped: returnFalse
  2352. };
  2353. // Checks if an event happened on an element within another element
  2354. // Used in jQuery.event.special.mouseenter and mouseleave handlers
  2355. var withinElement = function(event) {
  2356. // Check if mouse(over|out) are still within the same parent element
  2357. var parent = event.relatedTarget;
  2358. // Traverse up the tree
  2359. while ( parent && parent != this )
  2360. try { parent = parent.parentNode; }
  2361. catch(e) { parent = this; }
  2362. if( parent != this ){
  2363. // set the correct event type
  2364. event.type = event.data;
  2365. // handle event if we actually just moused on to a non sub-element
  2366. jQuery.event.handle.apply( this, arguments );
  2367. }
  2368. };
  2369. jQuery.each({
  2370. mouseover: 'mouseenter',
  2371. mouseout: 'mouseleave'
  2372. }, function( orig, fix ){
  2373. jQuery.event.special[ fix ] = {
  2374. setup: function(){
  2375. jQuery.event.add( this, orig, withinElement, fix );
  2376. },
  2377. teardown: function(){
  2378. jQuery.event.remove( this, orig, withinElement );
  2379. }
  2380. };
  2381. });
  2382. jQuery.fn.extend({
  2383. bind: function( type, data, fn ) {
  2384. return type == "unload" ? this.one(type, data, fn) : this.each(function(){
  2385. jQuery.event.add( this, type, fn || data, fn && data );
  2386. });
  2387. },
  2388. one: function( type, data, fn ) {
  2389. var one = jQuery.event.proxy( fn || data, function(event) {
  2390. jQuery(this).unbind(event, one);
  2391. return (fn || data).apply( this, arguments );
  2392. });
  2393. return this.each(function(){
  2394. jQuery.event.add( this, type, one, fn && data);
  2395. });
  2396. },
  2397. unbind: function( type, fn ) {
  2398. return this.each(function(){
  2399. jQuery.event.remove( this, type, fn );
  2400. });
  2401. },
  2402. trigger: function( type, data ) {
  2403. return this.each(function(){
  2404. jQuery.event.trigger( type, data, this );
  2405. });
  2406. },
  2407. triggerHandler: function( type, data ) {
  2408. if( this[0] ){
  2409. var event = jQuery.Event(type);
  2410. event.preventDefault();
  2411. event.stopPropagation();
  2412. jQuery.event.trigger( event, data, this[0] );
  2413. return event.result;
  2414. }
  2415. },
  2416. toggle: function( fn ) {
  2417. // Save reference to arguments for access in closure
  2418. var args = arguments, i = 1;
  2419. // link all the functions, so any of them can unbind this click handler
  2420. while( i < args.length )
  2421. jQuery.event.proxy( fn, args[i++] );
  2422. return this.click( jQuery.event.proxy( fn, function(event) {
  2423. // Figure out which function to execute
  2424. this.lastToggle = ( this.lastToggle || 0 ) % i;
  2425. // Make sure that clicks stop
  2426. event.preventDefault();
  2427. // and execute the function
  2428. return args[ this.lastToggle++ ].apply( this, arguments ) || false;
  2429. }));
  2430. },
  2431. hover: function(fnOver, fnOut) {
  2432. return this.mouseenter(fnOver).mouseleave(fnOut);
  2433. },
  2434. ready: function(fn) {
  2435. // Attach the listeners
  2436. bindReady();
  2437. // If the DOM is already ready
  2438. if ( jQuery.isReady )
  2439. // Execute the function immediately
  2440. fn.call( document, jQuery );
  2441. // Otherwise, remember the function for later
  2442. else
  2443. // Add the function to the wait list
  2444. jQuery.readyList.push( fn );
  2445. return this;
  2446. },
  2447. live: function( type, fn ){
  2448. var proxy = jQuery.event.proxy( fn );
  2449. proxy.guid += this.selector + type;
  2450. jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );
  2451. return this;
  2452. },
  2453. die: function( type, fn ){
  2454. jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
  2455. return this;
  2456. }
  2457. });
  2458. function liveHandler( event ){
  2459. var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
  2460. stop = true,
  2461. elems = [];
  2462. jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
  2463. if ( check.test(fn.type) ) {
  2464. var elem = jQuery(event.target).closest(fn.data)[0];
  2465. if ( elem )
  2466. elems.push({ elem: elem, fn: fn });
  2467. }
  2468. });
  2469. elems.sort(function(a,b) {
  2470. return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
  2471. });
  2472. jQuery.each(elems, function(){
  2473. if ( this.fn.call(this.elem, event, this.fn.data) === false )
  2474. return (stop = false);
  2475. });
  2476. return stop;
  2477. }
  2478. function liveConvert(type, selector){
  2479. return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
  2480. }
  2481. jQuery.extend({
  2482. isReady: false,
  2483. readyList: [],
  2484. // Handle when the DOM is ready
  2485. ready: function() {
  2486. // Make sure that the DOM is not already loaded
  2487. if ( !jQuery.isReady ) {
  2488. // Remember that the DOM is ready
  2489. jQuery.isReady = true;
  2490. // If there are functions bound, to execute
  2491. if ( jQuery.readyList ) {
  2492. // Execute all of them
  2493. jQuery.each( jQuery.readyList, function(){
  2494. this.call( document, jQuery );
  2495. });
  2496. // Reset the list of functions
  2497. jQuery.readyList = null;
  2498. }
  2499. // Trigger any bound ready events
  2500. jQuery(document).triggerHandler("ready");
  2501. }
  2502. }
  2503. });
  2504. var readyBound = false;
  2505. function bindReady(){
  2506. if ( readyBound ) return;
  2507. readyBound = true;
  2508. // Mozilla, Opera and webkit nightlies currently support this event
  2509. if ( document.addEventListener ) {
  2510. // Use the handy event callback
  2511. document.addEventListener( "DOMContentLoaded", function(){
  2512. document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
  2513. jQuery.ready();
  2514. }, false );
  2515. // If IE event model is used
  2516. } else if ( document.attachEvent ) {
  2517. // ensure firing before onload,
  2518. // maybe late but safe also for iframes
  2519. document.attachEvent("onreadystatechange", function(){
  2520. if ( document.readyState === "complete" ) {
  2521. document.detachEvent( "onreadystatechange", arguments.callee );
  2522. jQuery.ready();
  2523. }
  2524. });
  2525. // If IE and not an iframe
  2526. // continually check to see if the document is ready
  2527. if ( document.documentElement.doScroll && window == window.top ) (function(){
  2528. if ( jQuery.isReady ) return;
  2529. try {
  2530. // If IE is used, use the trick by Diego Perini
  2531. // http://javascript.nwbox.com/IEContentLoaded/
  2532. document.documentElement.doScroll("left");
  2533. } catch( error ) {
  2534. setTimeout( arguments.callee, 0 );
  2535. return;
  2536. }
  2537. // and execute any waiting functions
  2538. jQuery.ready();
  2539. })();
  2540. }
  2541. // A fallback to window.onload, that will always work
  2542. jQuery.event.add( window, "load", jQuery.ready );
  2543. }
  2544. jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
  2545. "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
  2546. "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
  2547. // Handle event binding
  2548. jQuery.fn[name] = function(fn){
  2549. return fn ? this.bind(name, fn) : this.trigger(name);
  2550. };
  2551. });
  2552. // Prevent memory leaks in IE
  2553. // And prevent errors on refresh with events like mouseover in other browsers
  2554. // Window isn't included so as not to unbind existing unload events
  2555. jQuery( window ).bind( 'unload', function(){
  2556. for ( var id in jQuery.cache )
  2557. // Skip the window
  2558. if ( id != 1 && jQuery.cache[ id ].handle )
  2559. jQuery.event.remove( jQuery.cache[ id ].handle.elem );
  2560. });
  2561. (function(){
  2562. jQuery.support = {};
  2563. var root = document.documentElement,
  2564. script = document.createElement("script"),
  2565. div = document.createElement("div"),
  2566. id = "script" + (new Date).getTime();
  2567. div.style.display = "none";
  2568. div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
  2569. var all = div.getElementsByTagName("*"),
  2570. a = div.getElementsByTagName("a")[0];
  2571. // Can't get basic test support
  2572. if ( !all || !all.length || !a ) {
  2573. return;
  2574. }
  2575. jQuery.support = {
  2576. // IE strips leading whitespace when .innerHTML is used
  2577. leadingWhitespace: div.firstChild.nodeType == 3,
  2578. // Make sure that tbody elements aren't automatically inserted
  2579. // IE will insert them into empty tables
  2580. tbody: !div.getElementsByTagName("tbody").length,
  2581. // Make sure that you can get all elements in an <object> element
  2582. // IE 7 always returns no results
  2583. objectAll: !!div.getElementsByTagName("object")[0]
  2584. .getElementsByTagName("*").length,
  2585. // Make sure that link elements get serialized correctly by innerHTML
  2586. // This requires a wrapper element in IE
  2587. htmlSerialize: !!div.getElementsByTagName("link").length,
  2588. // Get the style information from getAttribute
  2589. // (IE uses .cssText insted)
  2590. style: /red/.test( a.getAttribute("style") ),
  2591. // Make sure that URLs aren't manipulated
  2592. // (IE normalizes it by default)
  2593. hrefNormalized: a.getAttribute("href") === "/a",
  2594. // Make sure that element opacity exists
  2595. // (IE uses filter instead)
  2596. opacity: a.style.opacity === "0.5",
  2597. // Verify style float existence
  2598. // (IE uses styleFloat instead of cssFloat)
  2599. cssFloat: !!a.style.cssFloat,
  2600. // Will be defined later
  2601. scriptEval: false,
  2602. noCloneEvent: true,
  2603. boxModel: null
  2604. };
  2605. script.type = "text/javascript";
  2606. try {
  2607. script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
  2608. } catch(e){}
  2609. root.insertBefore( script, root.firstChild );
  2610. // Make sure that the execution of code works by injecting a script
  2611. // tag with appendChild/createTextNode
  2612. // (IE doesn't support this, fails, and uses .text instead)
  2613. if ( window[ id ] ) {
  2614. jQuery.support.scriptEval = true;
  2615. delete window[ id ];
  2616. }
  2617. root.removeChild( script );
  2618. if ( div.attachEvent && div.fireEvent ) {
  2619. div.attachEvent("onclick", function(){
  2620. // Cloning a node shouldn't copy over any
  2621. // bound event handlers (IE does this)
  2622. jQuery.support.noCloneEvent = false;
  2623. div.detachEvent("onclick", arguments.callee);
  2624. });
  2625. div.cloneNode(true).fireEvent("onclick");
  2626. }
  2627. // Figure out if the W3C box model works as expected
  2628. // document.body must exist before we can do this
  2629. jQuery(function(){
  2630. var div = document.createElement("div");
  2631. div.style.width = div.style.paddingLeft = "1px";
  2632. document.body.appendChild( div );
  2633. jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
  2634. document.body.removeChild( div ).style.display = 'none';
  2635. });
  2636. })();
  2637. var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
  2638. jQuery.props = {
  2639. "for": "htmlFor",
  2640. "class": "className",
  2641. "float": styleFloat,
  2642. cssFloat: styleFloat,
  2643. styleFloat: styleFloat,
  2644. readonly: "readOnly",
  2645. maxlength: "maxLength",
  2646. cellspacing: "cellSpacing",
  2647. rowspan: "rowSpan",
  2648. tabindex: "tabIndex"
  2649. };
  2650. jQuery.fn.extend({
  2651. // Keep a copy of the old load
  2652. _load: jQuery.fn.load,
  2653. load: function( url, params, callback ) {
  2654. if ( typeof url !== "string" )
  2655. return this._load( url );
  2656. var off = url.indexOf(" ");
  2657. if ( off >= 0 ) {
  2658. var selector = url.slice(off, url.length);
  2659. url = url.slice(0, off);
  2660. }
  2661. // Default to a GET request
  2662. var type = "GET";
  2663. // If the second parameter was provided
  2664. if ( params )
  2665. // If it's a function
  2666. if ( jQuery.isFunction( params ) ) {
  2667. // We assume that it's the callback
  2668. callback = params;
  2669. params = null;
  2670. // Otherwise, build a param string
  2671. } else if( typeof params === "object" ) {
  2672. params = jQuery.param( params );
  2673. type = "POST";
  2674. }
  2675. var self = this;
  2676. // Request the remote document
  2677. jQuery.ajax({
  2678. url: url,
  2679. type: type,
  2680. dataType: "html",
  2681. data: params,
  2682. complete: function(res, status){
  2683. // If successful, inject the HTML into all the matched elements
  2684. if ( status == "success" || status == "notmodified" )
  2685. // See if a selector was specified
  2686. self.html( selector ?
  2687. // Create a dummy div to hold the results
  2688. jQuery("<div/>")
  2689. // inject the contents of the document in, removing the scripts
  2690. // to avoid any 'Permission Denied' errors in IE
  2691. .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
  2692. // Locate the specified elements
  2693. .find(selector) :
  2694. // If not, just inject the full result
  2695. res.responseText );
  2696. if( callback )
  2697. self.each( callback, [res.responseText, status, res] );
  2698. }
  2699. });
  2700. return this;
  2701. },
  2702. serialize: function() {
  2703. return jQuery.param(this.serializeArray());
  2704. },
  2705. serializeArray: function() {
  2706. return this.map(function(){
  2707. return this.elements ? jQuery.makeArray(this.elements) : this;
  2708. })
  2709. .filter(function(){
  2710. return this.name && !this.disabled &&
  2711. (this.checked || /select|textarea/i.test(this.nodeName) ||
  2712. /text|hidden|password|search/i.test(this.type));
  2713. })
  2714. .map(function(i, elem){
  2715. var val = jQuery(this).val();
  2716. return val == null ? null :
  2717. jQuery.isArray(val) ?
  2718. jQuery.map( val, function(val, i){
  2719. return {name: elem.name, value: val};
  2720. }) :
  2721. {name: elem.name, value: val};
  2722. }).get();
  2723. }
  2724. });
  2725. // Attach a bunch of functions for handling common AJAX events
  2726. jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
  2727. jQuery.fn[o] = function(f){
  2728. return this.bind(o, f);
  2729. };
  2730. });
  2731. var jsc = now();
  2732. jQuery.extend({
  2733. get: function( url, data, callback, type ) {
  2734. // shift arguments if data argument was ommited
  2735. if ( jQuery.isFunction( data ) ) {
  2736. callback = data;
  2737. data = null;
  2738. }
  2739. return jQuery.ajax({
  2740. type: "GET",
  2741. url: url,
  2742. data: data,
  2743. success: callback,
  2744. dataType: type
  2745. });
  2746. },
  2747. getScript: function( url, callback ) {
  2748. return jQuery.get(url, null, callback, "script");
  2749. },
  2750. getJSON: function( url, data, callback ) {
  2751. return jQuery.get(url, data, callback, "json");
  2752. },
  2753. post: function( url, data, callback, type ) {
  2754. if ( jQuery.isFunction( data ) ) {
  2755. callback = data;
  2756. data = {};
  2757. }
  2758. return jQuery.ajax({
  2759. type: "POST",
  2760. url: url,
  2761. data: data,
  2762. success: callback,
  2763. dataType: type
  2764. });
  2765. },
  2766. ajaxSetup: function( settings ) {
  2767. jQuery.extend( jQuery.ajaxSettings, settings );
  2768. },
  2769. ajaxSettings: {
  2770. url: location.href,
  2771. global: true,
  2772. type: "GET",
  2773. contentType: "application/x-www-form-urlencoded",
  2774. processData: true,
  2775. async: true,
  2776. /*
  2777. timeout: 0,
  2778. data: null,
  2779. username: null,
  2780. password: null,
  2781. */
  2782. // Create the request object; Microsoft failed to properly
  2783. // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
  2784. // This function can be overriden by calling jQuery.ajaxSetup
  2785. xhr:function(){
  2786. return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  2787. },
  2788. accepts: {
  2789. xml: "application/xml, text/xml",
  2790. html: "text/html",
  2791. script: "text/javascript, application/javascript",
  2792. json: "application/json, text/javascript",
  2793. text: "text/plain",
  2794. _default: "*/*"
  2795. }
  2796. },
  2797. // Last-Modified header cache for next request
  2798. lastModified: {},
  2799. ajax: function( s ) {
  2800. // Extend the settings, but re-extend 's' so that it can be
  2801. // checked again later (in the test suite, specifically)
  2802. s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
  2803. var jsonp, jsre = /=\?(&|$)/g, status, data,
  2804. type = s.type.toUpperCase();
  2805. // convert data if not already a string
  2806. if ( s.data && s.processData && typeof s.data !== "string" )
  2807. s.data = jQuery.param(s.data);
  2808. // Handle JSONP Parameter Callbacks
  2809. if ( s.dataType == "jsonp" ) {
  2810. if ( type == "GET" ) {
  2811. if ( !s.url.match(jsre) )
  2812. s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
  2813. } else if ( !s.data || !s.data.match(jsre) )
  2814. s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
  2815. s.dataType = "json";
  2816. }
  2817. // Build temporary JSONP function
  2818. if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
  2819. jsonp = "jsonp" + jsc++;
  2820. // Replace the =? sequence both in the query string and the data
  2821. if ( s.data )
  2822. s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
  2823. s.url = s.url.replace(jsre, "=" + jsonp + "$1");
  2824. // We need to make sure
  2825. // that a JSONP style response is executed properly
  2826. s.dataType = "script";
  2827. // Handle JSONP-style loading
  2828. window[ jsonp ] = function(tmp){
  2829. data = tmp;
  2830. success();
  2831. complete();
  2832. // Garbage collect
  2833. window[ jsonp ] = undefined;
  2834. try{ delete window[ jsonp ]; } catch(e){}
  2835. if ( head )
  2836. head.removeChild( script );
  2837. };
  2838. }
  2839. if ( s.dataType == "script" && s.cache == null )
  2840. s.cache = false;
  2841. if ( s.cache === false && type == "GET" ) {
  2842. var ts = now();
  2843. // try replacing _= if it is there
  2844. var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
  2845. // if nothing was replaced, add timestamp to the end
  2846. s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
  2847. }
  2848. // If data is available, append data to url for get requests
  2849. if ( s.data && type == "GET" ) {
  2850. s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
  2851. // IE likes to send both get and post data, prevent this
  2852. s.data = null;
  2853. }
  2854. // Watch for a new set of requests
  2855. if ( s.global && ! jQuery.active++ )
  2856. jQuery.event.trigger( "ajaxStart" );
  2857. // Matches an absolute URL, and saves the domain
  2858. var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
  2859. // If we're requesting a remote document
  2860. // and trying to load JSON or Script with a GET
  2861. if ( s.dataType == "script" && type == "GET" && parts
  2862. && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
  2863. var head = document.getElementsByTagName("head")[0];
  2864. var script = document.createElement("script");
  2865. script.src = s.url;
  2866. if (s.scriptCharset)
  2867. script.charset = s.scriptCharset;
  2868. // Handle Script loading
  2869. if ( !jsonp ) {
  2870. var done = false;
  2871. // Attach handlers for all browsers
  2872. script.onload = script.onreadystatechange = function(){
  2873. if ( !done && (!this.readyState ||
  2874. this.readyState == "loaded" || this.readyState == "complete") ) {
  2875. done = true;
  2876. success();
  2877. complete();
  2878. // Handle memory leak in IE
  2879. script.onload = script.onreadystatechange = null;
  2880. head.removeChild( script );
  2881. }
  2882. };
  2883. }
  2884. head.appendChild(script);
  2885. // We handle everything using the script element injection
  2886. return undefined;
  2887. }
  2888. var requestDone = false;
  2889. // Create the request object
  2890. var xhr = s.xhr();
  2891. // Open the socket
  2892. // Passing null username, generates a login popup on Opera (#2865)
  2893. if( s.username )
  2894. xhr.open(type, s.url, s.async, s.username, s.password);
  2895. else
  2896. xhr.open(type, s.url, s.async);
  2897. // Need an extra try/catch for cross domain requests in Firefox 3
  2898. try {
  2899. // Set the correct header, if data is being sent
  2900. if ( s.data )
  2901. xhr.setRequestHeader("Content-Type", s.contentType);
  2902. // Set the If-Modified-Since header, if ifModified mode.
  2903. if ( s.ifModified )
  2904. xhr.setRequestHeader("If-Modified-Since",
  2905. jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
  2906. // Set header so the called script knows that it's an XMLHttpRequest
  2907. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  2908. // Set the Accepts header for the server, depending on the dataType
  2909. xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
  2910. s.accepts[ s.dataType ] + ", */*" :
  2911. s.accepts._default );
  2912. } catch(e){}
  2913. // Allow custom headers/mimetypes and early abort
  2914. if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
  2915. // Handle the global AJAX counter
  2916. if ( s.global && ! --jQuery.active )
  2917. jQuery.event.trigger( "ajaxStop" );
  2918. // close opended socket
  2919. xhr.abort();
  2920. return false;
  2921. }
  2922. if ( s.global )
  2923. jQuery.event.trigger("ajaxSend", [xhr, s]);
  2924. // Wait for a response to come back
  2925. var onreadystatechange = function(isTimeout){
  2926. // The request was aborted, clear the interval and decrement jQuery.active
  2927. if (xhr.readyState == 0) {
  2928. if (ival) {
  2929. // clear poll interval
  2930. clearInterval(ival);
  2931. ival = null;
  2932. // Handle the global AJAX counter
  2933. if ( s.global && ! --jQuery.active )
  2934. jQuery.event.trigger( "ajaxStop" );
  2935. }
  2936. // The transfer is complete and the data is available, or the request timed out
  2937. } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
  2938. requestDone = true;
  2939. // clear poll interval
  2940. if (ival) {
  2941. clearInterval(ival);
  2942. ival = null;
  2943. }
  2944. status = isTimeout == "timeout" ? "timeout" :
  2945. !jQuery.httpSuccess( xhr ) ? "error" :
  2946. s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
  2947. "success";
  2948. if ( status == "success" ) {
  2949. // Watch for, and catch, XML document parse errors
  2950. try {
  2951. // process the data (runs the xml through httpData regardless of callback)
  2952. data = jQuery.httpData( xhr, s.dataType, s );
  2953. } catch(e) {
  2954. status = "parsererror";
  2955. }
  2956. }
  2957. // Make sure that the request was successful or notmodified
  2958. if ( status == "success" ) {
  2959. // Cache Last-Modified header, if ifModified mode.
  2960. var modRes;
  2961. try {
  2962. modRes = xhr.getResponseHeader("Last-Modified");
  2963. } catch(e) {} // swallow exception thrown by FF if header is not available
  2964. if ( s.ifModified && modRes )
  2965. jQuery.lastModified[s.url] = modRes;
  2966. // JSONP handles its own success callback
  2967. if ( !jsonp )
  2968. success();
  2969. } else
  2970. jQuery.handleError(s, xhr, status);
  2971. // Fire the complete handlers
  2972. complete();
  2973. if ( isTimeout )
  2974. xhr.abort();
  2975. // Stop memory leaks
  2976. if ( s.async )
  2977. xhr = null;
  2978. }
  2979. };
  2980. if ( s.async ) {
  2981. // don't attach the handler to the request, just poll it instead
  2982. var ival = setInterval(onreadystatechange, 13);
  2983. // Timeout checker
  2984. if ( s.timeout > 0 )
  2985. setTimeout(function(){
  2986. // Check to see if the request is still happening
  2987. if ( xhr && !requestDone )
  2988. onreadystatechange( "timeout" );
  2989. }, s.timeout);
  2990. }
  2991. // Send the data
  2992. try {
  2993. xhr.send(s.data);
  2994. } catch(e) {
  2995. jQuery.handleError(s, xhr, null, e);
  2996. }
  2997. // firefox 1.5 doesn't fire statechange for sync requests
  2998. if ( !s.async )
  2999. onreadystatechange();
  3000. function success(){
  3001. // If a local callback was specified, fire it and pass it the data
  3002. if ( s.success )
  3003. s.success( data, status );
  3004. // Fire the global callback
  3005. if ( s.global )
  3006. jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
  3007. }
  3008. function complete(){
  3009. // Process result
  3010. if ( s.complete )
  3011. s.complete(xhr, status);
  3012. // The request was completed
  3013. if ( s.global )
  3014. jQuery.event.trigger( "ajaxComplete", [xhr, s] );
  3015. // Handle the global AJAX counter
  3016. if ( s.global && ! --jQuery.active )
  3017. jQuery.event.trigger( "ajaxStop" );
  3018. }
  3019. // return XMLHttpRequest to allow aborting the request etc.
  3020. return xhr;
  3021. },
  3022. handleError: function( s, xhr, status, e ) {
  3023. // If a local callback was specified, fire it
  3024. if ( s.error ) s.error( xhr, status, e );
  3025. // Fire the global callback
  3026. if ( s.global )
  3027. jQuery.event.trigger( "ajaxError", [xhr, s, e] );
  3028. },
  3029. // Counter for holding the number of active queries
  3030. active: 0,
  3031. // Determines if an XMLHttpRequest was successful or not
  3032. httpSuccess: function( xhr ) {
  3033. try {
  3034. // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
  3035. return !xhr.status && location.protocol == "file:" ||
  3036. ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
  3037. } catch(e){}
  3038. return false;
  3039. },
  3040. // Determines if an XMLHttpRequest returns NotModified
  3041. httpNotModified: function( xhr, url ) {
  3042. try {
  3043. var xhrRes = xhr.getResponseHeader("Last-Modified");
  3044. // Firefox always returns 200. check Last-Modified date
  3045. return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
  3046. } catch(e){}
  3047. return false;
  3048. },
  3049. httpData: function( xhr, type, s ) {
  3050. var ct = xhr.getResponseHeader("content-type"),
  3051. xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
  3052. data = xml ? xhr.responseXML : xhr.responseText;
  3053. if ( xml && data.documentElement.tagName == "parsererror" )
  3054. throw "parsererror";
  3055. // Allow a pre-filtering function to sanitize the response
  3056. // s != null is checked to keep backwards compatibility
  3057. if( s && s.dataFilter )
  3058. data = s.dataFilter( data, type );
  3059. // The filter can actually parse the response
  3060. if( typeof data === "string" ){
  3061. // If the type is "script", eval it in global context
  3062. if ( type == "script" )
  3063. jQuery.globalEval( data );
  3064. // Get the JavaScript object, if JSON is used.
  3065. if ( type == "json" )
  3066. data = window["eval"]("(" + data + ")");
  3067. }
  3068. return data;
  3069. },
  3070. // Serialize an array of form elements or a set of
  3071. // key/values into a query string
  3072. param: function( a ) {
  3073. var s = [ ];
  3074. function add( key, value ){
  3075. s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
  3076. };
  3077. // If an array was passed in, assume that it is an array
  3078. // of form elements
  3079. if ( jQuery.isArray(a) || a.jquery )
  3080. // Serialize the form elements
  3081. jQuery.each( a, function(){
  3082. add( this.name, this.value );
  3083. });
  3084. // Otherwise, assume that it's an object of key/value pairs
  3085. else
  3086. // Serialize the key/values
  3087. for ( var j in a )
  3088. // If the value is an array then the key names need to be repeated
  3089. if ( jQuery.isArray(a[j]) )
  3090. jQuery.each( a[j], function(){
  3091. add( j, this );
  3092. });
  3093. else
  3094. add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
  3095. // Return the resulting serialization
  3096. return s.join("&").replace(/%20/g, "+");
  3097. }
  3098. });
  3099. var elemdisplay = {},
  3100. timerId,
  3101. fxAttrs = [
  3102. // height animations
  3103. [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
  3104. // width animations
  3105. [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
  3106. // opacity animations
  3107. [ "opacity" ]
  3108. ];
  3109. function genFx( type, num ){
  3110. var obj = {};
  3111. jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
  3112. obj[ this ] = type;
  3113. });
  3114. return obj;
  3115. }
  3116. jQuery.fn.extend({
  3117. show: function(speed,callback){
  3118. if ( speed ) {
  3119. return this.animate( genFx("show", 3), speed, callback);
  3120. } else {
  3121. for ( var i = 0, l = this.length; i < l; i++ ){
  3122. var old = jQuery.data(this[i], "olddisplay");
  3123. this[i].style.display = old || "";
  3124. if ( jQuery.css(this[i], "display") === "none" ) {
  3125. var tagName = this[i].tagName, display;
  3126. if ( elemdisplay[ tagName ] ) {
  3127. display = elemdisplay[ tagName ];
  3128. } else {
  3129. var elem = jQuery("<" + tagName + " />").appendTo("body");
  3130. display = elem.css("display");
  3131. if ( display === "none" )
  3132. display = "block";
  3133. elem.remove();
  3134. elemdisplay[ tagName ] = display;
  3135. }
  3136. jQuery.data(this[i], "olddisplay", display);
  3137. }
  3138. }
  3139. // Set the display of the elements in a second loop
  3140. // to avoid the constant reflow
  3141. for ( var i = 0, l = this.length; i < l; i++ ){
  3142. this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
  3143. }
  3144. return this;
  3145. }
  3146. },
  3147. hide: function(speed,callback){
  3148. if ( speed ) {
  3149. return this.animate( genFx("hide", 3), speed, callback);
  3150. } else {
  3151. for ( var i = 0, l = this.length; i < l; i++ ){
  3152. var old = jQuery.data(this[i], "olddisplay");
  3153. if ( !old && old !== "none" )
  3154. jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
  3155. }
  3156. // Set the display of the elements in a second loop
  3157. // to avoid the constant reflow
  3158. for ( var i = 0, l = this.length; i < l; i++ ){
  3159. this[i].style.display = "none";
  3160. }
  3161. return this;
  3162. }
  3163. },
  3164. // Save the old toggle function
  3165. _toggle: jQuery.fn.toggle,
  3166. toggle: function( fn, fn2 ){
  3167. var bool = typeof fn === "boolean";
  3168. return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
  3169. this._toggle.apply( this, arguments ) :
  3170. fn == null || bool ?
  3171. this.each(function(){
  3172. var state = bool ? fn : jQuery(this).is(":hidden");
  3173. jQuery(this)[ state ? "show" : "hide" ]();
  3174. }) :
  3175. this.animate(genFx("toggle", 3), fn, fn2);
  3176. },
  3177. fadeTo: function(speed,to,callback){
  3178. return this.animate({opacity: to}, speed, callback);
  3179. },
  3180. animate: function( prop, speed, easing, callback ) {
  3181. var optall = jQuery.speed(speed, easing, callback);
  3182. return this[ optall.queue === false ? "each" : "queue" ](function(){
  3183. var opt = jQuery.extend({}, optall), p,
  3184. hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
  3185. self = this;
  3186. for ( p in prop ) {
  3187. if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
  3188. return opt.complete.call(this);
  3189. if ( ( p == "height" || p == "width" ) && this.style ) {
  3190. // Store display property
  3191. opt.display = jQuery.css(this, "display");
  3192. // Make sure that nothing sneaks out
  3193. opt.overflow = this.style.overflow;
  3194. }
  3195. }
  3196. if ( opt.overflow != null )
  3197. this.style.overflow = "hidden";
  3198. opt.curAnim = jQuery.extend({}, prop);
  3199. jQuery.each( prop, function(name, val){
  3200. var e = new jQuery.fx( self, opt, name );
  3201. if ( /toggle|show|hide/.test(val) )
  3202. e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
  3203. else {
  3204. var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
  3205. start = e.cur(true) || 0;
  3206. if ( parts ) {
  3207. var end = parseFloat(parts[2]),
  3208. unit = parts[3] || "px";
  3209. // We need to compute starting value
  3210. if ( unit != "px" ) {
  3211. self.style[ name ] = (end || 1) + unit;
  3212. start = ((end || 1) / e.cur(true)) * start;
  3213. self.style[ name ] = start + unit;
  3214. }
  3215. // If a +=/-= token was provided, we're doing a relative animation
  3216. if ( parts[1] )
  3217. end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
  3218. e.custom( start, end, unit );
  3219. } else
  3220. e.custom( start, val, "" );
  3221. }
  3222. });
  3223. // For JS strict compliance
  3224. return true;
  3225. });
  3226. },
  3227. stop: function(clearQueue, gotoEnd){
  3228. var timers = jQuery.timers;
  3229. if (clearQueue)
  3230. this.queue([]);
  3231. this.each(function(){
  3232. // go in reverse order so anything added to the queue during the loop is ignored
  3233. for ( var i = timers.length - 1; i >= 0; i-- )
  3234. if ( timers[i].elem == this ) {
  3235. if (gotoEnd)
  3236. // force the next step to be the last
  3237. timers[i](true);
  3238. timers.splice(i, 1);
  3239. }
  3240. });
  3241. // start the next in the queue if the last step wasn't forced
  3242. if (!gotoEnd)
  3243. this.dequeue();
  3244. return this;
  3245. }
  3246. });
  3247. // Generate shortcuts for custom animations
  3248. jQuery.each({
  3249. slideDown: genFx("show", 1),
  3250. slideUp: genFx("hide", 1),
  3251. slideToggle: genFx("toggle", 1),
  3252. fadeIn: { opacity: "show" },
  3253. fadeOut: { opacity: "hide" }
  3254. }, function( name, props ){
  3255. jQuery.fn[ name ] = function( speed, callback ){
  3256. return this.animate( props, speed, callback );
  3257. };
  3258. });
  3259. jQuery.extend({
  3260. speed: function(speed, easing, fn) {
  3261. var opt = typeof speed === "object" ? speed : {
  3262. complete: fn || !fn && easing ||
  3263. jQuery.isFunction( speed ) && speed,
  3264. duration: speed,
  3265. easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
  3266. };
  3267. opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
  3268. jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
  3269. // Queueing
  3270. opt.old = opt.complete;
  3271. opt.complete = function(){
  3272. if ( opt.queue !== false )
  3273. jQuery(this).dequeue();
  3274. if ( jQuery.isFunction( opt.old ) )
  3275. opt.old.call( this );
  3276. };
  3277. return opt;
  3278. },
  3279. easing: {
  3280. linear: function( p, n, firstNum, diff ) {
  3281. return firstNum + diff * p;
  3282. },
  3283. swing: function( p, n, firstNum, diff ) {
  3284. return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
  3285. }
  3286. },
  3287. timers: [],
  3288. fx: function( elem, options, prop ){
  3289. this.options = options;
  3290. this.elem = elem;
  3291. this.prop = prop;
  3292. if ( !options.orig )
  3293. options.orig = {};
  3294. }
  3295. });
  3296. jQuery.fx.prototype = {
  3297. // Simple function for setting a style value
  3298. update: function(){
  3299. if ( this.options.step )
  3300. this.options.step.call( this.elem, this.now, this );
  3301. (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
  3302. // Set display property to block for height/width animations
  3303. if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
  3304. this.elem.style.display = "block";
  3305. },
  3306. // Get the current size
  3307. cur: function(force){
  3308. if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
  3309. return this.elem[ this.prop ];
  3310. var r = parseFloat(jQuery.css(this.elem, this.prop, force));
  3311. return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
  3312. },
  3313. // Start an animation from one number to another
  3314. custom: function(from, to, unit){
  3315. this.startTime = now();
  3316. this.start = from;
  3317. this.end = to;
  3318. this.unit = unit || this.unit || "px";
  3319. this.now = this.start;
  3320. this.pos = this.state = 0;
  3321. var self = this;
  3322. function t(gotoEnd){
  3323. return self.step(gotoEnd);
  3324. }
  3325. t.elem = this.elem;
  3326. if ( t() && jQuery.timers.push(t) && !timerId ) {
  3327. timerId = setInterval(function(){
  3328. var timers = jQuery.timers;
  3329. for ( var i = 0; i < timers.length; i++ )
  3330. if ( !timers[i]() )
  3331. timers.splice(i--, 1);
  3332. if ( !timers.length ) {
  3333. clearInterval( timerId );
  3334. timerId = undefined;
  3335. }
  3336. }, 13);
  3337. }
  3338. },
  3339. // Simple 'show' function
  3340. show: function(){
  3341. // Remember where we started, so that we can go back to it later
  3342. this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
  3343. this.options.show = true;
  3344. // Begin the animation
  3345. // Make sure that we start at a small width/height to avoid any
  3346. // flash of content
  3347. this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());
  3348. // Start by showing the element
  3349. jQuery(this.elem).show();
  3350. },
  3351. // Simple 'hide' function
  3352. hide: function(){
  3353. // Remember where we started, so that we can go back to it later
  3354. this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
  3355. this.options.hide = true;
  3356. // Begin the animation
  3357. this.custom(this.cur(), 0);
  3358. },
  3359. // Each step of an animation
  3360. step: function(gotoEnd){
  3361. var t = now();
  3362. if ( gotoEnd || t >= this.options.duration + this.startTime ) {
  3363. this.now = this.end;
  3364. this.pos = this.state = 1;
  3365. this.update();
  3366. this.options.curAnim[ this.prop ] = true;
  3367. var done = true;
  3368. for ( var i in this.options.curAnim )
  3369. if ( this.options.curAnim[i] !== true )
  3370. done = false;
  3371. if ( done ) {
  3372. if ( this.options.display != null ) {
  3373. // Reset the overflow
  3374. this.elem.style.overflow = this.options.overflow;
  3375. // Reset the display
  3376. this.elem.style.display = this.options.display;
  3377. if ( jQuery.css(this.elem, "display") == "none" )
  3378. this.elem.style.display = "block";
  3379. }
  3380. // Hide the element if the "hide" operation was done
  3381. if ( this.options.hide )
  3382. jQuery(this.elem).hide();
  3383. // Reset the properties, if the item has been hidden or shown
  3384. if ( this.options.hide || this.options.show )
  3385. for ( var p in this.options.curAnim )
  3386. jQuery.attr(this.elem.style, p, this.options.orig[p]);
  3387. // Execute the complete function
  3388. this.options.complete.call( this.elem );
  3389. }
  3390. return false;
  3391. } else {
  3392. var n = t - this.startTime;
  3393. this.state = n / this.options.duration;
  3394. // Perform the easing function, defaults to swing
  3395. this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
  3396. this.now = this.start + ((this.end - this.start) * this.pos);
  3397. // Perform the next step of the animation
  3398. this.update();
  3399. }
  3400. return true;
  3401. }
  3402. };
  3403. jQuery.extend( jQuery.fx, {
  3404. speeds:{
  3405. slow: 600,
  3406. fast: 200,
  3407. // Default speed
  3408. _default: 400
  3409. },
  3410. step: {
  3411. opacity: function(fx){
  3412. jQuery.attr(fx.elem.style, "opacity", fx.now);
  3413. },
  3414. _default: function(fx){
  3415. if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
  3416. fx.elem.style[ fx.prop ] = fx.now + fx.unit;
  3417. else
  3418. fx.elem[ fx.prop ] = fx.now;
  3419. }
  3420. }
  3421. });
  3422. if ( document.documentElement["getBoundingClientRect"] )
  3423. jQuery.fn.offset = function() {
  3424. if ( !this[0] ) return { top: 0, left: 0 };
  3425. if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
  3426. var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
  3427. clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
  3428. top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
  3429. left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
  3430. return { top: top, left: left };
  3431. };
  3432. else
  3433. jQuery.fn.offset = function() {
  3434. if ( !this[0] ) return { top: 0, left: 0 };
  3435. if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
  3436. jQuery.offset.initialized || jQuery.offset.initialize();
  3437. var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
  3438. doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
  3439. body = doc.body, defaultView = doc.defaultView,
  3440. prevComputedStyle = defaultView.getComputedStyle(elem, null),
  3441. top = elem.offsetTop, left = elem.offsetLeft;
  3442. while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
  3443. computedStyle = defaultView.getComputedStyle(elem, null);
  3444. top -= elem.scrollTop, left -= elem.scrollLeft;
  3445. if ( elem === offsetParent ) {
  3446. top += elem.offsetTop, left += elem.offsetLeft;
  3447. if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
  3448. top += parseInt( computedStyle.borderTopWidth, 10) || 0,
  3449. left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
  3450. prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
  3451. }
  3452. if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
  3453. top += parseInt( computedStyle.borderTopWidth, 10) || 0,
  3454. left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
  3455. prevComputedStyle = computedStyle;
  3456. }
  3457. if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
  3458. top += body.offsetTop,
  3459. left += body.offsetLeft;
  3460. if ( prevComputedStyle.position === "fixed" )
  3461. top += Math.max(docElem.scrollTop, body.scrollTop),
  3462. left += Math.max(docElem.scrollLeft, body.scrollLeft);
  3463. return { top: top, left: left };
  3464. };
  3465. jQuery.offset = {
  3466. initialize: function() {
  3467. if ( this.initialized ) return;
  3468. var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
  3469. html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';
  3470. rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
  3471. for ( prop in rules ) container.style[prop] = rules[prop];
  3472. container.innerHTML = html;
  3473. body.insertBefore(container, body.firstChild);
  3474. innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
  3475. this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
  3476. this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
  3477. innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
  3478. this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
  3479. body.style.marginTop = '1px';
  3480. this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
  3481. body.style.marginTop = bodyMarginTop;
  3482. body.removeChild(container);
  3483. this.initialized = true;
  3484. },
  3485. bodyOffset: function(body) {
  3486. jQuery.offset.initialized || jQuery.offset.initialize();
  3487. var top = body.offsetTop, left = body.offsetLeft;
  3488. if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
  3489. top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0,
  3490. left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
  3491. return { top: top, left: left };
  3492. }
  3493. };
  3494. jQuery.fn.extend({
  3495. position: function() {
  3496. var left = 0, top = 0, results;
  3497. if ( this[0] ) {
  3498. // Get *real* offsetParent
  3499. var offsetParent = this.offsetParent(),
  3500. // Get correct offsets
  3501. offset = this.offset(),
  3502. parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
  3503. // Subtract element margins
  3504. // note: when an element has margin: auto the offsetLeft and marginLeft
  3505. // are the same in Safari causing offset.left to incorrectly be 0
  3506. offset.top -= num( this, 'marginTop' );
  3507. offset.left -= num( this, 'marginLeft' );
  3508. // Add offsetParent borders
  3509. parentOffset.top += num( offsetParent, 'borderTopWidth' );
  3510. parentOffset.left += num( offsetParent, 'borderLeftWidth' );
  3511. // Subtract the two offsets
  3512. results = {
  3513. top: offset.top - parentOffset.top,
  3514. left: offset.left - parentOffset.left
  3515. };
  3516. }
  3517. return results;
  3518. },
  3519. offsetParent: function() {
  3520. var offsetParent = this[0].offsetParent || document.body;
  3521. while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
  3522. offsetParent = offsetParent.offsetParent;
  3523. return jQuery(offsetParent);
  3524. }
  3525. });
  3526. // Create scrollLeft and scrollTop methods
  3527. jQuery.each( ['Left', 'Top'], function(i, name) {
  3528. var method = 'scroll' + name;
  3529. jQuery.fn[ method ] = function(val) {
  3530. if (!this[0]) return null;
  3531. return val !== undefined ?
  3532. // Set the scroll offset
  3533. this.each(function() {
  3534. this == window || this == document ?
  3535. window.scrollTo(
  3536. !i ? val : jQuery(window).scrollLeft(),
  3537. i ? val : jQuery(window).scrollTop()
  3538. ) :
  3539. this[ method ] = val;
  3540. }) :
  3541. // Return the scroll offset
  3542. this[0] == window || this[0] == document ?
  3543. self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
  3544. jQuery.boxModel && document.documentElement[ method ] ||
  3545. document.body[ method ] :
  3546. this[0][ method ];
  3547. };
  3548. });
  3549. // Create innerHeight, innerWidth, outerHeight and outerWidth methods
  3550. jQuery.each([ "Height", "Width" ], function(i, name){
  3551. var tl = i ? "Left" : "Top", // top or left
  3552. br = i ? "Right" : "Bottom", // bottom or right
  3553. lower = name.toLowerCase();
  3554. // innerHeight and innerWidth
  3555. jQuery.fn["inner" + name] = function(){
  3556. return this[0] ?
  3557. jQuery.css( this[0], lower, false, "padding" ) :
  3558. null;
  3559. };
  3560. // outerHeight and outerWidth
  3561. jQuery.fn["outer" + name] = function(margin) {
  3562. return this[0] ?
  3563. jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
  3564. null;
  3565. };
  3566. var type = name.toLowerCase();
  3567. jQuery.fn[ type ] = function( size ) {
  3568. // Get window width or height
  3569. return this[0] == window ?
  3570. // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
  3571. document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
  3572. document.body[ "client" + name ] :
  3573. // Get document width or height
  3574. this[0] == document ?
  3575. // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
  3576. Math.max(
  3577. document.documentElement["client" + name],
  3578. document.body["scroll" + name], document.documentElement["scroll" + name],
  3579. document.body["offset" + name], document.documentElement["offset" + name]
  3580. ) :
  3581. // Get or set width or height on the element
  3582. size === undefined ?
  3583. // Get width or height on the element
  3584. (this.length ? jQuery.css( this[0], type ) : null) :
  3585. // Set the width or height on the element (default to pixels if value is unitless)
  3586. this.css( type, typeof size === "string" ? size : size + "px" );
  3587. };
  3588. });
  3589. })();
  3590. /*
  3591. * jQuery UI 1.7
  3592. *
  3593. * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
  3594. * Dual licensed under the MIT (MIT-LICENSE.txt)
  3595. * and GPL (GPL-LICENSE.txt) licenses.
  3596. *
  3597. * http://docs.jquery.com/UI
  3598. */
  3599. ;jQuery.ui || (function($) {
  3600. var _remove = $.fn.remove,
  3601. isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);
  3602. //Helper functions and ui object
  3603. $.ui = {
  3604. version: "1.7",
  3605. // $.ui.plugin is deprecated. Use the proxy pattern instead.
  3606. plugin: {
  3607. add: function(module, option, set) {
  3608. var proto = $.ui[module].prototype;
  3609. for(var i in set) {
  3610. proto.plugins[i] = proto.plugins[i] || [];
  3611. proto.plugins[i].push([option, set[i]]);
  3612. }
  3613. },
  3614. call: function(instance, name, args) {
  3615. var set = instance.plugins[name];
  3616. if(!set || !instance.element[0].parentNode) { return; }
  3617. for (var i = 0; i < set.length; i++) {
  3618. if (instance.options[set[i][0]]) {
  3619. set[i][1].apply(instance.element, args);
  3620. }
  3621. }
  3622. }
  3623. },
  3624. contains: function(a, b) {
  3625. return document.compareDocumentPosition
  3626. ? a.compareDocumentPosition(b) & 16
  3627. : a !== b && a.contains(b);
  3628. },
  3629. hasScroll: function(el, a) {
  3630. //If overflow is hidden, the element might have extra content, but the user wants to hide it
  3631. if ($(el).css('overflow') == 'hidden') { return false; }
  3632. var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
  3633. has = false;
  3634. if (el[scroll] > 0) { return true; }
  3635. // TODO: determine which cases actually cause this to happen
  3636. // if the element doesn't have the scroll set, see if it's possible to
  3637. // set the scroll
  3638. el[scroll] = 1;
  3639. has = (el[scroll] > 0);
  3640. el[scroll] = 0;
  3641. return has;
  3642. },
  3643. isOverAxis: function(x, reference, size) {
  3644. //Determines when x coordinate is over "b" element axis
  3645. return (x > reference) && (x < (reference + size));
  3646. },
  3647. isOver: function(y, x, top, left, height, width) {
  3648. //Determines when x, y coordinates is over "b" element
  3649. return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
  3650. },
  3651. keyCode: {
  3652. BACKSPACE: 8,
  3653. CAPS_LOCK: 20,
  3654. COMMA: 188,
  3655. CONTROL: 17,
  3656. DELETE: 46,
  3657. DOWN: 40,
  3658. END: 35,
  3659. ENTER: 13,
  3660. ESCAPE: 27,
  3661. HOME: 36,
  3662. INSERT: 45,
  3663. LEFT: 37,
  3664. NUMPAD_ADD: 107,
  3665. NUMPAD_DECIMAL: 110,
  3666. NUMPAD_DIVIDE: 111,
  3667. NUMPAD_ENTER: 108,
  3668. NUMPAD_MULTIPLY: 106,
  3669. NUMPAD_SUBTRACT: 109,
  3670. PAGE_DOWN: 34,
  3671. PAGE_UP: 33,
  3672. PERIOD: 190,
  3673. RIGHT: 39,
  3674. SHIFT: 16,
  3675. SPACE: 32,
  3676. TAB: 9,
  3677. UP: 38
  3678. }
  3679. };
  3680. // WAI-ARIA normalization
  3681. if (isFF2) {
  3682. var attr = $.attr,
  3683. removeAttr = $.fn.removeAttr,
  3684. ariaNS = "http://www.w3.org/2005/07/aaa",
  3685. ariaState = /^aria-/,
  3686. ariaRole = /^wairole:/;
  3687. $.attr = function(elem, name, value) {
  3688. var set = value !== undefined;
  3689. return (name == 'role'
  3690. ? (set
  3691. ? attr.call(this, elem, name, "wairole:" + value)
  3692. : (attr.apply(this, arguments) || "").replace(ariaRole, ""))
  3693. : (ariaState.test(name)
  3694. ? (set
  3695. ? elem.setAttributeNS(ariaNS,
  3696. name.replace(ariaState, "aaa:"), value)
  3697. : attr.call(this, elem, name.replace(ariaState, "aaa:")))
  3698. : attr.apply(this, arguments)));
  3699. };
  3700. $.fn.removeAttr = function(name) {
  3701. return (ariaState.test(name)
  3702. ? this.each(function() {
  3703. this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
  3704. }) : removeAttr.call(this, name));
  3705. };
  3706. }
  3707. //jQuery plugins
  3708. $.fn.extend({
  3709. remove: function() {
  3710. // Safari has a native remove event which actually removes DOM elements,
  3711. // so we have to use triggerHandler instead of trigger (#3037).
  3712. $("*", this).add(this).each(function() {
  3713. $(this).triggerHandler("remove");
  3714. });
  3715. return _remove.apply(this, arguments );
  3716. },
  3717. enableSelection: function() {
  3718. return this
  3719. .attr('unselectable', 'off')
  3720. .css('MozUserSelect', '')
  3721. .unbind('selectstart.ui');
  3722. },
  3723. disableSelection: function() {
  3724. return this
  3725. .attr('unselectable', 'on')
  3726. .css('MozUserSelect', 'none')
  3727. .bind('selectstart.ui', function() { return false; });
  3728. },
  3729. scrollParent: function() {
  3730. var scrollParent;
  3731. if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
  3732. scrollParent = this.parents().filter(function() {
  3733. return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
  3734. }).eq(0);
  3735. } else {
  3736. scrollParent = this.parents().filter(function() {
  3737. return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
  3738. }).eq(0);
  3739. }
  3740. return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
  3741. }
  3742. });
  3743. //Additional selectors
  3744. $.extend($.expr[':'], {
  3745. data: function(elem, i, match) {
  3746. return !!$.data(elem, match[3]);
  3747. },
  3748. focusable: function(element) {
  3749. var nodeName = element.nodeName.toLowerCase(),
  3750. tabIndex = $.attr(element, 'tabindex');
  3751. return (/input|select|textarea|button|object/.test(nodeName)
  3752. ? !element.disabled
  3753. : 'a' == nodeName || 'area' == nodeName
  3754. ? element.href || !isNaN(tabIndex)
  3755. : !isNaN(tabIndex))
  3756. // the element and all of its ancestors must be visible
  3757. // the browser may report that the area is hidden
  3758. && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
  3759. },
  3760. tabbable: function(element) {
  3761. var tabIndex = $.attr(element, 'tabindex');
  3762. return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
  3763. }
  3764. });
  3765. // $.widget is a factory to create jQuery plugins
  3766. // taking some boilerplate code out of the plugin code
  3767. function getter(namespace, plugin, method, args) {
  3768. function getMethods(type) {
  3769. var methods = $[namespace][plugin][type] || [];
  3770. return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
  3771. }
  3772. var methods = getMethods('getter');
  3773. if (args.length == 1 && typeof args[0] == 'string') {
  3774. methods = methods.concat(getMethods('getterSetter'));
  3775. }
  3776. return ($.inArray(method, methods) != -1);
  3777. }
  3778. $.widget = function(name, prototype) {
  3779. var namespace = name.split(".")[0];
  3780. name = name.split(".")[1];
  3781. // create plugin method
  3782. $.fn[name] = function(options) {
  3783. var isMethodCall = (typeof options == 'string'),
  3784. args = Array.prototype.slice.call(arguments, 1);
  3785. // prevent calls to internal methods
  3786. if (isMethodCall && options.substring(0, 1) == '_') {
  3787. return this;
  3788. }
  3789. // handle getter methods
  3790. if (isMethodCall && getter(namespace, name, options, args)) {
  3791. var instance = $.data(this[0], name);
  3792. return (instance ? instance[options].apply(instance, args)
  3793. : undefined);
  3794. }
  3795. // handle initialization and non-getter methods
  3796. return this.each(function() {
  3797. var instance = $.data(this, name);
  3798. // constructor
  3799. (!instance && !isMethodCall &&
  3800. $.data(this, name, new $[namespace][name](this, options))._init());
  3801. // method call
  3802. (instance && isMethodCall && $.isFunction(instance[options]) &&
  3803. instance[options].apply(instance, args));
  3804. });
  3805. };
  3806. // create widget constructor
  3807. $[namespace] = $[namespace] || {};
  3808. $[namespace][name] = function(element, options) {
  3809. var self = this;
  3810. this.namespace = namespace;
  3811. this.widgetName = name;
  3812. this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
  3813. this.widgetBaseClass = namespace + '-' + name;
  3814. this.options = $.extend({},
  3815. $.widget.defaults,
  3816. $[namespace][name].defaults,
  3817. $.metadata && $.metadata.get(element)[name],
  3818. options);
  3819. this.element = $(element)
  3820. .bind('setData.' + name, function(event, key, value) {
  3821. if (event.target == element) {
  3822. return self._setData(key, value);
  3823. }
  3824. })
  3825. .bind('getData.' + name, function(event, key) {
  3826. if (event.target == element) {
  3827. return self._getData(key);
  3828. }
  3829. })
  3830. .bind('remove', function() {
  3831. return self.destroy();
  3832. });
  3833. };
  3834. // add widget prototype
  3835. $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
  3836. // TODO: merge getter and getterSetter properties from widget prototype
  3837. // and plugin prototype
  3838. $[namespace][name].getterSetter = 'option';
  3839. };
  3840. $.widget.prototype = {
  3841. _init: function() {},
  3842. destroy: function() {
  3843. this.element.removeData(this.widgetName)
  3844. .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
  3845. .removeAttr('aria-disabled');
  3846. },
  3847. option: function(key, value) {
  3848. var options = key,
  3849. self = this;
  3850. if (typeof key == "string") {
  3851. if (value === undefined) {
  3852. return this._getData(key);
  3853. }
  3854. options = {};
  3855. options[key] = value;
  3856. }
  3857. $.each(options, function(key, value) {
  3858. self._setData(key, value);
  3859. });
  3860. },
  3861. _getData: function(key) {
  3862. return this.options[key];
  3863. },
  3864. _setData: function(key, value) {
  3865. this.options[key] = value;
  3866. if (key == 'disabled') {
  3867. this.element
  3868. [value ? 'addClass' : 'removeClass'](
  3869. this.widgetBaseClass + '-disabled' + ' ' +
  3870. this.namespace + '-state-disabled')
  3871. .attr("aria-disabled", value);
  3872. }
  3873. },
  3874. enable: function() {
  3875. this._setData('disabled', false);
  3876. },
  3877. disable: function() {
  3878. this._setData('disabled', true);
  3879. },
  3880. _trigger: function(type, event, data) {
  3881. var callback = this.options[type],
  3882. eventName = (type == this.widgetEventPrefix
  3883. ? type : this.widgetEventPrefix + type);
  3884. event = $.Event(event);
  3885. event.type = eventName;
  3886. // copy original event properties over to the new event
  3887. // this would happen if we could call $.event.fix instead of $.Event
  3888. // but we don't have a way to force an event to be fixed multiple times
  3889. if (event.originalEvent) {
  3890. for (var i = $.event.props.length, prop; i;) {
  3891. prop = $.event.props[--i];
  3892. event[prop] = event.originalEvent[prop];
  3893. }
  3894. }
  3895. this.element.trigger(event, data);
  3896. return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
  3897. || event.isDefaultPrevented());
  3898. }
  3899. };
  3900. $.widget.defaults = {
  3901. disabled: false
  3902. };
  3903. /** Mouse Interaction Plugin **/
  3904. $.ui.mouse = {
  3905. _mouseInit: function() {
  3906. var self = this;
  3907. this.element
  3908. .bind('mousedown.'+this.widgetName, function(event) {
  3909. return self._mouseDown(event);
  3910. })
  3911. .bind('click.'+this.widgetName, function(event) {
  3912. if(self._preventClickEvent) {
  3913. self._preventClickEvent = false;
  3914. event.stopImmediatePropagation();
  3915. return false;
  3916. }
  3917. });
  3918. // Prevent text selection in IE
  3919. if ($.browser.msie) {
  3920. this._mouseUnselectable = this.element.attr('unselectable');
  3921. this.element.attr('unselectable', 'on');
  3922. }
  3923. this.started = false;
  3924. },
  3925. // TODO: make sure destroying one instance of mouse doesn't mess with
  3926. // other instances of mouse
  3927. _mouseDestroy: function() {
  3928. this.element.unbind('.'+this.widgetName);
  3929. // Restore text selection in IE
  3930. ($.browser.msie
  3931. && this.element.attr('unselectable', this._mouseUnselectable));
  3932. },
  3933. _mouseDown: function(event) {
  3934. // don't let more than one widget handle mouseStart
  3935. // TODO: figure out why we have to use originalEvent
  3936. event.originalEvent = event.originalEvent || {};
  3937. if (event.originalEvent.mouseHandled) { return; }
  3938. // we may have missed mouseup (out of window)
  3939. (this._mouseStarted && this._mouseUp(event));
  3940. this._mouseDownEvent = event;
  3941. var self = this,
  3942. btnIsLeft = (event.which == 1),
  3943. elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
  3944. if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
  3945. return true;
  3946. }
  3947. this.mouseDelayMet = !this.options.delay;
  3948. if (!this.mouseDelayMet) {
  3949. this._mouseDelayTimer = setTimeout(function() {
  3950. self.mouseDelayMet = true;
  3951. }, this.options.delay);
  3952. }
  3953. if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
  3954. this._mouseStarted = (this._mouseStart(event) !== false);
  3955. if (!this._mouseStarted) {
  3956. event.preventDefault();
  3957. return true;
  3958. }
  3959. }
  3960. // these delegates are required to keep context
  3961. this._mouseMoveDelegate = function(event) {
  3962. return self._mouseMove(event);
  3963. };
  3964. this._mouseUpDelegate = function(event) {
  3965. return self._mouseUp(event);
  3966. };
  3967. $(document)
  3968. .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
  3969. .bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
  3970. // preventDefault() is used to prevent the selection of text here -
  3971. // however, in Safari, this causes select boxes not to be selectable
  3972. // anymore, so this fix is needed
  3973. ($.browser.safari || event.preventDefault());
  3974. event.originalEvent.mouseHandled = true;
  3975. return true;
  3976. },
  3977. _mouseMove: function(event) {
  3978. // IE mouseup check - mouseup happened when mouse was out of window
  3979. if ($.browser.msie && !event.button) {
  3980. return this._mouseUp(event);
  3981. }
  3982. if (this._mouseStarted) {
  3983. this._mouseDrag(event);
  3984. return event.preventDefault();
  3985. }
  3986. if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
  3987. this._mouseStarted =
  3988. (this._mouseStart(this._mouseDownEvent, event) !== false);
  3989. (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
  3990. }
  3991. return !this._mouseStarted;
  3992. },
  3993. _mouseUp: function(event) {
  3994. $(document)
  3995. .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
  3996. .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
  3997. if (this._mouseStarted) {
  3998. this._mouseStarted = false;
  3999. this._preventClickEvent = (event.target == this._mouseDownEvent.target);
  4000. this._mouseStop(event);
  4001. }
  4002. return false;
  4003. },
  4004. _mouseDistanceMet: function(event) {
  4005. return (Math.max(
  4006. Math.abs(this._mouseDownEvent.pageX - event.pageX),
  4007. Math.abs(this._mouseDownEvent.pageY - event.pageY)
  4008. ) >= this.options.distance
  4009. );
  4010. },
  4011. _mouseDelayMet: function(event) {
  4012. return this.mouseDelayMet;
  4013. },
  4014. // These are placeholder methods, to be overriden by extending plugin
  4015. _mouseStart: function(event) {},
  4016. _mouseDrag: function(event) {},
  4017. _mouseStop: function(event) {},
  4018. _mouseCapture: function(event) { return true; }
  4019. };
  4020. $.ui.mouse.defaults = {
  4021. cancel: null,
  4022. distance: 1,
  4023. delay: 0
  4024. };
  4025. })(jQuery);
  4026. /* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
  4027. * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
  4028. * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
  4029. *
  4030. * $LastChangedDate: 2009-05-05 11:14:12 -0400 (Tue, 05 May 2009) $
  4031. * $Rev: 7137 $
  4032. *
  4033. * Version 2.1
  4034. */
  4035. (function($){
  4036. /**
  4037. * The bgiframe is chainable and applies the iframe hack to get
  4038. * around zIndex issues in IE6. It will only apply itself in IE
  4039. * and adds a class to the iframe called 'bgiframe'. The iframe
  4040. * is appeneded as the first child of the matched element(s)
  4041. * with a tabIndex and zIndex of -1.
  4042. *
  4043. * By default the plugin will take borders, sized with pixel units,
  4044. * into account. If a different unit is used for the border's width,
  4045. * then you will need to use the top and left settings as explained below.
  4046. *
  4047. * NOTICE: This plugin has been reported to cause perfromance problems
  4048. * when used on elements that change properties (like width, height and
  4049. * opacity) a lot in IE6. Most of these problems have been caused by
  4050. * the expressions used to calculate the elements width, height and
  4051. * borders. Some have reported it is due to the opacity filter. All
  4052. * these settings can be changed if needed as explained below.
  4053. *
  4054. * @example $('div').bgiframe();
  4055. * @before <div><p>Paragraph</p></div>
  4056. * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div>
  4057. *
  4058. * @param Map settings Optional settings to configure the iframe.
  4059. * @option String|Number top The iframe must be offset to the top
  4060. * by the width of the top border. This should be a negative
  4061. * number representing the border-top-width. If a number is
  4062. * is used here, pixels will be assumed. Otherwise, be sure
  4063. * to specify a unit. An expression could also be used.
  4064. * By default the value is "auto" which will use an expression
  4065. * to get the border-top-width if it is in pixels.
  4066. * @option String|Number left The iframe must be offset to the left
  4067. * by the width of the left border. This should be a negative
  4068. * number representing the border-left-width. If a number is
  4069. * is used here, pixels will be assumed. Otherwise, be sure
  4070. * to specify a unit. An expression could also be used.
  4071. * By default the value is "auto" which will use an expression
  4072. * to get the border-left-width if it is in pixels.
  4073. * @option String|Number width This is the width of the iframe. If
  4074. * a number is used here, pixels will be assume. Otherwise, be sure
  4075. * to specify a unit. An experssion could also be used.
  4076. * By default the value is "auto" which will use an experssion
  4077. * to get the offsetWidth.
  4078. * @option String|Number height This is the height of the iframe. If
  4079. * a number is used here, pixels will be assume. Otherwise, be sure
  4080. * to specify a unit. An experssion could also be used.
  4081. * By default the value is "auto" which will use an experssion
  4082. * to get the offsetHeight.
  4083. * @option Boolean opacity This is a boolean representing whether or not
  4084. * to use opacity. If set to true, the opacity of 0 is applied. If
  4085. * set to false, the opacity filter is not applied. Default: true.
  4086. * @option String src This setting is provided so that one could change
  4087. * the src of the iframe to whatever they need.
  4088. * Default: "javascript:false;"
  4089. *
  4090. * @name bgiframe
  4091. * @type jQuery
  4092. * @cat Plugins/bgiframe
  4093. * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
  4094. */
  4095. $.fn.bgIframe = $.fn.bgiframe = function(s) {
  4096. // This is only for IE6
  4097. if ( $.browser.msie && parseInt($.browser.version) <= 6 ) {
  4098. s = $.extend({
  4099. top : 'auto', // auto == .currentStyle.borderTopWidth
  4100. left : 'auto', // auto == .currentStyle.borderLeftWidth
  4101. width : 'auto', // auto == offsetWidth
  4102. height : 'auto', // auto == offsetHeight
  4103. opacity : true,
  4104. src : 'javascript:false;'
  4105. }, s || {});
  4106. var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
  4107. html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
  4108. 'style="display:block;position:absolute;z-index:-1;'+
  4109. (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
  4110. 'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
  4111. 'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
  4112. 'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
  4113. 'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
  4114. '"/>';
  4115. return this.each(function() {
  4116. if ( $('> iframe.bgiframe', this).length == 0 )
  4117. this.insertBefore( document.createElement(html), this.firstChild );
  4118. });
  4119. }
  4120. return this;
  4121. };
  4122. // Add browser.version if it doesn't exist
  4123. if (!$.browser.version)
  4124. $.browser.version = navigator.userAgent.toLowerCase().match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)[1];
  4125. })(jQuery);/*
  4126. * jQuery UI Dialog 1.7
  4127. *
  4128. * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
  4129. * Dual licensed under the MIT (MIT-LICENSE.txt)
  4130. * and GPL (GPL-LICENSE.txt) licenses.
  4131. *
  4132. * http://docs.jquery.com/UI/Dialog
  4133. *
  4134. * Depends:
  4135. * ui.core.js
  4136. * ui.draggable.js
  4137. * ui.resizable.js
  4138. */
  4139. (function($) {
  4140. var setDataSwitch = {
  4141. dragStart: "start.draggable",
  4142. drag: "drag.draggable",
  4143. dragStop: "stop.draggable",
  4144. maxHeight: "maxHeight.resizable",
  4145. minHeight: "minHeight.resizable",
  4146. maxWidth: "maxWidth.resizable",
  4147. minWidth: "minWidth.resizable",
  4148. resizeStart: "start.resizable",
  4149. resize: "drag.resizable",
  4150. resizeStop: "stop.resizable"
  4151. },
  4152. uiDialogClasses =
  4153. 'ui-dialog ' +
  4154. 'ui-widget ' +
  4155. 'ui-widget-content ' +
  4156. 'ui-corner-all ';
  4157. $.widget("ui.dialog", {
  4158. _init: function() {
  4159. this.originalTitle = this.element.attr('title');
  4160. var self = this,
  4161. options = this.options,
  4162. title = options.title || this.originalTitle || '&nbsp;',
  4163. titleId = $.ui.dialog.getTitleId(this.element),
  4164. uiDialog = (this.uiDialog = $('<div/>'))
  4165. .appendTo(document.body)
  4166. .hide()
  4167. .addClass(uiDialogClasses + options.dialogClass)
  4168. .css({
  4169. position: 'absolute',
  4170. overflow: 'hidden',
  4171. zIndex: options.zIndex
  4172. })
  4173. // setting tabIndex makes the div focusable
  4174. // setting outline to 0 prevents a border on focus in Mozilla
  4175. .attr('tabIndex', -1).css('outline', 0).keydown(function(event) {
  4176. (options.closeOnEscape && event.keyCode
  4177. && event.keyCode == $.ui.keyCode.ESCAPE && self.close(event));
  4178. })
  4179. .attr({
  4180. role: 'dialog',
  4181. 'aria-labelledby': titleId
  4182. })
  4183. .mousedown(function(event) {
  4184. self.moveToTop(false, event);
  4185. }),
  4186. uiDialogContent = this.element
  4187. .show()
  4188. .removeAttr('title')
  4189. .addClass(
  4190. 'ui-dialog-content ' +
  4191. 'ui-widget-content')
  4192. .appendTo(uiDialog),
  4193. uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>'))
  4194. .addClass(
  4195. 'ui-dialog-titlebar ' +
  4196. 'ui-widget-header ' +
  4197. 'ui-corner-all ' +
  4198. 'ui-helper-clearfix'
  4199. )
  4200. .prependTo(uiDialog),
  4201. uiDialogTitlebarClose = $('<a href="#"/>')
  4202. .addClass(
  4203. 'ui-dialog-titlebar-close ' +
  4204. 'ui-corner-all'
  4205. )
  4206. .attr('role', 'button')
  4207. .hover(
  4208. function() {
  4209. uiDialogTitlebarClose.addClass('ui-state-hover');
  4210. },
  4211. function() {
  4212. uiDialogTitlebarClose.removeClass('ui-state-hover');
  4213. }
  4214. )
  4215. .focus(function() {
  4216. uiDialogTitlebarClose.addClass('ui-state-focus');
  4217. })
  4218. .blur(function() {
  4219. uiDialogTitlebarClose.removeClass('ui-state-focus');
  4220. })
  4221. .mousedown(function(ev) {
  4222. ev.stopPropagation();
  4223. })
  4224. .click(function(event) {
  4225. self.close(event);
  4226. return false;
  4227. })
  4228. .appendTo(uiDialogTitlebar),
  4229. uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>'))
  4230. .addClass(
  4231. 'ui-icon ' +
  4232. 'ui-icon-closethick'
  4233. )
  4234. .text(options.closeText)
  4235. .appendTo(uiDialogTitlebarClose),
  4236. uiDialogTitle = $('<span/>')
  4237. .addClass('ui-dialog-title')
  4238. .attr('id', titleId)
  4239. .html(title)
  4240. .prependTo(uiDialogTitlebar);
  4241. uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection();
  4242. (options.draggable && $.fn.draggable && this._makeDraggable());
  4243. (options.resizable && $.fn.resizable && this._makeResizable());
  4244. this._createButtons(options.buttons);
  4245. this._isOpen = false;
  4246. (options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe());
  4247. (options.autoOpen && this.open());
  4248. },
  4249. destroy: function() {
  4250. (this.overlay && this.overlay.destroy());
  4251. this.uiDialog.hide();
  4252. this.element
  4253. .unbind('.dialog')
  4254. .removeData('dialog')
  4255. .removeClass('ui-dialog-content ui-widget-content')
  4256. .hide().appendTo('body');
  4257. this.uiDialog.remove();
  4258. (this.originalTitle && this.element.attr('title', this.originalTitle));
  4259. },
  4260. close: function(event) {
  4261. var self = this;
  4262. if (false === self._trigger('beforeclose', event)) {
  4263. return;
  4264. }
  4265. (self.overlay && self.overlay.destroy());
  4266. self.uiDialog.unbind('keypress.ui-dialog');
  4267. (self.options.hide
  4268. ? self.uiDialog.hide(self.options.hide, function() {
  4269. self._trigger('close', event);
  4270. })
  4271. : self.uiDialog.hide() && self._trigger('close', event));
  4272. $.ui.dialog.overlay.resize();
  4273. self._isOpen = false;
  4274. },
  4275. isOpen: function() {
  4276. return this._isOpen;
  4277. },
  4278. // the force parameter allows us to move modal dialogs to their correct
  4279. // position on open
  4280. moveToTop: function(force, event) {
  4281. if ((this.options.modal && !force)
  4282. || (!this.options.stack && !this.options.modal)) {
  4283. return this._trigger('focus', event);
  4284. }
  4285. if (this.options.zIndex > $.ui.dialog.maxZ) {
  4286. $.ui.dialog.maxZ = this.options.zIndex;
  4287. }
  4288. (this.overlay && this.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = ++$.ui.dialog.maxZ));
  4289. //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed.
  4290. // http://ui.jquery.com/bugs/ticket/3193
  4291. var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') };
  4292. this.uiDialog.css('z-index', ++$.ui.dialog.maxZ);
  4293. this.element.attr(saveScroll);
  4294. this._trigger('focus', event);
  4295. },
  4296. open: function() {
  4297. if (this._isOpen) { return; }
  4298. var options = this.options,
  4299. uiDialog = this.uiDialog;
  4300. this.overlay = options.modal ? new $.ui.dialog.overlay(this) : null;
  4301. (uiDialog.next().length && uiDialog.appendTo('body'));
  4302. this._size();
  4303. this._position(options.position);
  4304. uiDialog.show(options.show);
  4305. this.moveToTop(true);
  4306. // prevent tabbing out of modal dialogs
  4307. (options.modal && uiDialog.bind('keypress.ui-dialog', function(event) {
  4308. if (event.keyCode != $.ui.keyCode.TAB) {
  4309. return;
  4310. }
  4311. var tabbables = $(':tabbable', this),
  4312. first = tabbables.filter(':first')[0],
  4313. last = tabbables.filter(':last')[0];
  4314. if (event.target == last && !event.shiftKey) {
  4315. setTimeout(function() {
  4316. first.focus();
  4317. }, 1);
  4318. } else if (event.target == first && event.shiftKey) {
  4319. setTimeout(function() {
  4320. last.focus();
  4321. }, 1);
  4322. }
  4323. }));
  4324. // set focus to the first tabbable element in the content area or the first button
  4325. // if there are no tabbable elements, set focus on the dialog itself
  4326. $([])
  4327. .add(uiDialog.find('.ui-dialog-content :tabbable:first'))
  4328. .add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first'))
  4329. .add(uiDialog)
  4330. .filter(':first')
  4331. .focus();
  4332. this._trigger('open');
  4333. this._isOpen = true;
  4334. },
  4335. _createButtons: function(buttons) {
  4336. var self = this,
  4337. hasButtons = false,
  4338. uiDialogButtonPane = $('<div></div>')
  4339. .addClass(
  4340. 'ui-dialog-buttonpane ' +
  4341. 'ui-widget-content ' +
  4342. 'ui-helper-clearfix'
  4343. );
  4344. // if we already have a button pane, remove it
  4345. this.uiDialog.find('.ui-dialog-buttonpane').remove();
  4346. (typeof buttons == 'object' && buttons !== null &&
  4347. $.each(buttons, function() { return !(hasButtons = true); }));
  4348. if (hasButtons) {
  4349. $.each(buttons, function(name, fn) {
  4350. $('<button type="button"></button>')
  4351. .addClass(
  4352. 'ui-state-default ' +
  4353. 'ui-corner-all'
  4354. )
  4355. .text(name)
  4356. .click(function() { fn.apply(self.element[0], arguments); })
  4357. .hover(
  4358. function() {
  4359. $(this).addClass('ui-state-hover');
  4360. },
  4361. function() {
  4362. $(this).removeClass('ui-state-hover');
  4363. }
  4364. )
  4365. .focus(function() {
  4366. $(this).addClass('ui-state-focus');
  4367. })
  4368. .blur(function() {
  4369. $(this).removeClass('ui-state-focus');
  4370. })
  4371. .appendTo(uiDialogButtonPane);
  4372. });
  4373. uiDialogButtonPane.appendTo(this.uiDialog);
  4374. }
  4375. },
  4376. _makeDraggable: function() {
  4377. var self = this,
  4378. options = this.options,
  4379. heightBeforeDrag;
  4380. this.uiDialog.draggable({
  4381. cancel: '.ui-dialog-content',
  4382. handle: '.ui-dialog-titlebar',
  4383. containment: 'document',
  4384. start: function() {
  4385. heightBeforeDrag = options.height;
  4386. $(this).height($(this).height()).addClass("ui-dialog-dragging");
  4387. (options.dragStart && options.dragStart.apply(self.element[0], arguments));
  4388. },
  4389. drag: function() {
  4390. (options.drag && options.drag.apply(self.element[0], arguments));
  4391. },
  4392. stop: function() {
  4393. $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag);
  4394. (options.dragStop && options.dragStop.apply(self.element[0], arguments));
  4395. $.ui.dialog.overlay.resize();
  4396. }
  4397. });
  4398. },
  4399. _makeResizable: function(handles) {
  4400. handles = (handles === undefined ? this.options.resizable : handles);
  4401. var self = this,
  4402. options = this.options,
  4403. resizeHandles = typeof handles == 'string'
  4404. ? handles
  4405. : 'n,e,s,w,se,sw,ne,nw';
  4406. this.uiDialog.resizable({
  4407. cancel: '.ui-dialog-content',
  4408. alsoResize: this.element,
  4409. maxWidth: options.maxWidth,
  4410. maxHeight: options.maxHeight,
  4411. minWidth: options.minWidth,
  4412. minHeight: options.minHeight,
  4413. start: function() {
  4414. $(this).addClass("ui-dialog-resizing");
  4415. (options.resizeStart && options.resizeStart.apply(self.element[0], arguments));
  4416. },
  4417. resize: function() {
  4418. (options.resize && options.resize.apply(self.element[0], arguments));
  4419. },
  4420. handles: resizeHandles,
  4421. stop: function() {
  4422. $(this).removeClass("ui-dialog-resizing");
  4423. options.height = $(this).height();
  4424. options.width = $(this).width();
  4425. (options.resizeStop && options.resizeStop.apply(self.element[0], arguments));
  4426. $.ui.dialog.overlay.resize();
  4427. }
  4428. })
  4429. .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se');
  4430. },
  4431. _position: function(pos) {
  4432. var wnd = $(window), doc = $(document),
  4433. pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
  4434. minTop = pTop;
  4435. if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) {
  4436. pos = [
  4437. pos == 'right' || pos == 'left' ? pos : 'center',
  4438. pos == 'top' || pos == 'bottom' ? pos : 'middle'
  4439. ];
  4440. }
  4441. if (pos.constructor != Array) {
  4442. pos = ['center', 'middle'];
  4443. }
  4444. if (pos[0].constructor == Number) {
  4445. pLeft += pos[0];
  4446. } else {
  4447. switch (pos[0]) {
  4448. case 'left':
  4449. pLeft += 0;
  4450. break;
  4451. case 'right':
  4452. pLeft += wnd.width() - this.uiDialog.outerWidth();
  4453. break;
  4454. default:
  4455. case 'center':
  4456. pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2;
  4457. }
  4458. }
  4459. if (pos[1].constructor == Number) {
  4460. pTop += pos[1];
  4461. } else {
  4462. switch (pos[1]) {
  4463. case 'top':
  4464. pTop += 0;
  4465. break;
  4466. case 'bottom':
  4467. pTop += wnd.height() - this.uiDialog.outerHeight();
  4468. break;
  4469. default:
  4470. case 'middle':
  4471. pTop += (wnd.height() - this.uiDialog.outerHeight()) / 2;
  4472. }
  4473. }
  4474. // prevent the dialog from being too high (make sure the titlebar
  4475. // is accessible)
  4476. pTop = Math.max(pTop, minTop);
  4477. this.uiDialog.css({top: pTop, left: pLeft});
  4478. },
  4479. _setData: function(key, value){
  4480. (setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value));
  4481. switch (key) {
  4482. case "buttons":
  4483. this._createButtons(value);
  4484. break;
  4485. case "closeText":
  4486. this.uiDialogTitlebarCloseText.text(value);
  4487. break;
  4488. case "dialogClass":
  4489. this.uiDialog
  4490. .removeClass(this.options.dialogClass)
  4491. .addClass(uiDialogClasses + value);
  4492. break;
  4493. case "draggable":
  4494. (value
  4495. ? this._makeDraggable()
  4496. : this.uiDialog.draggable('destroy'));
  4497. break;
  4498. case "height":
  4499. this.uiDialog.height(value);
  4500. break;
  4501. case "position":
  4502. this._position(value);
  4503. break;
  4504. case "resizable":
  4505. var uiDialog = this.uiDialog,
  4506. isResizable = this.uiDialog.is(':data(resizable)');
  4507. // currently resizable, becoming non-resizable
  4508. (isResizable && !value && uiDialog.resizable('destroy'));
  4509. // currently resizable, changing handles
  4510. (isResizable && typeof value == 'string' &&
  4511. uiDialog.resizable('option', 'handles', value));
  4512. // currently non-resizable, becoming resizable
  4513. (isResizable || this._makeResizable(value));
  4514. break;
  4515. case "title":
  4516. $(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;');
  4517. break;
  4518. case "width":
  4519. this.uiDialog.width(value);
  4520. break;
  4521. }
  4522. $.widget.prototype._setData.apply(this, arguments);
  4523. },
  4524. _size: function() {
  4525. /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
  4526. * divs will both have width and height set, so we need to reset them
  4527. */
  4528. var options = this.options;
  4529. // reset content sizing
  4530. this.element.css({
  4531. height: 0,
  4532. minHeight: 0,
  4533. width: 'auto'
  4534. });
  4535. // reset wrapper sizing
  4536. // determine the height of all the non-content elements
  4537. var nonContentHeight = this.uiDialog.css({
  4538. height: 'auto',
  4539. width: options.width
  4540. })
  4541. .height();
  4542. this.element
  4543. .css({
  4544. minHeight: Math.max(options.minHeight - nonContentHeight, 0),
  4545. height: options.height == 'auto'
  4546. ? 'auto'
  4547. : Math.max(options.height - nonContentHeight, 0)
  4548. });
  4549. }
  4550. });
  4551. $.extend($.ui.dialog, {
  4552. version: "1.7",
  4553. defaults: {
  4554. autoOpen: true,
  4555. bgiframe: false,
  4556. buttons: {},
  4557. closeOnEscape: true,
  4558. closeText: 'close',
  4559. dialogClass: '',
  4560. draggable: true,
  4561. hide: null,
  4562. height: 'auto',
  4563. maxHeight: false,
  4564. maxWidth: false,
  4565. minHeight: 150,
  4566. minWidth: 150,
  4567. modal: false,
  4568. position: 'center',
  4569. resizable: true,
  4570. show: null,
  4571. stack: true,
  4572. title: '',
  4573. width: 300,
  4574. zIndex: 1000
  4575. },
  4576. getter: 'isOpen',
  4577. uuid: 0,
  4578. maxZ: 0,
  4579. getTitleId: function($el) {
  4580. return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid);
  4581. },
  4582. overlay: function(dialog) {
  4583. this.$el = $.ui.dialog.overlay.create(dialog);
  4584. }
  4585. });
  4586. $.extend($.ui.dialog.overlay, {
  4587. instances: [],
  4588. maxZ: 0,
  4589. events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','),
  4590. function(event) { return event + '.dialog-overlay'; }).join(' '),
  4591. create: function(dialog) {
  4592. if (this.instances.length === 0) {
  4593. // prevent use of anchors and inputs
  4594. // we use a setTimeout in case the overlay is created from an
  4595. // event that we're going to be cancelling (see #2804)
  4596. setTimeout(function() {
  4597. $(document).bind($.ui.dialog.overlay.events, function(event) {
  4598. var dialogZ = $(event.target).parents('.ui-dialog').css('zIndex') || 0;
  4599. return (dialogZ > $.ui.dialog.overlay.maxZ);
  4600. });
  4601. }, 1);
  4602. // allow closing by pressing the escape key
  4603. $(document).bind('keydown.dialog-overlay', function(event) {
  4604. (dialog.options.closeOnEscape && event.keyCode
  4605. && event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
  4606. });
  4607. // handle window resize
  4608. $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
  4609. }
  4610. var $el = $('<div></div>').appendTo(document.body)
  4611. .addClass('ui-widget-overlay').css({
  4612. width: this.width(),
  4613. height: this.height()
  4614. });
  4615. (dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe());
  4616. this.instances.push($el);
  4617. return $el;
  4618. },
  4619. destroy: function($el) {
  4620. this.instances.splice($.inArray(this.instances, $el), 1);
  4621. if (this.instances.length === 0) {
  4622. $([document, window]).unbind('.dialog-overlay');
  4623. }
  4624. $el.remove();
  4625. },
  4626. height: function() {
  4627. // handle IE 6
  4628. if ($.browser.msie && $.browser.version < 7) {
  4629. var scrollHeight = Math.max(
  4630. document.documentElement.scrollHeight,
  4631. document.body.scrollHeight
  4632. );
  4633. var offsetHeight = Math.max(
  4634. document.documentElement.offsetHeight,
  4635. document.body.offsetHeight
  4636. );
  4637. if (scrollHeight < offsetHeight) {
  4638. return $(window).height() + 'px';
  4639. } else {
  4640. return scrollHeight + 'px';
  4641. }
  4642. // handle "good" browsers
  4643. } else {
  4644. return $(document).height() + 'px';
  4645. }
  4646. },
  4647. width: function() {
  4648. // handle IE 6
  4649. if ($.browser.msie && $.browser.version < 7) {
  4650. var scrollWidth = Math.max(
  4651. document.documentElement.scrollWidth,
  4652. document.body.scrollWidth
  4653. );
  4654. var offsetWidth = Math.max(
  4655. document.documentElement.offsetWidth,
  4656. document.body.offsetWidth
  4657. );
  4658. if (scrollWidth < offsetWidth) {
  4659. return $(window).width() + 'px';
  4660. } else {
  4661. return scrollWidth + 'px';
  4662. }
  4663. // handle "good" browsers
  4664. } else {
  4665. return $(document).width() + 'px';
  4666. }
  4667. },
  4668. resize: function() {
  4669. /* If the dialog is draggable and the user drags it past the
  4670. * right edge of the window, the document becomes wider so we
  4671. * need to stretch the overlay. If the user then drags the
  4672. * dialog back to the left, the document will become narrower,
  4673. * so we need to shrink the overlay to the appropriate size.
  4674. * This is handled by shrinking the overlay before setting it
  4675. * to the full document size.
  4676. */
  4677. var $overlays = $([]);
  4678. $.each($.ui.dialog.overlay.instances, function() {
  4679. $overlays = $overlays.add(this);
  4680. });
  4681. $overlays.css({
  4682. width: 0,
  4683. height: 0
  4684. }).css({
  4685. width: $.ui.dialog.overlay.width(),
  4686. height: $.ui.dialog.overlay.height()
  4687. });
  4688. }
  4689. });
  4690. $.extend($.ui.dialog.overlay.prototype, {
  4691. destroy: function() {
  4692. $.ui.dialog.overlay.destroy(this.$el);
  4693. }
  4694. });
  4695. })(jQuery);
  4696. /*
  4697. * jQuery UI Draggable 1.7
  4698. *
  4699. * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
  4700. * Dual licensed under the MIT (MIT-LICENSE.txt)
  4701. * and GPL (GPL-LICENSE.txt) licenses.
  4702. *
  4703. * http://docs.jquery.com/UI/Draggables
  4704. *
  4705. * Depends:
  4706. * ui.core.js
  4707. */
  4708. (function($) {
  4709. $.widget("ui.draggable", $.extend({}, $.ui.mouse, {
  4710. _init: function() {
  4711. if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
  4712. this.element[0].style.position = 'relative';
  4713. (this.options.addClasses && this.element.addClass("ui-draggable"));
  4714. (this.options.disabled && this.element.addClass("ui-draggable-disabled"));
  4715. this._mouseInit();
  4716. },
  4717. destroy: function() {
  4718. if(!this.element.data('draggable')) return;
  4719. this.element
  4720. .removeData("draggable")
  4721. .unbind(".draggable")
  4722. .removeClass("ui-draggable"
  4723. + " ui-draggable-dragging"
  4724. + " ui-draggable-disabled");
  4725. this._mouseDestroy();
  4726. },
  4727. _mouseCapture: function(event) {
  4728. var o = this.options;
  4729. if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
  4730. return false;
  4731. //Quit if we're not on a valid handle
  4732. this.handle = this._getHandle(event);
  4733. if (!this.handle)
  4734. return false;
  4735. return true;
  4736. },
  4737. _mouseStart: function(event) {
  4738. var o = this.options;
  4739. //Create and append the visible helper
  4740. this.helper = this._createHelper(event);
  4741. //Cache the helper size
  4742. this._cacheHelperProportions();
  4743. //If ddmanager is used for droppables, set the global draggable
  4744. if($.ui.ddmanager)
  4745. $.ui.ddmanager.current = this;
  4746. /*
  4747. * - Position generation -
  4748. * This block generates everything position related - it's the core of draggables.
  4749. */
  4750. //Cache the margins of the original element
  4751. this._cacheMargins();
  4752. //Store the helper's css position
  4753. this.cssPosition = this.helper.css("position");
  4754. this.scrollParent = this.helper.scrollParent();
  4755. //The element's absolute position on the page minus margins
  4756. this.offset = this.element.offset();
  4757. this.offset = {
  4758. top: this.offset.top - this.margins.top,
  4759. left: this.offset.left - this.margins.left
  4760. };
  4761. $.extend(this.offset, {
  4762. click: { //Where the click happened, relative to the element
  4763. left: event.pageX - this.offset.left,
  4764. top: event.pageY - this.offset.top
  4765. },
  4766. parent: this._getParentOffset(),
  4767. relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
  4768. });
  4769. //Generate the original position
  4770. this.originalPosition = this._generatePosition(event);
  4771. this.originalPageX = event.pageX;
  4772. this.originalPageY = event.pageY;
  4773. //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
  4774. if(o.cursorAt)
  4775. this._adjustOffsetFromHelper(o.cursorAt);
  4776. //Set a containment if given in the options
  4777. if(o.containment)
  4778. this._setContainment();
  4779. //Call plugins and callbacks
  4780. this._trigger("start", event);
  4781. //Recache the helper size
  4782. this._cacheHelperProportions();
  4783. //Prepare the droppable offsets
  4784. if ($.ui.ddmanager && !o.dropBehaviour)
  4785. $.ui.ddmanager.prepareOffsets(this, event);
  4786. this.helper.addClass("ui-draggable-dragging");
  4787. this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
  4788. return true;
  4789. },
  4790. _mouseDrag: function(event, noPropagation) {
  4791. //Compute the helpers position
  4792. this.position = this._generatePosition(event);
  4793. this.positionAbs = this._convertPositionTo("absolute");
  4794. //Call plugins and callbacks and use the resulting position if something is returned
  4795. if (!noPropagation) {
  4796. var ui = this._uiHash();
  4797. this._trigger('drag', event, ui);
  4798. this.position = ui.position;
  4799. }
  4800. if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
  4801. if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
  4802. if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
  4803. return false;
  4804. },
  4805. _mouseStop: function(event) {
  4806. //If we are using droppables, inform the manager about the drop
  4807. var dropped = false;
  4808. if ($.ui.ddmanager && !this.options.dropBehaviour)
  4809. dropped = $.ui.ddmanager.drop(this, event);
  4810. //if a drop comes from outside (a sortable)
  4811. if(this.dropped) {
  4812. dropped = this.dropped;
  4813. this.dropped = false;
  4814. }
  4815. 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))) {
  4816. var self = this;
  4817. $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
  4818. self._trigger("stop", event);
  4819. self._clear();
  4820. });
  4821. } else {
  4822. this._trigger("stop", event);
  4823. this._clear();
  4824. }
  4825. return false;
  4826. },
  4827. _getHandle: function(event) {
  4828. var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
  4829. $(this.options.handle, this.element)
  4830. .find("*")
  4831. .andSelf()
  4832. .each(function() {
  4833. if(this == event.target) handle = true;
  4834. });
  4835. return handle;
  4836. },
  4837. _createHelper: function(event) {
  4838. var o = this.options;
  4839. var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);
  4840. if(!helper.parents('body').length)
  4841. helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
  4842. if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
  4843. helper.css("position", "absolute");
  4844. return helper;
  4845. },
  4846. _adjustOffsetFromHelper: function(obj) {
  4847. if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
  4848. if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
  4849. if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
  4850. if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
  4851. },
  4852. _getParentOffset: function() {
  4853. //Get the offsetParent and cache its position
  4854. this.offsetParent = this.helper.offsetParent();
  4855. var po = this.offsetParent.offset();
  4856. // This is a special case where we need to modify a offset calculated on start, since the following happened:
  4857. // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
  4858. // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
  4859. // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
  4860. if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
  4861. po.left += this.scrollParent.scrollLeft();
  4862. po.top += this.scrollParent.scrollTop();
  4863. }
  4864. if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
  4865. || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
  4866. po = { top: 0, left: 0 };
  4867. return {
  4868. top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
  4869. left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
  4870. };
  4871. },
  4872. _getRelativeOffset: function() {
  4873. if(this.cssPosition == "relative") {
  4874. var p = this.element.position();
  4875. return {
  4876. top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
  4877. left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
  4878. };
  4879. } else {
  4880. return { top: 0, left: 0 };
  4881. }
  4882. },
  4883. _cacheMargins: function() {
  4884. this.margins = {
  4885. left: (parseInt(this.element.css("marginLeft"),10) || 0),
  4886. top: (parseInt(this.element.css("marginTop"),10) || 0)
  4887. };
  4888. },
  4889. _cacheHelperProportions: function() {
  4890. this.helperProportions = {
  4891. width: this.helper.outerWidth(),
  4892. height: this.helper.outerHeight()
  4893. };
  4894. },
  4895. _setContainment: function() {
  4896. var o = this.options;
  4897. if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
  4898. if(o.containment == 'document' || o.containment == 'window') this.containment = [
  4899. 0 - this.offset.relative.left - this.offset.parent.left,
  4900. 0 - this.offset.relative.top - this.offset.parent.top,
  4901. $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
  4902. ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
  4903. ];
  4904. if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
  4905. var ce = $(o.containment)[0]; if(!ce) return;
  4906. var co = $(o.containment).offset();
  4907. var over = ($(ce).css("overflow") != 'hidden');
  4908. this.containment = [
  4909. co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
  4910. co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
  4911. 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,
  4912. 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
  4913. ];
  4914. } else if(o.containment.constructor == Array) {
  4915. this.containment = o.containment;
  4916. }
  4917. },
  4918. _convertPositionTo: function(d, pos) {
  4919. if(!pos) pos = this.position;
  4920. var mod = d == "absolute" ? 1 : -1;
  4921. var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
  4922. return {
  4923. top: (
  4924. pos.top // The absolute mouse position
  4925. + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent
  4926. + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border)
  4927. - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
  4928. ),
  4929. left: (
  4930. pos.left // The absolute mouse position
  4931. + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent
  4932. + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border)
  4933. - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
  4934. )
  4935. };
  4936. },
  4937. _generatePosition: function(event) {
  4938. var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
  4939. // This is another very weird special case that only happens for relative elements:
  4940. // 1. If the css position is relative
  4941. // 2. and the scroll parent is the document or similar to the offset parent
  4942. // we have to refresh the relative offset during the scroll so there are no jumps
  4943. if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
  4944. this.offset.relative = this._getRelativeOffset();
  4945. }
  4946. var pageX = event.pageX;
  4947. var pageY = event.pageY;
  4948. /*
  4949. * - Position constraining -
  4950. * Constrain the position to a mix of grid, containment.
  4951. */
  4952. if(this.originalPosition) { //If we are not dragging yet, we won't check for options
  4953. if(this.containment) {
  4954. if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
  4955. if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
  4956. if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
  4957. if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
  4958. }
  4959. if(o.grid) {
  4960. var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
  4961. 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;
  4962. var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
  4963. 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;
  4964. }
  4965. }
  4966. return {
  4967. top: (
  4968. pageY // The absolute mouse position
  4969. - this.offset.click.top // Click offset (relative to the element)
  4970. - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent
  4971. - this.offset.parent.top // The offsetParent's offset without borders (offset + border)
  4972. + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
  4973. ),
  4974. left: (
  4975. pageX // The absolute mouse position
  4976. - this.offset.click.left // Click offset (relative to the element)
  4977. - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent
  4978. - this.offset.parent.left // The offsetParent's offset without borders (offset + border)
  4979. + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
  4980. )
  4981. };
  4982. },
  4983. _clear: function() {
  4984. this.helper.removeClass("ui-draggable-dragging");
  4985. if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
  4986. //if($.ui.ddmanager) $.ui.ddmanager.current = null;
  4987. this.helper = null;
  4988. this.cancelHelperRemoval = false;
  4989. },
  4990. // From now on bulk stuff - mainly helpers
  4991. _trigger: function(type, event, ui) {
  4992. ui = ui || this._uiHash();
  4993. $.ui.plugin.call(this, type, [event, ui]);
  4994. if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
  4995. return $.widget.prototype._trigger.call(this, type, event, ui);
  4996. },
  4997. plugins: {},
  4998. _uiHash: function(event) {
  4999. return {
  5000. helper: this.helper,
  5001. position: this.position,
  5002. absolutePosition: this.positionAbs, //deprecated
  5003. offset: this.positionAbs
  5004. };
  5005. }
  5006. }));
  5007. $.extend($.ui.draggable, {
  5008. version: "1.7",
  5009. eventPrefix: "drag",
  5010. defaults: {
  5011. addClasses: true,
  5012. appendTo: "parent",
  5013. axis: false,
  5014. cancel: ":input,option",
  5015. connectToSortable: false,
  5016. containment: false,
  5017. cursor: "auto",
  5018. cursorAt: false,
  5019. delay: 0,
  5020. distance: 1,
  5021. grid: false,
  5022. handle: false,
  5023. helper: "original",
  5024. iframeFix: false,
  5025. opacity: false,
  5026. refreshPositions: false,
  5027. revert: false,
  5028. revertDuration: 500,
  5029. scope: "default",
  5030. scroll: true,
  5031. scrollSensitivity: 20,
  5032. scrollSpeed: 20,
  5033. snap: false,
  5034. snapMode: "both",
  5035. snapTolerance: 20,
  5036. stack: false,
  5037. zIndex: false
  5038. }
  5039. });
  5040. $.ui.plugin.add("draggable", "connectToSortable", {
  5041. start: function(event, ui) {
  5042. var inst = $(this).data("draggable"), o = inst.options,
  5043. uiSortable = $.extend({}, ui, { item: inst.element });
  5044. inst.sortables = [];
  5045. $(o.connectToSortable).each(function() {
  5046. var sortable = $.data(this, 'sortable');
  5047. if (sortable && !sortable.options.disabled) {
  5048. inst.sortables.push({
  5049. instance: sortable,
  5050. shouldRevert: sortable.options.revert
  5051. });
  5052. sortable._refreshItems(); //Do a one-time refresh at start to refresh the containerCache
  5053. sortable._trigger("activate", event, uiSortable);
  5054. }
  5055. });
  5056. },
  5057. stop: function(event, ui) {
  5058. //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
  5059. var inst = $(this).data("draggable"),
  5060. uiSortable = $.extend({}, ui, { item: inst.element });
  5061. $.each(inst.sortables, function() {
  5062. if(this.instance.isOver) {
  5063. this.instance.isOver = 0;
  5064. inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
  5065. this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
  5066. //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
  5067. if(this.shouldRevert) this.instance.options.revert = true;
  5068. //Trigger the stop of the sortable
  5069. this.instance._mouseStop(event);
  5070. this.instance.options.helper = this.instance.options._helper;
  5071. //If the helper has been the original item, restore properties in the sortable
  5072. if(inst.options.helper == 'original')
  5073. this.instance.currentItem.css({ top: 'auto', left: 'auto' });
  5074. } else {
  5075. this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
  5076. this.instance._trigger("deactivate", event, uiSortable);
  5077. }
  5078. });
  5079. },
  5080. drag: function(event, ui) {
  5081. var inst = $(this).data("draggable"), self = this;
  5082. var checkPos = function(o) {
  5083. var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
  5084. var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
  5085. var itemHeight = o.height, itemWidth = o.width;
  5086. var itemTop = o.top, itemLeft = o.left;
  5087. return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
  5088. };
  5089. $.each(inst.sortables, function(i) {
  5090. //Copy over some variables to allow calling the sortable's native _intersectsWith
  5091. this.instance.positionAbs = inst.positionAbs;
  5092. this.instance.helperProportions = inst.helperProportions;
  5093. this.instance.offset.click = inst.offset.click;
  5094. if(this.instance._intersectsWith(this.instance.containerCache)) {
  5095. //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
  5096. if(!this.instance.isOver) {
  5097. this.instance.isOver = 1;
  5098. //Now we fake the start of dragging for the sortable instance,
  5099. //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
  5100. //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)
  5101. this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
  5102. this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
  5103. this.instance.options.helper = function() { return ui.helper[0]; };
  5104. event.target = this.instance.currentItem[0];
  5105. this.instance._mouseCapture(event, true);
  5106. this.instance._mouseStart(event, true, true);
  5107. //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
  5108. this.instance.offset.click.top = inst.offset.click.top;
  5109. this.instance.offset.click.left = inst.offset.click.left;
  5110. this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
  5111. this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
  5112. inst._trigger("toSortable", event);
  5113. inst.dropped = this.instance.element; //draggable revert needs that
  5114. //hack so receive/update callbacks work (mostly)
  5115. inst.currentItem = inst.element;
  5116. this.instance.fromOutside = inst;
  5117. }
  5118. //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
  5119. if(this.instance.currentItem) this.instance._mouseDrag(event);
  5120. } else {
  5121. //If it doesn't intersect with the sortable, and it intersected before,
  5122. //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
  5123. if(this.instance.isOver) {
  5124. this.instance.isOver = 0;
  5125. this.instance.cancelHelperRemoval = true;
  5126. //Prevent reverting on this forced stop
  5127. this.instance.options.revert = false;
  5128. // The out event needs to be triggered independently
  5129. this.instance._trigger('out', event, this.instance._uiHash(this.instance));
  5130. this.instance._mouseStop(event, true);
  5131. this.instance.options.helper = this.instance.options._helper;
  5132. //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
  5133. this.instance.currentItem.remove();
  5134. if(this.instance.placeholder) this.instance.placeholder.remove();
  5135. inst._trigger("fromSortable", event);
  5136. inst.dropped = false; //draggable revert needs that
  5137. }
  5138. };
  5139. });
  5140. }
  5141. });
  5142. $.ui.plugin.add("draggable", "cursor", {
  5143. start: function(event, ui) {
  5144. var t = $('body'), o = $(this).data('draggable').options;
  5145. if (t.css("cursor")) o._cursor = t.css("cursor");
  5146. t.css("cursor", o.cursor);
  5147. },
  5148. stop: function(event, ui) {
  5149. var o = $(this).data('draggable').options;
  5150. if (o._cursor) $('body').css("cursor", o._cursor);
  5151. }
  5152. });
  5153. $.ui.plugin.add("draggable", "iframeFix", {
  5154. start: function(event, ui) {
  5155. var o = $(this).data('draggable').options;
  5156. $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
  5157. $('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
  5158. .css({
  5159. width: this.offsetWidth+"px", height: this.offsetHeight+"px",
  5160. position: "absolute", opacity: "0.001", zIndex: 1000
  5161. })
  5162. .css($(this).offset())
  5163. .appendTo("body");
  5164. });
  5165. },
  5166. stop: function(event, ui) {
  5167. $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
  5168. }
  5169. });
  5170. $.ui.plugin.add("draggable", "opacity", {
  5171. start: function(event, ui) {
  5172. var t = $(ui.helper), o = $(this).data('draggable').options;
  5173. if(t.css("opacity")) o._opacity = t.css("opacity");
  5174. t.css('opacity', o.opacity);
  5175. },
  5176. stop: function(event, ui) {
  5177. var o = $(this).data('draggable').options;
  5178. if(o._opacity) $(ui.helper).css('opacity', o._opacity);
  5179. }
  5180. });
  5181. $.ui.plugin.add("draggable", "scroll", {
  5182. start: function(event, ui) {
  5183. var i = $(this).data("draggable");
  5184. if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
  5185. },
  5186. drag: function(event, ui) {
  5187. var i = $(this).data("draggable"), o = i.options, scrolled = false;
  5188. if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {
  5189. if(!o.axis || o.axis != 'x') {
  5190. if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
  5191. i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
  5192. else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
  5193. i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
  5194. }
  5195. if(!o.axis || o.axis != 'y') {
  5196. if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
  5197. i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
  5198. else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
  5199. i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
  5200. }
  5201. } else {
  5202. if(!o.axis || o.axis != 'x') {
  5203. if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
  5204. scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
  5205. else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
  5206. scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
  5207. }
  5208. if(!o.axis || o.axis != 'y') {
  5209. if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
  5210. scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
  5211. else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
  5212. scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
  5213. }
  5214. }
  5215. if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
  5216. $.ui.ddmanager.prepareOffsets(i, event);
  5217. }
  5218. });
  5219. $.ui.plugin.add("draggable", "snap", {
  5220. start: function(event, ui) {
  5221. var i = $(this).data("draggable"), o = i.options;
  5222. i.snapElements = [];
  5223. $(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
  5224. var $t = $(this); var $o = $t.offset();
  5225. if(this != i.element[0]) i.snapElements.push({
  5226. item: this,
  5227. width: $t.outerWidth(), height: $t.outerHeight(),
  5228. top: $o.top, left: $o.left
  5229. });
  5230. });
  5231. },
  5232. drag: function(event, ui) {
  5233. var inst = $(this).data("draggable"), o = inst.options;
  5234. var d = o.snapTolerance;
  5235. var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
  5236. y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
  5237. for (var i = inst.snapElements.length - 1; i >= 0; i--){
  5238. var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
  5239. t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;
  5240. //Yes, I know, this is insane ;)
  5241. if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
  5242. 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 })));
  5243. inst.snapElements[i].snapping = false;
  5244. continue;
  5245. }
  5246. if(o.snapMode != 'inner') {
  5247. var ts = Math.abs(t - y2) <= d;
  5248. var bs = Math.abs(b - y1) <= d;
  5249. var ls = Math.abs(l - x2) <= d;
  5250. var rs = Math.abs(r - x1) <= d;
  5251. if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
  5252. if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
  5253. if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
  5254. if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
  5255. }
  5256. var first = (ts || bs || ls || rs);
  5257. if(o.snapMode != 'outer') {
  5258. var ts = Math.abs(t - y1) <= d;
  5259. var bs = Math.abs(b - y2) <= d;
  5260. var ls = Math.abs(l - x1) <= d;
  5261. var rs = Math.abs(r - x2) <= d;
  5262. if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
  5263. if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
  5264. if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
  5265. if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
  5266. }
  5267. if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
  5268. (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
  5269. inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
  5270. };
  5271. }
  5272. });
  5273. $.ui.plugin.add("draggable", "stack", {
  5274. start: function(event, ui) {
  5275. var o = $(this).data("draggable").options;
  5276. var group = $.makeArray($(o.stack.group)).sort(function(a,b) {
  5277. return (parseInt($(a).css("zIndex"),10) || o.stack.min) - (parseInt($(b).css("zIndex"),10) || o.stack.min);
  5278. });
  5279. $(group).each(function(i) {
  5280. this.style.zIndex = o.stack.min + i;
  5281. });
  5282. this[0].style.zIndex = o.stack.min + group.length;
  5283. }
  5284. });
  5285. $.ui.plugin.add("draggable", "zIndex", {
  5286. start: function(event, ui) {
  5287. var t = $(ui.helper), o = $(this).data("draggable").options;
  5288. if(t.css("zIndex")) o._zIndex = t.css("zIndex");
  5289. t.css('zIndex', o.zIndex);
  5290. },
  5291. stop: function(event, ui) {
  5292. var o = $(this).data("draggable").options;
  5293. if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
  5294. }
  5295. });
  5296. })(jQuery);
  5297. /*
  5298. * jQuery UI Accordion 1.7
  5299. *
  5300. * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
  5301. * Dual licensed under the MIT (MIT-LICENSE.txt)
  5302. * and GPL (GPL-LICENSE.txt) licenses.
  5303. *
  5304. * http://docs.jquery.com/UI/Accordion
  5305. *
  5306. * Depends:
  5307. * ui.core.js
  5308. */
  5309. (function($) {
  5310. $.widget("ui.accordion", {
  5311. _init: function() {
  5312. var o = this.options, self = this;
  5313. this.running = 0;
  5314. // if the user set the alwaysOpen option on init
  5315. // then we need to set the collapsible option
  5316. // if they set both on init, collapsible will take priority
  5317. if (o.collapsible == $.ui.accordion.defaults.collapsible &&
  5318. o.alwaysOpen != $.ui.accordion.defaults.alwaysOpen) {
  5319. o.collapsible = !o.alwaysOpen;
  5320. }
  5321. if ( o.navigation ) {
  5322. var current = this.element.find("a").filter(o.navigationFilter);
  5323. if ( current.length ) {
  5324. if ( current.filter(o.header).length ) {
  5325. this.active = current;
  5326. } else {
  5327. this.active = current.parent().parent().prev();
  5328. current.addClass("ui-accordion-content-active");
  5329. }
  5330. }
  5331. }
  5332. this.element.addClass("ui-accordion ui-widget ui-helper-reset");
  5333. // in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix
  5334. if (this.element[0].nodeName == "UL") {
  5335. this.element.children("li").addClass("ui-accordion-li-fix");
  5336. }
  5337. this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all")
  5338. .bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); })
  5339. .bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); })
  5340. .bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); })
  5341. .bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); });
  5342. this.headers
  5343. .next()
  5344. .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");
  5345. this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");
  5346. this.active.next().addClass('ui-accordion-content-active');
  5347. //Append icon elements
  5348. $("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers);
  5349. this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected);
  5350. // IE7-/Win - Extra vertical space in lists fixed
  5351. if ($.browser.msie) {
  5352. this.element.find('a').css('zoom', '1');
  5353. }
  5354. this.resize();
  5355. //ARIA
  5356. this.element.attr('role','tablist');
  5357. this.headers
  5358. .attr('role','tab')
  5359. .bind('keydown', function(event) { return self._keydown(event); })
  5360. .next()
  5361. .attr('role','tabpanel');
  5362. this.headers
  5363. .not(this.active || "")
  5364. .attr('aria-expanded','false')
  5365. .attr("tabIndex", "-1")
  5366. .next()
  5367. .hide();
  5368. // make sure at least one header is in the tab order
  5369. if (!this.active.length) {
  5370. this.headers.eq(0).attr('tabIndex','0');
  5371. } else {
  5372. this.active
  5373. .attr('aria-expanded','true')
  5374. .attr('tabIndex', '0');
  5375. }
  5376. // only need links in taborder for Safari
  5377. if (!$.browser.safari)
  5378. this.headers.find('a').attr('tabIndex','-1');
  5379. if (o.event) {
  5380. this.headers.bind((o.event) + ".accordion", function(event) { return self._clickHandler.call(self, event, this); });
  5381. }
  5382. },
  5383. destroy: function() {
  5384. var o = this.options;
  5385. this.element
  5386. .removeClass("ui-accordion ui-widget ui-helper-reset")
  5387. .removeAttr("role")
  5388. .unbind('.accordion')
  5389. .removeData('accordion');
  5390. this.headers
  5391. .unbind(".accordion")
  5392. .removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top")
  5393. .removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex");
  5394. this.headers.find("a").removeAttr("tabindex");
  5395. this.headers.children(".ui-icon").remove();
  5396. var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");
  5397. if (o.autoHeight || o.fillHeight) {
  5398. contents.css("height", "");
  5399. }
  5400. },
  5401. _setData: function(key, value) {
  5402. if(key == 'alwaysOpen') { key = 'collapsible'; value = !value; }
  5403. $.widget.prototype._setData.apply(this, arguments);
  5404. },
  5405. _keydown: function(event) {
  5406. var o = this.options, keyCode = $.ui.keyCode;
  5407. if (o.disabled || event.altKey || event.ctrlKey)
  5408. return;
  5409. var length = this.headers.length;
  5410. var currentIndex = this.headers.index(event.target);
  5411. var toFocus = false;
  5412. switch(event.keyCode) {
  5413. case keyCode.RIGHT:
  5414. case keyCode.DOWN:
  5415. toFocus = this.headers[(currentIndex + 1) % length];
  5416. break;
  5417. case keyCode.LEFT:
  5418. case keyCode.UP:
  5419. toFocus = this.headers[(currentIndex - 1 + length) % length];
  5420. break;
  5421. case keyCode.SPACE:
  5422. case keyCode.ENTER:
  5423. return this._clickHandler({ target: event.target }, event.target);
  5424. }
  5425. if (toFocus) {
  5426. $(event.target).attr('tabIndex','-1');
  5427. $(toFocus).attr('tabIndex','0');
  5428. toFocus.focus();
  5429. return false;
  5430. }
  5431. return true;
  5432. },
  5433. resize: function() {
  5434. var o = this.options, maxHeight;
  5435. if (o.fillSpace) {
  5436. if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); }
  5437. maxHeight = this.element.parent().height();
  5438. if($.browser.msie) { this.element.parent().css('overflow', defOverflow); }
  5439. this.headers.each(function() {
  5440. maxHeight -= $(this).outerHeight();
  5441. });
  5442. var maxPadding = 0;
  5443. this.headers.next().each(function() {
  5444. maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height());
  5445. }).height(Math.max(0, maxHeight - maxPadding))
  5446. .css('overflow', 'auto');
  5447. } else if ( o.autoHeight ) {
  5448. maxHeight = 0;
  5449. this.headers.next().each(function() {
  5450. maxHeight = Math.max(maxHeight, $(this).outerHeight());
  5451. }).height(maxHeight);
  5452. }
  5453. },
  5454. activate: function(index) {
  5455. // call clickHandler with custom event
  5456. var active = this._findActive(index)[0];
  5457. this._clickHandler({ target: active }, active);
  5458. },
  5459. _findActive: function(selector) {
  5460. return selector
  5461. ? typeof selector == "number"
  5462. ? this.headers.filter(":eq(" + selector + ")")
  5463. : this.headers.not(this.headers.not(selector))
  5464. : selector === false
  5465. ? $([])
  5466. : this.headers.filter(":eq(0)");
  5467. },
  5468. _clickHandler: function(event, target) {
  5469. var o = this.options;
  5470. if (o.disabled) return false;
  5471. // called only when using activate(false) to close all parts programmatically
  5472. if (!event.target && o.collapsible) {
  5473. this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
  5474. .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
  5475. this.active.next().addClass('ui-accordion-content-active');
  5476. var toHide = this.active.next(),
  5477. data = {
  5478. options: o,
  5479. newHeader: $([]),
  5480. oldHeader: o.active,
  5481. newContent: $([]),
  5482. oldContent: toHide
  5483. },
  5484. toShow = (this.active = $([]));
  5485. this._toggle(toShow, toHide, data);
  5486. return false;
  5487. }
  5488. // get the click target
  5489. var clicked = $(event.currentTarget || target);
  5490. var clickedIsActive = clicked[0] == this.active[0];
  5491. // if animations are still active, or the active header is the target, ignore click
  5492. if (this.running || (!o.collapsible && clickedIsActive)) {
  5493. return false;
  5494. }
  5495. // switch classes
  5496. this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
  5497. .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
  5498. this.active.next().addClass('ui-accordion-content-active');
  5499. if (!clickedIsActive) {
  5500. clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top")
  5501. .find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected);
  5502. clicked.next().addClass('ui-accordion-content-active');
  5503. }
  5504. // find elements to show and hide
  5505. var toShow = clicked.next(),
  5506. toHide = this.active.next(),
  5507. data = {
  5508. options: o,
  5509. newHeader: clickedIsActive && o.collapsible ? $([]) : clicked,
  5510. oldHeader: this.active,
  5511. newContent: clickedIsActive && o.collapsible ? $([]) : toShow.find('> *'),
  5512. oldContent: toHide.find('> *')
  5513. },
  5514. down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] );
  5515. this.active = clickedIsActive ? $([]) : clicked;
  5516. this._toggle(toShow, toHide, data, clickedIsActive, down);
  5517. return false;
  5518. },
  5519. _toggle: function(toShow, toHide, data, clickedIsActive, down) {
  5520. var o = this.options, self = this;
  5521. this.toShow = toShow;
  5522. this.toHide = toHide;
  5523. this.data = data;
  5524. var complete = function() { if(!self) return; return self._completed.apply(self, arguments); };
  5525. // trigger changestart event
  5526. this._trigger("changestart", null, this.data);
  5527. // count elements to animate
  5528. this.running = toHide.size() === 0 ? toShow.size() : toHide.size();
  5529. if (o.animated) {
  5530. var animOptions = {};
  5531. if ( o.collapsible && clickedIsActive ) {
  5532. animOptions = {
  5533. toShow: $([]),
  5534. toHide: toHide,
  5535. complete: complete,
  5536. down: down,
  5537. autoHeight: o.autoHeight || o.fillSpace
  5538. };
  5539. } else {
  5540. animOptions = {
  5541. toShow: toShow,
  5542. toHide: toHide,
  5543. complete: complete,
  5544. down: down,
  5545. autoHeight: o.autoHeight || o.fillSpace
  5546. };
  5547. }
  5548. if (!o.proxied) {
  5549. o.proxied = o.animated;
  5550. }
  5551. if (!o.proxiedDuration) {
  5552. o.proxiedDuration = o.duration;
  5553. }
  5554. o.animated = $.isFunction(o.proxied) ?
  5555. o.proxied(animOptions) : o.proxied;
  5556. o.duration = $.isFunction(o.proxiedDuration) ?
  5557. o.proxiedDuration(animOptions) : o.proxiedDuration;
  5558. var animations = $.ui.accordion.animations,
  5559. duration = o.duration,
  5560. easing = o.animated;
  5561. if (!animations[easing]) {
  5562. animations[easing] = function(options) {
  5563. this.slide(options, {
  5564. easing: easing,
  5565. duration: duration || 700
  5566. });
  5567. };
  5568. }
  5569. animations[easing](animOptions);
  5570. } else {
  5571. if (o.collapsible && clickedIsActive) {
  5572. toShow.toggle();
  5573. } else {
  5574. toHide.hide();
  5575. toShow.show();
  5576. }
  5577. complete(true);
  5578. }
  5579. toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur();
  5580. toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus();
  5581. },
  5582. _completed: function(cancel) {
  5583. var o = this.options;
  5584. this.running = cancel ? 0 : --this.running;
  5585. if (this.running) return;
  5586. if (o.clearStyle) {
  5587. this.toShow.add(this.toHide).css({
  5588. height: "",
  5589. overflow: ""
  5590. });
  5591. }
  5592. this._trigger('change', null, this.data);
  5593. }
  5594. });
  5595. $.extend($.ui.accordion, {
  5596. version: "1.7",
  5597. defaults: {
  5598. active: null,
  5599. alwaysOpen: true, //deprecated, use collapsible
  5600. animated: 'slide',
  5601. autoHeight: true,
  5602. clearStyle: false,
  5603. collapsible: false,
  5604. event: "click",
  5605. fillSpace: false,
  5606. header: "> li > :first-child,> :not(li):even",
  5607. icons: {
  5608. header: "ui-icon-triangle-1-e",
  5609. headerSelected: "ui-icon-triangle-1-s"
  5610. },
  5611. navigation: false,
  5612. navigationFilter: function() {
  5613. return this.href.toLowerCase() == location.href.toLowerCase();
  5614. }
  5615. },
  5616. animations: {
  5617. slide: function(options, additions) {
  5618. options = $.extend({
  5619. easing: "swing",
  5620. duration: 300
  5621. }, options, additions);
  5622. if ( !options.toHide.size() ) {
  5623. options.toShow.animate({height: "show"}, options);
  5624. return;
  5625. }
  5626. if ( !options.toShow.size() ) {
  5627. options.toHide.animate({height: "hide"}, options);
  5628. return;
  5629. }
  5630. var overflow = options.toShow.css('overflow'),
  5631. percentDone,
  5632. showProps = {},
  5633. hideProps = {},
  5634. fxAttrs = [ "height", "paddingTop", "paddingBottom" ],
  5635. originalWidth;
  5636. // fix width before calculating height of hidden element
  5637. var s = options.toShow;
  5638. originalWidth = s[0].style.width;
  5639. s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - parseInt(s.css("borderLeftWidth"),10) - parseInt(s.css("borderRightWidth"),10) );
  5640. $.each(fxAttrs, function(i, prop) {
  5641. hideProps[prop] = 'hide';
  5642. var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/);
  5643. showProps[prop] = {
  5644. value: parts[1],
  5645. unit: parts[2] || 'px'
  5646. };
  5647. });
  5648. options.toShow.css({ height: 0, overflow: 'hidden' }).show();
  5649. options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{
  5650. step: function(now, settings) {
  5651. // only calculate the percent when animating height
  5652. // IE gets very inconsistent results when animating elements
  5653. // with small values, which is common for padding
  5654. if (settings.prop == 'height') {
  5655. percentDone = (settings.now - settings.start) / (settings.end - settings.start);
  5656. }
  5657. options.toShow[0].style[settings.prop] =
  5658. (percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit;
  5659. },
  5660. duration: options.duration,
  5661. easing: options.easing,
  5662. complete: function() {
  5663. if ( !options.autoHeight ) {
  5664. options.toShow.css("height", "");
  5665. }
  5666. options.toShow.css("width", originalWidth);
  5667. options.toShow.css({overflow: overflow});
  5668. options.complete();
  5669. }
  5670. });
  5671. },
  5672. bounceslide: function(options) {
  5673. this.slide(options, {
  5674. easing: options.down ? "easeOutBounce" : "swing",
  5675. duration: options.down ? 1000 : 200
  5676. });
  5677. },
  5678. easeslide: function(options) {
  5679. this.slide(options, {
  5680. easing: "easeinout",
  5681. duration: 700
  5682. });
  5683. }
  5684. }
  5685. });
  5686. })(jQuery);
  5687. /*
  5688. * jQuery UI Slider 1.7
  5689. *
  5690. * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
  5691. * Dual licensed under the MIT (MIT-LICENSE.txt)
  5692. * and GPL (GPL-LICENSE.txt) licenses.
  5693. *
  5694. * http://docs.jquery.com/UI/Slider
  5695. *
  5696. * Depends:
  5697. * ui.core.js
  5698. */
  5699. (function($) {
  5700. $.widget("ui.slider", $.extend({}, $.ui.mouse, {
  5701. _init: function() {
  5702. var self = this, o = this.options;
  5703. this._keySliding = false;
  5704. this._handleIndex = null;
  5705. this._detectOrientation();
  5706. this._mouseInit();
  5707. this.element
  5708. .addClass("ui-slider"
  5709. + " ui-slider-" + this.orientation
  5710. + " ui-widget"
  5711. + " ui-widget-content"
  5712. + " ui-corner-all");
  5713. this.range = $([]);
  5714. if (o.range) {
  5715. if (o.range === true) {
  5716. this.range = $('<div></div>');
  5717. if (!o.values) o.values = [this._valueMin(), this._valueMin()];
  5718. if (o.values.length && o.values.length != 2) {
  5719. o.values = [o.values[0], o.values[0]];
  5720. }
  5721. } else {
  5722. this.range = $('<div></div>');
  5723. }
  5724. this.range
  5725. .appendTo(this.element)
  5726. .addClass("ui-slider-range");
  5727. if (o.range == "min" || o.range == "max") {
  5728. this.range.addClass("ui-slider-range-" + o.range);
  5729. }
  5730. // note: this isn't the most fittingly semantic framework class for this element,
  5731. // but worked best visually with a variety of themes
  5732. this.range.addClass("ui-widget-header");
  5733. }
  5734. if ($(".ui-slider-handle", this.element).length == 0)
  5735. $('<a href="#"></a>')
  5736. .appendTo(this.element)
  5737. .addClass("ui-slider-handle");
  5738. if (o.values && o.values.length) {
  5739. while ($(".ui-slider-handle", this.element).length < o.values.length)
  5740. $('<a href="#"></a>')
  5741. .appendTo(this.element)
  5742. .addClass("ui-slider-handle");
  5743. }
  5744. this.handles = $(".ui-slider-handle", this.element)
  5745. .addClass("ui-state-default"
  5746. + " ui-corner-all");
  5747. this.handle = this.handles.eq(0);
  5748. this.handles.add(this.range).filter("a")
  5749. .click(function(event) { event.preventDefault(); })
  5750. .hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); })
  5751. .focus(function() { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); })
  5752. .blur(function() { $(this).removeClass('ui-state-focus'); });
  5753. this.handles.each(function(i) {
  5754. $(this).data("index.ui-slider-handle", i);
  5755. });
  5756. this.handles.keydown(function(event) {
  5757. var ret = true;
  5758. var index = $(this).data("index.ui-slider-handle");
  5759. if (self.options.disabled)
  5760. return;
  5761. switch (event.keyCode) {
  5762. case $.ui.keyCode.HOME:
  5763. case $.ui.keyCode.END:
  5764. case $.ui.keyCode.UP:
  5765. case $.ui.keyCode.RIGHT:
  5766. case $.ui.keyCode.DOWN:
  5767. case $.ui.keyCode.LEFT:
  5768. ret = false;
  5769. if (!self._keySliding) {
  5770. self._keySliding = true;
  5771. $(this).addClass("ui-state-active");
  5772. self._start(event, index);
  5773. }
  5774. break;
  5775. }
  5776. var curVal, newVal, step = self._step();
  5777. if (self.options.values && self.options.values.length) {
  5778. curVal = newVal = self.values(index);
  5779. } else {
  5780. curVal = newVal = self.value();
  5781. }
  5782. switch (event.keyCode) {
  5783. case $.ui.keyCode.HOME:
  5784. newVal = self._valueMin();
  5785. break;
  5786. case $.ui.keyCode.END:
  5787. newVal = self._valueMax();
  5788. break;
  5789. case $.ui.keyCode.UP:
  5790. case $.ui.keyCode.RIGHT:
  5791. if(curVal == self._valueMax()) return;
  5792. newVal = curVal + step;
  5793. break;
  5794. case $.ui.keyCode.DOWN:
  5795. case $.ui.keyCode.LEFT:
  5796. if(curVal == self._valueMin()) return;
  5797. newVal = curVal - step;
  5798. break;
  5799. }
  5800. self._slide(event, index, newVal);
  5801. return ret;
  5802. }).keyup(function(event) {
  5803. var index = $(this).data("index.ui-slider-handle");
  5804. if (self._keySliding) {
  5805. self._stop(event, index);
  5806. self._change(event, index);
  5807. self._keySliding = false;
  5808. $(this).removeClass("ui-state-active");
  5809. }
  5810. });
  5811. this._refreshValue();
  5812. },
  5813. destroy: function() {
  5814. this.handles.remove();
  5815. this.element
  5816. .removeClass("ui-slider"
  5817. + " ui-slider-horizontal"
  5818. + " ui-slider-vertical"
  5819. + " ui-slider-disabled"
  5820. + " ui-widget"
  5821. + " ui-widget-content"
  5822. + " ui-corner-all")
  5823. .removeData("slider")
  5824. .unbind(".slider");
  5825. this._mouseDestroy();
  5826. },
  5827. _mouseCapture: function(event) {
  5828. var o = this.options;
  5829. if (o.disabled)
  5830. return false;
  5831. this.elementSize = {
  5832. width: this.element.outerWidth(),
  5833. height: this.element.outerHeight()
  5834. };
  5835. this.elementOffset = this.element.offset();
  5836. var position = { x: event.pageX, y: event.pageY };
  5837. var normValue = this._normValueFromMouse(position);
  5838. var distance = this._valueMax() + 1, closestHandle;
  5839. var self = this, index;
  5840. this.handles.each(function(i) {
  5841. var thisDistance = Math.abs(normValue - self.values(i));
  5842. if (distance > thisDistance) {
  5843. distance = thisDistance;
  5844. closestHandle = $(this);
  5845. index = i;
  5846. }
  5847. });
  5848. // workaround for bug #3736 (if both handles of a range are at 0,
  5849. // the first is always used as the one with least distance,
  5850. // and moving it is obviously prevented by preventing negative ranges)
  5851. if(o.range == true && this.values(1) == o.min) {
  5852. closestHandle = $(this.handles[++index]);
  5853. }
  5854. this._start(event, index);
  5855. self._handleIndex = index;
  5856. closestHandle
  5857. .addClass("ui-state-active")
  5858. .focus();
  5859. var offset = closestHandle.offset();
  5860. var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle');
  5861. this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
  5862. left: event.pageX - offset.left - (closestHandle.width() / 2),
  5863. top: event.pageY - offset.top
  5864. - (closestHandle.height() / 2)
  5865. - (parseInt(closestHandle.css('borderTopWidth'),10) || 0)
  5866. - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0)
  5867. + (parseInt(closestHandle.css('marginTop'),10) || 0)
  5868. };
  5869. normValue = this._normValueFromMouse(position);
  5870. this._slide(event, index, normValue);
  5871. return true;
  5872. },
  5873. _mouseStart: function(event) {
  5874. return true;
  5875. },
  5876. _mouseDrag: function(event) {
  5877. var position = { x: event.pageX, y: event.pageY };
  5878. var normValue = this._normValueFromMouse(position);
  5879. this._slide(event, this._handleIndex, normValue);
  5880. return false;
  5881. },
  5882. _mouseStop: function(event) {
  5883. this.handles.removeClass("ui-state-active");
  5884. this._stop(event, this._handleIndex);
  5885. this._change(event, this._handleIndex);
  5886. this._handleIndex = null;
  5887. this._clickOffset = null;
  5888. return false;
  5889. },
  5890. _detectOrientation: function() {
  5891. this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal';
  5892. },
  5893. _normValueFromMouse: function(position) {
  5894. var pixelTotal, pixelMouse;
  5895. if ('horizontal' == this.orientation) {
  5896. pixelTotal = this.elementSize.width;
  5897. pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
  5898. } else {
  5899. pixelTotal = this.elementSize.height;
  5900. pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
  5901. }
  5902. var percentMouse = (pixelMouse / pixelTotal);
  5903. if (percentMouse > 1) percentMouse = 1;
  5904. if (percentMouse < 0) percentMouse = 0;
  5905. if ('vertical' == this.orientation)
  5906. percentMouse = 1 - percentMouse;
  5907. var valueTotal = this._valueMax() - this._valueMin(),
  5908. valueMouse = percentMouse * valueTotal,
  5909. valueMouseModStep = valueMouse % this.options.step,
  5910. normValue = this._valueMin() + valueMouse - valueMouseModStep;
  5911. if (valueMouseModStep > (this.options.step / 2))
  5912. normValue += this.options.step;
  5913. // Since JavaScript has problems with large floats, round
  5914. // the final value to 5 digits after the decimal point (see #4124)
  5915. return parseFloat(normValue.toFixed(5));
  5916. },
  5917. _start: function(event, index) {
  5918. this._trigger("start", event, this._uiHash(index));
  5919. },
  5920. _slide: function(event, index, newVal) {
  5921. var handle = this.handles[index];
  5922. if (this.options.values && this.options.values.length) {
  5923. var otherVal = this.values(index ? 0 : 1);
  5924. if ((index == 0 && newVal >= otherVal) || (index == 1 && newVal <= otherVal))
  5925. newVal = otherVal;
  5926. if (newVal != this.values(index)) {
  5927. var newValues = this.values();
  5928. newValues[index] = newVal;
  5929. // A slide can be canceled by returning false from the slide callback
  5930. var allowed = this._trigger("slide", event, this._uiHash(index, newVal, newValues));
  5931. var otherVal = this.values(index ? 0 : 1);
  5932. if (allowed !== false) {
  5933. this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true);
  5934. }
  5935. }
  5936. } else {
  5937. if (newVal != this.value()) {
  5938. // A slide can be canceled by returning false from the slide callback
  5939. var allowed = this._trigger("slide", event, this._uiHash(index, newVal));
  5940. if (allowed !== false) {
  5941. this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate ));
  5942. }
  5943. }
  5944. }
  5945. },
  5946. _stop: function(event, index) {
  5947. this._trigger("stop", event, this._uiHash(index));
  5948. },
  5949. _change: function(event, index) {
  5950. this._trigger("change", event, this._uiHash(index));
  5951. },
  5952. value: function(newValue) {
  5953. if (arguments.length) {
  5954. this._setData("value", newValue);
  5955. this._change(null, 0);
  5956. }
  5957. return this._value();
  5958. },
  5959. values: function(index, newValue, animated, noPropagation) {
  5960. if (arguments.length > 1) {
  5961. this.options.values[index] = newValue;
  5962. this._refreshValue(animated);
  5963. if(!noPropagation) this._change(null, index);
  5964. }
  5965. if (arguments.length) {
  5966. if (this.options.values && this.options.values.length) {
  5967. return this._values(index);
  5968. } else {
  5969. return this.value();
  5970. }
  5971. } else {
  5972. return this._values();
  5973. }
  5974. },
  5975. _setData: function(key, value, animated) {
  5976. $.widget.prototype._setData.apply(this, arguments);
  5977. switch (key) {
  5978. case 'orientation':
  5979. this._detectOrientation();
  5980. this.element
  5981. .removeClass("ui-slider-horizontal ui-slider-vertical")
  5982. .addClass("ui-slider-" + this.orientation);
  5983. this._refreshValue(animated);
  5984. break;
  5985. case 'value':
  5986. this._refreshValue(animated);
  5987. break;
  5988. }
  5989. },
  5990. _step: function() {
  5991. var step = this.options.step;
  5992. return step;
  5993. },
  5994. _value: function() {
  5995. var val = this.options.value;
  5996. if (val < this._valueMin()) val = this._valueMin();
  5997. if (val > this._valueMax()) val = this._valueMax();
  5998. return val;
  5999. },
  6000. _values: function(index) {
  6001. if (arguments.length) {
  6002. var val = this.options.values[index];
  6003. if (val < this._valueMin()) val = this._valueMin();
  6004. if (val > this._valueMax()) val = this._valueMax();
  6005. return val;
  6006. } else {
  6007. return this.options.values;
  6008. }
  6009. },
  6010. _valueMin: function() {
  6011. var valueMin = this.options.min;
  6012. return valueMin;
  6013. },
  6014. _valueMax: function() {
  6015. var valueMax = this.options.max;
  6016. return valueMax;
  6017. },
  6018. _refreshValue: function(animate) {
  6019. var oRange = this.options.range, o = this.options, self = this;
  6020. if (this.options.values && this.options.values.length) {
  6021. var vp0, vp1;
  6022. this.handles.each(function(i, j) {
  6023. var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
  6024. var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
  6025. $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
  6026. if (self.options.range === true) {
  6027. if (self.orientation == 'horizontal') {
  6028. (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate);
  6029. (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
  6030. } else {
  6031. (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate);
  6032. (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
  6033. }
  6034. }
  6035. lastValPercent = valPercent;
  6036. });
  6037. } else {
  6038. var value = this.value(),
  6039. valueMin = this._valueMin(),
  6040. valueMax = this._valueMax(),
  6041. valPercent = valueMax != valueMin
  6042. ? (value - valueMin) / (valueMax - valueMin) * 100
  6043. : 0;
  6044. var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
  6045. this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
  6046. (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate);
  6047. (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
  6048. (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate);
  6049. (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
  6050. }
  6051. },
  6052. _uiHash: function(index, value, values) {
  6053. var multiple = this.options.values && this.options.values.length;
  6054. return {
  6055. handle: this.handles[index],
  6056. value: value || (multiple ? this.values(index) : this.value()),
  6057. values: values || (multiple && this.values())
  6058. };
  6059. }
  6060. }));
  6061. $.extend($.ui.slider, {
  6062. getter: "value values",
  6063. version: "1.7",
  6064. eventPrefix: "slide",
  6065. defaults: {
  6066. animate: false,
  6067. delay: 0,
  6068. distance: 0,
  6069. max: 100,
  6070. min: 0,
  6071. orientation: 'horizontal',
  6072. range: false,
  6073. step: 1,
  6074. value: 0,
  6075. values: null
  6076. }
  6077. });
  6078. })(jQuery);
  6079. /*
  6080. * jQuery delegate plug-in v1.0
  6081. *
  6082. * Copyright (c) 2007 J??rn Zaefferer
  6083. *
  6084. * $Id: jquery.delegate.js 7175 2009-05-15 16:59:09Z antranig@caret.cam.ac.uk $
  6085. *
  6086. * Dual licensed under the MIT and GPL licenses:
  6087. * http://www.opensource.org/licenses/mit-license.php
  6088. * http://www.gnu.org/licenses/gpl.html
  6089. */
  6090. // provides cross-browser focusin and focusout events
  6091. // IE has native support, in other browsers, use event caputuring (neither bubbles)
  6092. // provides delegate(type: String, delegate: Selector, handler: Callback) plugin for easier event delegation
  6093. // handler is only called when $(event.target).is(delegate), in the scope of the jQuery-object for event.target
  6094. // provides triggerEvent(type: String, target: Element) to trigger delegated events
  6095. ;(function($) {
  6096. $.each({
  6097. focus: 'focusin',
  6098. blur: 'focusout'
  6099. }, function( original, fix ){
  6100. $.event.special[fix] = {
  6101. setup:function() {
  6102. if ( $.browser.msie ) return false;
  6103. this.addEventListener( original, $.event.special[fix].handler, true );
  6104. },
  6105. teardown:function() {
  6106. if ( $.browser.msie ) return false;
  6107. this.removeEventListener( original,
  6108. $.event.special[fix].handler, true );
  6109. },
  6110. handler: function(e) {
  6111. arguments[0] = $.event.fix(e);
  6112. arguments[0].type = fix;
  6113. return $.event.handle.apply(this, arguments);
  6114. }
  6115. };
  6116. });
  6117. $.extend($.fn, {
  6118. delegate: function(type, delegate, handler) {
  6119. return this.bind(type, function(event) {
  6120. var target = $(event.target);
  6121. if (target.is(delegate)) {
  6122. return handler.apply(target, arguments);
  6123. }
  6124. });
  6125. },
  6126. triggerEvent: function(type, target) {
  6127. return this.triggerHandler(type, [jQuery.event.fix({ type: type, target: target })]);
  6128. }
  6129. })
  6130. })(jQuery);
  6131. /*
  6132. Copyright 2008-2009 University of Cambridge
  6133. Copyright 2008-2009 University of Toronto
  6134. Copyright 2007-2009 University of California, Berkeley
  6135. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  6136. BSD license. You may not use this file except in compliance with one these
  6137. Licenses.
  6138. You may obtain a copy of the ECL 2.0 License and BSD License at
  6139. https://source.fluidproject.org/svn/LICENSE.txt
  6140. */
  6141. // Declare dependencies.
  6142. /*global jQuery, YAHOO, opera*/
  6143. var fluid_1_1 = fluid_1_1 || {};
  6144. var fluid = fluid || fluid_1_1;
  6145. (function ($, fluid) {
  6146. fluid.version = "Infusion 1.1.1";
  6147. /**
  6148. * Causes an error message to be logged to the console and a real runtime error to be thrown.
  6149. *
  6150. * @param {String|Error} message the error message to log
  6151. */
  6152. fluid.fail = function (message) {
  6153. fluid.setLogging(true);
  6154. fluid.log(message.message? message.message : message);
  6155. throw new Error(message);
  6156. //message.fail(); // Intentionally cause a browser error by invoking a nonexistent function.
  6157. };
  6158. /**
  6159. * Wraps an object in a jQuery if it isn't already one. This function is useful since
  6160. * it ensures to wrap a null or otherwise falsy argument to itself, rather than the
  6161. * often unhelpful jQuery default of returning the overall document node.
  6162. *
  6163. * @param {Object} obj the object to wrap in a jQuery
  6164. */
  6165. fluid.wrap = function (obj) {
  6166. return ((!obj || obj.jquery) ? obj : $(obj));
  6167. };
  6168. /**
  6169. * If obj is a jQuery, this function will return the first DOM element within it.
  6170. *
  6171. * @param {jQuery} obj the jQuery instance to unwrap into a pure DOM element
  6172. */
  6173. fluid.unwrap = function (obj) {
  6174. return obj && obj.jquery && obj.length === 1 ? obj[0] : obj; // Unwrap the element if it's a jQuery.
  6175. };
  6176. /**
  6177. * Searches through the supplied object for the first value which matches the one supplied.
  6178. * @param obj {Object} the Object to be searched through
  6179. * @param value {Object} the value to be found. This will be compared against the object's
  6180. * member using === equality.
  6181. * @return {String} The first key whose value matches the one supplied, or <code>null</code> if no
  6182. * such key is found.
  6183. */
  6184. fluid.keyForValue = function (obj, value) {
  6185. for (var key in obj) {
  6186. if (obj[key] === value) {
  6187. return key;
  6188. }
  6189. }
  6190. return null;
  6191. };
  6192. /**
  6193. * This method is now deprecated and will be removed in a future release of Infusion.
  6194. * See fluid.keyForValue instead.
  6195. */
  6196. fluid.findKeyInObject = fluid.keyForValue;
  6197. /**
  6198. * Clears an object or array of its contents. For objects, each property is deleted.
  6199. *
  6200. * @param {Object|Array} target the target to be cleared
  6201. */
  6202. fluid.clear = function (target) {
  6203. if (target instanceof Array) {
  6204. target.length = 0;
  6205. }
  6206. else {
  6207. for (var i in target) {
  6208. delete target[i];
  6209. }
  6210. }
  6211. };
  6212. // Framework and instantiation functions.
  6213. /**
  6214. * Fetches a single container element and returns it as a jQuery.
  6215. *
  6216. * @param {String||jQuery||element} an id string, a single-element jQuery, or a DOM element specifying a unique container
  6217. * @return a single-element jQuery of container
  6218. */
  6219. fluid.container = function (containerSpec) {
  6220. var container = containerSpec;
  6221. if (typeof containerSpec === "string" ||
  6222. containerSpec.nodeType && (containerSpec.nodeType === 1 || containerSpec.nodeType === 9)) {
  6223. container = $(containerSpec);
  6224. }
  6225. // Throw an exception if we've got more or less than one element.
  6226. if (!container || !container.jquery || container.length !== 1) {
  6227. if (typeof(containerSpec) !== "string") {
  6228. containerSpec = container.selector;
  6229. }
  6230. fluid.fail({
  6231. name: "NotOne",
  6232. message: "A single container element was not found for selector " + containerSpec
  6233. });
  6234. }
  6235. return container;
  6236. };
  6237. /**
  6238. * Retreives and stores a component's default settings centrally.
  6239. * @param {boolean} (options) if true, manipulate a global option (for the head
  6240. * component) rather than instance options.
  6241. * @param {String} componentName the name of the component
  6242. * @param {Object} (optional) an container of key/value pairs to set
  6243. *
  6244. */
  6245. var defaultsStore = {};
  6246. var globalDefaultsStore = {};
  6247. fluid.defaults = function () {
  6248. var offset = 0;
  6249. var store = defaultsStore;
  6250. if (typeof arguments[0] === "boolean") {
  6251. store = globalDefaultsStore;
  6252. offset = 1;
  6253. }
  6254. var componentName = arguments[offset];
  6255. var defaultsObject = arguments[offset + 1];
  6256. if (defaultsObject !== undefined) {
  6257. store[componentName] = defaultsObject;
  6258. return defaultsObject;
  6259. }
  6260. return store[componentName];
  6261. };
  6262. /**
  6263. * Creates a new DOM Binder instance, used to locate elements in the DOM by name.
  6264. *
  6265. * @param {Object} container the root element in which to locate named elements
  6266. * @param {Object} selectors a collection of named jQuery selectors
  6267. */
  6268. fluid.createDomBinder = function (container, selectors) {
  6269. var cache = {}, that = {};
  6270. function cacheKey(name, thisContainer) {
  6271. return $.data(fluid.unwrap(thisContainer)) + "-" + name;
  6272. }
  6273. function record(name, thisContainer, result) {
  6274. cache[cacheKey(name, thisContainer)] = result;
  6275. }
  6276. that.locate = function (name, localContainer) {
  6277. var selector, thisContainer, togo;
  6278. selector = selectors[name];
  6279. thisContainer = localContainer? localContainer: container;
  6280. if (!thisContainer) {
  6281. fluid.fail("DOM binder invoked for selector " + name + " without container");
  6282. }
  6283. if (!selector) {
  6284. return thisContainer;
  6285. }
  6286. if (typeof(selector) === "function") {
  6287. togo = $(selector.call(null, fluid.unwrap(thisContainer)));
  6288. } else {
  6289. togo = $(selector, thisContainer);
  6290. }
  6291. if (togo.get(0) === document) {
  6292. togo = [];
  6293. //fluid.fail("Selector " + name + " with value " + selectors[name] +
  6294. // " did not find any elements with container " + fluid.dumpEl(container));
  6295. }
  6296. if (!togo.selector) {
  6297. togo.selector = selector;
  6298. togo.context = thisContainer;
  6299. }
  6300. togo.selectorName = name;
  6301. record(name, thisContainer, togo);
  6302. return togo;
  6303. };
  6304. that.fastLocate = function (name, localContainer) {
  6305. var thisContainer = localContainer? localContainer: container;
  6306. var key = cacheKey(name, thisContainer);
  6307. var togo = cache[key];
  6308. return togo? togo : that.locate(name, localContainer);
  6309. };
  6310. that.clear = function () {
  6311. cache = {};
  6312. };
  6313. that.refresh = function (names, localContainer) {
  6314. var thisContainer = localContainer? localContainer: container;
  6315. if (typeof names === "string") {
  6316. names = [names];
  6317. }
  6318. if (thisContainer.length === undefined) {
  6319. thisContainer = [thisContainer];
  6320. }
  6321. for (var i = 0; i < names.length; ++ i) {
  6322. for (var j = 0; j < thisContainer.length; ++ j) {
  6323. that.locate(names[i], thisContainer[j]);
  6324. }
  6325. }
  6326. };
  6327. return that;
  6328. };
  6329. /**
  6330. * Attaches the user's listeners to a set of events.
  6331. *
  6332. * @param {Object} events a collection of named event firers
  6333. * @param {Object} listeners optional listeners to add
  6334. */
  6335. fluid.mergeListeners = function (events, listeners) {
  6336. if (listeners) {
  6337. for (var key in listeners) {
  6338. var value = listeners[key];
  6339. var keydot = key.indexOf(".");
  6340. var namespace;
  6341. if (keydot !== -1) {
  6342. namespace = key.substring(keydot + 1);
  6343. key = key.substring(0, keydot);
  6344. }
  6345. if (!events[key]) {
  6346. events[key] = fluid.event.getEventFirer();
  6347. }
  6348. var firer = events[key];
  6349. if (typeof(value) === "function") {
  6350. firer.addListener(value, namespace);
  6351. }
  6352. else if (value && typeof value.length === "number") {
  6353. for (var i = 0; i < value.length; ++ i) {
  6354. firer.addListener(value[i], namespace);
  6355. }
  6356. }
  6357. }
  6358. }
  6359. };
  6360. /**
  6361. * Sets up a component's declared events.
  6362. * Events are specified in the options object by name. There are three different types of events that can be
  6363. * specified:
  6364. * 1. an ordinary multicast event, specified by "null.
  6365. * 2. a unicast event, which allows only one listener to be registered
  6366. * 3. a preventable event
  6367. *
  6368. * @param {Object} that the component
  6369. * @param {Object} options the component's options structure, containing the declared event names and types
  6370. */
  6371. fluid.instantiateFirers = function (that, options) {
  6372. that.events = {};
  6373. if (options.events) {
  6374. for (var event in options.events) {
  6375. var eventType = options.events[event];
  6376. that.events[event] = fluid.event.getEventFirer(eventType === "unicast", eventType === "preventable");
  6377. }
  6378. }
  6379. fluid.mergeListeners(that.events, options.listeners);
  6380. };
  6381. /**
  6382. * Merges the component's declared defaults, as obtained from fluid.defaults(),
  6383. * with the user's specified overrides.
  6384. *
  6385. * @param {Object} that the instance to attach the options to
  6386. * @param {String} componentName the unique "name" of the component, which will be used
  6387. * to fetch the default options from store. By recommendation, this should be the global
  6388. * name of the component's creator function.
  6389. * @param {Object} userOptions the user-specified configuration options for this component
  6390. */
  6391. fluid.mergeComponentOptions = function (that, componentName, userOptions) {
  6392. var defaults = fluid.defaults(componentName);
  6393. that.options = fluid.merge(defaults? defaults.mergePolicy: null, {}, defaults, userOptions);
  6394. };
  6395. /** Expect that an output from the DOM binder has resulted in a non-empty set of
  6396. * results. If none are found, this function will fail with a diagnostic message,
  6397. * with the supplied message prepended.
  6398. */
  6399. fluid.expectFilledSelector = function (result, message) {
  6400. if (result && result.length === 0 && result.jquery) {
  6401. fluid.fail(message + ": selector \"" + result.selector + "\" with name " + result.selectorName +
  6402. " returned no results in context " + fluid.dumpEl(result.context));
  6403. }
  6404. };
  6405. /**
  6406. * The central initialiation method called as the first act of every Fluid
  6407. * component. This function automatically merges user options with defaults,
  6408. * attaches a DOM Binder to the instance, and configures events.
  6409. *
  6410. * @param {String} componentName The unique "name" of the component, which will be used
  6411. * to fetch the default options from store. By recommendation, this should be the global
  6412. * name of the component's creator function.
  6413. * @param {jQueryable} container A specifier for the single root "container node" in the
  6414. * DOM which will house all the markup for this component.
  6415. * @param {Object} userOptions The configuration options for this component.
  6416. */
  6417. fluid.initView = function (componentName, container, userOptions) {
  6418. var that = {};
  6419. fluid.expectFilledSelector(container, "Error instantiating component with name \"" + componentName);
  6420. fluid.mergeComponentOptions(that, componentName, userOptions);
  6421. if (container) {
  6422. that.container = fluid.container(container);
  6423. fluid.initDomBinder(that);
  6424. }
  6425. fluid.instantiateFirers(that, that.options);
  6426. return that;
  6427. };
  6428. /** A special "marker object" which is recognised as one of the arguments to
  6429. * fluid.initSubcomponents. This object is recognised by reference equality -
  6430. * where it is found, it is replaced in the actual argument position supplied
  6431. * to the specific subcomponent instance, with the particular options block
  6432. * for that instance attached to the overall "that" object.
  6433. */
  6434. fluid.COMPONENT_OPTIONS = {};
  6435. /** Another special "marker object" representing that a distinguished
  6436. * (probably context-dependent) value should be substituted.
  6437. */
  6438. fluid.VALUE = {};
  6439. /** Construct a dummy or "placeholder" subcomponent, that optionally provides empty
  6440. * implementations for a set of methods.
  6441. */
  6442. fluid.emptySubcomponent = function (options) {
  6443. var that = {};
  6444. options = $.makeArray(options);
  6445. for (var i = 0; i < options.length; ++ i) {
  6446. that[options[i]] = function () {};
  6447. }
  6448. return that;
  6449. };
  6450. fluid.initSubcomponent = function (that, className, args) {
  6451. return fluid.initSubcomponents(that, className, args)[0];
  6452. };
  6453. /** Initialise all the "subcomponents" which are configured to be attached to
  6454. * the supplied top-level component, which share a particular "class name".
  6455. * @param {Component} that The top-level component for which sub-components are
  6456. * to be instantiated. It contains specifications for these subcomponents in its
  6457. * <code>options</code> structure.
  6458. * @param {String} className The "class name" or "category" for the subcomponents to
  6459. * be instantiated. A class name specifies an overall "function" for a class of
  6460. * subcomponents and represents a category which accept the same signature of
  6461. * instantiation arguments.
  6462. * @param {Array of Object} args The instantiation arguments to be passed to each
  6463. * constructed subcomponent. These will typically be members derived from the
  6464. * top-level <code>that</code> or perhaps globally discovered from elsewhere. One
  6465. * of these arguments may be <code>fluid.COMPONENT_OPTIONS</code> in which case this
  6466. * placeholder argument will be replaced by instance-specific options configured
  6467. * into the member of the top-level <code>options</code> structure named for the
  6468. * <code>className</code>
  6469. * @return {Array of Object} The instantiated subcomponents, one for each member
  6470. * of <code>that.options[className]</code>.
  6471. */
  6472. fluid.initSubcomponents = function (that, className, args) {
  6473. var entry = that.options[className];
  6474. if (!entry) {
  6475. return;
  6476. }
  6477. var entries = $.makeArray(entry);
  6478. var optindex = -1;
  6479. var togo = [];
  6480. args = $.makeArray(args);
  6481. for (var i = 0; i < args.length; ++ i) {
  6482. if (args[i] === fluid.COMPONENT_OPTIONS) {
  6483. optindex = i;
  6484. }
  6485. }
  6486. for (i = 0; i < entries.length; ++ i) {
  6487. entry = entries[i];
  6488. if (optindex !== -1 && entry.options) {
  6489. args[optindex] = entry.options;
  6490. }
  6491. if (typeof(entry) !== "function") {
  6492. var entryType = typeof(entry) === "string"? entry : entry.type;
  6493. var globDef = fluid.defaults(true, entryType);
  6494. fluid.merge("reverse", that.options, globDef);
  6495. togo[i] = entryType === "fluid.emptySubcomponent"?
  6496. fluid.emptySubcomponent(entry.options) :
  6497. fluid.invokeGlobalFunction(entryType, args, {fluid: fluid});
  6498. }
  6499. else {
  6500. togo[i] = entry.apply(null, args);
  6501. }
  6502. var returnedOptions = togo[i]? togo[i].returnedOptions : null;
  6503. if (returnedOptions) {
  6504. fluid.merge(that.options.mergePolicy, that.options, returnedOptions);
  6505. if (returnedOptions.listeners) {
  6506. fluid.mergeListeners(that.events, returnedOptions.listeners);
  6507. }
  6508. }
  6509. }
  6510. return togo;
  6511. };
  6512. /**
  6513. * Creates a new DOM Binder instance for the specified component and mixes it in.
  6514. *
  6515. * @param {Object} that the component instance to attach the new DOM Binder to
  6516. */
  6517. fluid.initDomBinder = function (that) {
  6518. that.dom = fluid.createDomBinder(that.container, that.options.selectors);
  6519. that.locate = that.dom.locate;
  6520. };
  6521. /** Returns true if the argument is a primitive type **/
  6522. fluid.isPrimitive = function (value) {
  6523. var valueType = typeof(value);
  6524. return !value || valueType === "string" || valueType === "boolean" || valueType === "number";
  6525. };
  6526. function mergeImpl(policy, basePath, target, source) {
  6527. var thisPolicy = policy && typeof(policy) !== "string"? policy[basePath] : policy;
  6528. if (typeof(thisPolicy) === "function") {
  6529. thisPolicy.apply(null, target, source);
  6530. return target;
  6531. }
  6532. if (thisPolicy === "replace") {
  6533. fluid.clear(target);
  6534. }
  6535. for (var name in source) {
  6536. var path = (basePath? basePath + ".": "") + name;
  6537. var thisTarget = target[name];
  6538. var thisSource = source[name];
  6539. var primitiveTarget = fluid.isPrimitive(thisTarget);
  6540. if (thisSource !== undefined) {
  6541. if (thisSource !== null && typeof thisSource === 'object' &&
  6542. !thisSource.nodeType && !thisSource.jquery && thisSource !== fluid.VALUE) {
  6543. if (primitiveTarget) {
  6544. target[name] = thisTarget = thisSource instanceof Array? [] : {};
  6545. }
  6546. mergeImpl(policy, path, thisTarget, thisSource);
  6547. }
  6548. else {
  6549. if (thisTarget === null || thisTarget === undefined || thisPolicy !== "reverse") {
  6550. target[name] = thisSource;
  6551. }
  6552. }
  6553. }
  6554. }
  6555. return target;
  6556. }
  6557. /** Merge a collection of options structures onto a target, following an optional policy.
  6558. * This function is typically called automatically, as a result of an invocation of
  6559. * <code>fluid.iniView</code>. The behaviour of this function is explained more fully on
  6560. * the page http://wiki.fluidproject.org/display/fluid/Options+Merging+for+Fluid+Components .
  6561. * @param policy {Object/String} A "policy object" specifiying the type of merge to be performed.
  6562. * If policy is of type {String} it should take on the value "reverse" or "replace" representing
  6563. * a static policy. If it is an
  6564. * Object, it should contain a mapping of EL paths onto these String values, representing a
  6565. * fine-grained policy. If it is an Object, the values may also themselves be EL paths
  6566. * representing that a default value is to be taken from that path.
  6567. * @param target {Object} The options structure which is to be modified by receiving the merge results.
  6568. * @param options1, options2, .... {Object} an arbitrary list of options structure which are to
  6569. * be merged "on top of" the <code>target</code>. These will not be modified.
  6570. */
  6571. fluid.merge = function (policy, target) {
  6572. var path = "";
  6573. for (var i = 2; i < arguments.length; ++i) {
  6574. var source = arguments[i];
  6575. if (source !== null && source !== undefined) {
  6576. mergeImpl(policy, path, target, source);
  6577. }
  6578. }
  6579. if (policy && typeof(policy) !== "string") {
  6580. for (var key in policy) {
  6581. var elrh = policy[key];
  6582. if (typeof(elrh) === 'string' && elrh !== "replace") {
  6583. var oldValue = fluid.model.getBeanValue(target, key);
  6584. if (oldValue === null || oldValue === undefined) {
  6585. var value = fluid.model.getBeanValue(target, elrh);
  6586. fluid.model.setBeanValue(target, key, value);
  6587. }
  6588. }
  6589. }
  6590. }
  6591. return target;
  6592. };
  6593. /** Performs a deep copy (clone) of its argument **/
  6594. fluid.copy = function (tocopy) {
  6595. if (fluid.isPrimitive(tocopy)) {
  6596. return tocopy;
  6597. }
  6598. return $.extend(true, typeof(tocopy.length) === "number"? [] : {}, tocopy);
  6599. };
  6600. /**
  6601. * Allows for the calling of a function from an EL expression "functionPath", with the arguments "args", scoped to an framework version "environment".
  6602. * @param {Object} functionPath - An EL expression
  6603. * @param {Object} args - An array of arguments to be applied to the function, specified in functionPath
  6604. * @param {Object} environment - (optional) The object to scope the functionPath to (typically the framework root for version control)
  6605. */
  6606. fluid.invokeGlobalFunction = function (functionPath, args, environment) {
  6607. var func = fluid.model.getBeanValue(window, functionPath, environment);
  6608. if (!func) {
  6609. fluid.fail("Error invoking global function: " + functionPath + " could not be located");
  6610. } else {
  6611. return func.apply(null, args);
  6612. }
  6613. };
  6614. // The Model Events system.
  6615. fluid.event = {};
  6616. var fluid_guid = 1;
  6617. /** Construct an "event firer" object which can be used to register and deregister
  6618. * listeners, to which "events" can be fired. These events consist of an arbitrary
  6619. * function signature. General documentation on the Fluid events system is at
  6620. * http://wiki.fluidproject.org/display/fluid/The+Fluid+Event+System .
  6621. * @param {Boolean} unicast If <code>true</code>, this is a "unicast" event which may only accept
  6622. * a single listener.
  6623. * @param {Boolean} preventable If <code>true</code> the return value of each handler will
  6624. * be checked for <code>false</code> in which case further listeners will be shortcircuited, and this
  6625. * will be the return value of fire()
  6626. */
  6627. fluid.event.getEventFirer = function (unicast, preventable) {
  6628. var log = fluid.log;
  6629. var listeners = {};
  6630. return {
  6631. addListener: function (listener, namespace, predicate) {
  6632. if (!listener) {
  6633. return;
  6634. }
  6635. if (unicast) {
  6636. namespace = "unicast";
  6637. }
  6638. if (!namespace) {
  6639. if (!listener.$$guid) {
  6640. listener.$$guid = fluid_guid++;
  6641. }
  6642. namespace = listener.$$guid;
  6643. }
  6644. listeners[namespace] = {listener: listener, predicate: predicate};
  6645. },
  6646. removeListener: function (listener) {
  6647. if (typeof(listener) === 'string') {
  6648. delete listeners[listener];
  6649. }
  6650. else if (typeof(listener) === 'object' && listener.$$guid) {
  6651. delete listeners[listener.$$guid];
  6652. }
  6653. },
  6654. fire: function () {
  6655. for (var i in listeners) {
  6656. var lisrec = listeners[i];
  6657. var listener = lisrec.listener;
  6658. if (lisrec.predicate && !lisrec.predicate(listener, arguments)) {
  6659. continue;
  6660. }
  6661. try {
  6662. var ret = listener.apply(null, arguments);
  6663. if (preventable && ret === false) {
  6664. return false;
  6665. }
  6666. }
  6667. catch (e) {
  6668. log("FireEvent received exception " + e.message + " e " + e + " firing to listener " + i);
  6669. throw (e);
  6670. }
  6671. }
  6672. }
  6673. };
  6674. };
  6675. // Model functions
  6676. fluid.model = {};
  6677. /** Copy a source "model" onto a target **/
  6678. fluid.model.copyModel = function (target, source) {
  6679. fluid.clear(target);
  6680. $.extend(true, target, source);
  6681. };
  6682. /** Parse an EL expression separated by periods (.) into its component segments.
  6683. * @param {String} EL The EL expression to be split
  6684. * @return {Array of String} the component path expressions.
  6685. * TODO: This needs to be upgraded to handle (the same) escaping rules (as RSF), so that
  6686. * path segments containing periods and backslashes etc. can be processed.
  6687. */
  6688. fluid.model.parseEL = function (EL) {
  6689. return EL.toString().split('.');
  6690. };
  6691. fluid.model.composePath = function (prefix, suffix) {
  6692. return prefix === ""? suffix : prefix + "." + suffix;
  6693. };
  6694. fluid.model.setBeanValue = function (root, EL, newValue) {
  6695. var segs = fluid.model.parseEL(EL);
  6696. for (var i = 0; i < segs.length - 1; i += 1) {
  6697. if (!root[segs[i]]) {
  6698. root[segs[i]] = {};
  6699. }
  6700. root = root[segs[i]];
  6701. }
  6702. root[segs[segs.length - 1]] = newValue;
  6703. };
  6704. /** Evaluates an EL expression by fetching a dot-separated list of members
  6705. * recursively from a provided root.
  6706. * @param root The root data structure in which the EL expression is to be evaluated
  6707. * @param {string} EL The EL expression to be evaluated
  6708. * @param environment An optional "environment" which, if it contains any members
  6709. * at top level, will take priority over the root data structure.
  6710. * @return The fetched data value.
  6711. */
  6712. fluid.model.getBeanValue = function (root, EL, environment) {
  6713. if (EL === "" || EL === null || EL === undefined) {
  6714. return root;
  6715. }
  6716. var segs = fluid.model.parseEL(EL);
  6717. for (var i = 0; i < segs.length; ++i) {
  6718. if (!root) {
  6719. return root;
  6720. }
  6721. var segment = segs[i];
  6722. if (environment && environment[segment]) {
  6723. root = environment[segment];
  6724. environment = null;
  6725. }
  6726. else {
  6727. root = root[segment];
  6728. }
  6729. }
  6730. return root;
  6731. };
  6732. // Logging
  6733. var logging;
  6734. /** method to allow user to enable logging (off by default) */
  6735. fluid.setLogging = function (enabled) {
  6736. if (typeof enabled === "boolean") {
  6737. logging = enabled;
  6738. } else {
  6739. logging = false;
  6740. }
  6741. };
  6742. /** Log a message to a suitable environmental console. If the standard "console"
  6743. * stream is available, the message will be sent there - otherwise either the
  6744. * YAHOO logger or the Opera "postError" stream will be used. Logging must first
  6745. * be enabled with a call fo the fluid.setLogging(true) function.
  6746. */
  6747. fluid.log = function (str) {
  6748. if (logging) {
  6749. str = new Date().toTimeString() + ": " + str;
  6750. if (typeof(console) !== "undefined") {
  6751. if (console.debug) {
  6752. console.debug(str);
  6753. } else {
  6754. console.log(str);
  6755. }
  6756. }
  6757. else if (typeof(YAHOO) !== "undefined") {
  6758. YAHOO.log(str);
  6759. }
  6760. else if (typeof(opera) !== "undefined") {
  6761. opera.postError(str);
  6762. }
  6763. }
  6764. };
  6765. /**
  6766. * Dumps a DOM element into a readily recognisable form for debugging - produces a
  6767. * "semi-selector" summarising its tag name, class and id, whichever are set.
  6768. *
  6769. * @param {jQueryable} element The element to be dumped
  6770. * @return A string representing the element.
  6771. */
  6772. fluid.dumpEl = function (element) {
  6773. var togo;
  6774. if (!element) {
  6775. return "null";
  6776. }
  6777. if (element.nodeType === 3 || element.nodeType === 8) {
  6778. return "[data: " + element.data + "]";
  6779. }
  6780. if (element.nodeType === 9) {
  6781. return "[document: location " + element.location + "]";
  6782. }
  6783. if (!element.nodeType && typeof element.length === "number") {
  6784. togo = "[";
  6785. for (var i = 0; i < element.length; ++ i) {
  6786. togo += fluid.dumpEl(element[i]);
  6787. if (i < element.length - 1) {
  6788. togo += ", ";
  6789. }
  6790. }
  6791. return togo + "]";
  6792. }
  6793. element = $(element);
  6794. togo = element.get(0).tagName;
  6795. if (element.attr("id")) {
  6796. togo += "#" + element.attr("id");
  6797. }
  6798. if (element.attr("class")) {
  6799. togo += "." + element.attr("class");
  6800. }
  6801. return togo;
  6802. };
  6803. // DOM Utilities.
  6804. /**
  6805. * Finds the nearest ancestor of the element that passes the test
  6806. * @param {Element} element DOM element
  6807. * @param {Function} test A function which takes an element as a parameter and return true or false for some test
  6808. */
  6809. fluid.findAncestor = function (element, test) {
  6810. element = fluid.unwrap(element);
  6811. while (element) {
  6812. if (test(element)) {
  6813. return element;
  6814. }
  6815. element = element.parentNode;
  6816. }
  6817. };
  6818. /**
  6819. * Returns a jQuery object given the id of a DOM node. In the case the element
  6820. * is not found, will return an empty list.
  6821. */
  6822. fluid.jById = function (id, dokkument) {
  6823. dokkument = dokkument && dokkument.nodeType === 9? dokkument : document;
  6824. var element = fluid.byId(id, dokkument);
  6825. var togo = element? $(element) : [];
  6826. togo.selector = "#" + id;
  6827. togo.context = dokkument;
  6828. return togo;
  6829. };
  6830. /**
  6831. * Returns an DOM element quickly, given an id
  6832. *
  6833. * @param {Object} id the id of the DOM node to find
  6834. * @param {Document} dokkument the document in which it is to be found (if left empty, use the current document)
  6835. * @return The DOM element with this id, or null, if none exists in the document.
  6836. */
  6837. fluid.byId = function (id, dokkument) {
  6838. dokkument = dokkument && dokkument.nodeType === 9? dokkument : document;
  6839. var el = dokkument.getElementById(id);
  6840. if (el) {
  6841. if (el.getAttribute("id") !== id) {
  6842. fluid.fail("Problem in document structure - picked up element " +
  6843. fluid.dumpEl(el) +
  6844. " for id " +
  6845. id +
  6846. " without this id - most likely the element has a name which conflicts with this id");
  6847. }
  6848. return el;
  6849. }
  6850. else {
  6851. return null;
  6852. }
  6853. };
  6854. /**
  6855. * Returns the id attribute from a jQuery or pure DOM element.
  6856. *
  6857. * @param {jQuery||Element} element the element to return the id attribute for
  6858. */
  6859. fluid.getId = function (element) {
  6860. return fluid.unwrap(element).getAttribute("id");
  6861. };
  6862. /**
  6863. * Allocate an id to the supplied element if it has none already, by a simple
  6864. * scheme resulting in ids "fluid-id-nnnn" where nnnn is an increasing integer.
  6865. */
  6866. fluid.allocateSimpleId = function (element) {
  6867. element = fluid.unwrap(element);
  6868. if (!element.id) {
  6869. element.id = "fluid-id-" + (fluid_guid++);
  6870. }
  6871. return element.id;
  6872. };
  6873. // Functional programming utilities.
  6874. /** Return a list of objects, transformed by one or more functions. Similar to
  6875. * jQuery.map, only will accept an arbitrary list of transformation functions.
  6876. * @param list {Array} The initial array of objects to be transformed.
  6877. * @param fn1, fn2, etc. {Function} An arbitrary number of optional further arguments,
  6878. * all of type Function, accepting the signature (object, index), where object is the
  6879. * list member to be transformed, and index is its list index. Each function will be
  6880. * applied in turn to each list member, which will be replaced by the return value
  6881. * from the function.
  6882. * @return The finally transformed list, where each member has been replaced by the
  6883. * original member acted on by the function or functions.
  6884. */
  6885. fluid.transform = function (list) {
  6886. var togo = [];
  6887. for (var i = 0; i < list.length; ++ i) {
  6888. var transit = list[i];
  6889. for (var j = 0; j < arguments.length - 1; ++ j) {
  6890. transit = arguments[j + 1](transit, i);
  6891. }
  6892. togo[togo.length] = transit;
  6893. }
  6894. return togo;
  6895. };
  6896. /** Scan through a list of objects, terminating on and returning the first member which
  6897. * matches a predicate function.
  6898. * @param list {Array} The list of objects to be searched.
  6899. * @param fn {Function} A predicate function, acting on a list member. A predicate which
  6900. * returns any value which is not <code>null</code> or <code>undefined</code> will terminate
  6901. * the search. The function accepts (object, index).
  6902. * @param deflt {Object} A value to be returned in the case no predicate function matches
  6903. * a list member. The default will be the natural value of <code>undefined</code>
  6904. * @return The first return value from the predicate function which is not <code>null</code>
  6905. * or <code>undefined</code>
  6906. */
  6907. fluid.find = function (list, fn, deflt) {
  6908. for (var i = 0; i < list.length; ++ i) {
  6909. var transit = fn(list[i], i);
  6910. if (transit !== null && transit !== undefined) {
  6911. return transit;
  6912. }
  6913. }
  6914. return deflt;
  6915. };
  6916. /** Scan through a list of objects, "accumulating" a value over them
  6917. * (may be a straightforward "sum" or some other chained computation).
  6918. * @param list {Array} The list of objects to be accumulated over.
  6919. * @param fn {Function} An "accumulation function" accepting the signature (object, total, index) where
  6920. * object is the list member, total is the "running total" object (which is the return value from the previous function),
  6921. * and index is the index number.
  6922. * @param arg {Object} The initial value for the "running total" object.
  6923. * @return {Object} the final running total object as returned from the final invocation of the function on the last list member.
  6924. */
  6925. fluid.accumulate = function (list, fn, arg) {
  6926. for (var i = 0; i < list.length; ++ i) {
  6927. arg = fn(list[i], arg, i);
  6928. }
  6929. return arg;
  6930. };
  6931. /** Can through a list of objects, removing those which match a predicate. Similar to
  6932. * jQuery.grep, only acts on the list in-place by removal, rather than by creating
  6933. * a new list by inclusion.
  6934. * @param list {Array} The list of objects to be scanned over.
  6935. * @param fn {Function} A predicate function determining whether an element should be
  6936. * removed. This accepts the standard signature (object, index) and returns a "truthy"
  6937. * result in order to determine that the supplied object should be removed from the list.
  6938. * @return The list, transformed by the operation of removing the matched elements. The
  6939. * supplied list is modified by this operation.
  6940. */
  6941. fluid.remove_if = function (list, fn) {
  6942. for (var i = 0; i < list.length; ++ i) {
  6943. if (fn(list[i], i)) {
  6944. list.splice(i, 1);
  6945. --i;
  6946. }
  6947. }
  6948. return list;
  6949. };
  6950. /**
  6951. * Expand a message string with respect to a set of arguments, following a basic
  6952. * subset of the Java MessageFormat rules.
  6953. * http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html
  6954. *
  6955. * The message string is expected to contain replacement specifications such
  6956. * as {0}, {1}, {2}, etc.
  6957. * @param messageString {String} The message key to be expanded
  6958. * @param args {String/Array of String} An array of arguments to be substituted into the message.
  6959. * @return The expanded message string.
  6960. */
  6961. fluid.formatMessage = function (messageString, args) {
  6962. if (!args) {
  6963. return messageString;
  6964. }
  6965. if (typeof(args) === "string") {
  6966. args = [args];
  6967. }
  6968. for (var i = 0; i < args.length; ++ i) {
  6969. messageString = messageString.replace("{" + i + "}", args[i]);
  6970. }
  6971. return messageString;
  6972. };
  6973. /** Converts a data structure consisting of a mapping of keys to message strings,
  6974. * into a "messageLocator" function which maps an array of message codes, to be
  6975. * tried in sequence until a key is found, and an array of substitution arguments,
  6976. * into a substituted message string.
  6977. */
  6978. fluid.messageLocator = function (messageBase) {
  6979. return function (messagecodes, args) {
  6980. if (typeof(messagecodes) === "string") {
  6981. messagecodes = [messagecodes];
  6982. }
  6983. for (var i = 0; i < messagecodes.length; ++ i) {
  6984. var code = messagecodes[i];
  6985. var message = messageBase[code];
  6986. if (message === undefined) {
  6987. continue;
  6988. }
  6989. return fluid.formatMessage(message, args);
  6990. }
  6991. return "[Message string for key " + messagecodes[0] + " not found]";
  6992. };
  6993. };
  6994. // Other useful helpers.
  6995. /**
  6996. * Simple string template system.
  6997. * Takes a template string containing tokens in the form of "%value".
  6998. * Returns a new string with the tokens replaced by the specified values.
  6999. * Keys and values can be of any data type that can be coerced into a string. Arrays will work here as well.
  7000. *
  7001. * @param {String} template a string (can be HTML) that contains tokens embedded into it
  7002. * @param {object} values a collection of token keys and values
  7003. */
  7004. fluid.stringTemplate = function (template, values) {
  7005. var newString = template;
  7006. for (var key in values) {
  7007. if (values.hasOwnProperty(key)) {
  7008. var searchStr = "%" + key;
  7009. newString = newString.replace(searchStr, values[key]);
  7010. }
  7011. }
  7012. return newString;
  7013. };
  7014. })(jQuery, fluid_1_1);
  7015. /*
  7016. Copyright 2008-2009 University of Cambridge
  7017. Copyright 2008-2009 University of Toronto
  7018. Copyright 2007-2009 University of California, Berkeley
  7019. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  7020. BSD license. You may not use this file except in compliance with one these
  7021. Licenses.
  7022. You may obtain a copy of the ECL 2.0 License and BSD License at
  7023. https://source.fluidproject.org/svn/LICENSE.txt
  7024. */
  7025. // Declare dependencies.
  7026. /*global jQuery */
  7027. var fluid_1_1 = fluid_1_1 || {};
  7028. (function ($, fluid) {
  7029. fluid.dom = fluid.dom || {};
  7030. // Node walker function for iterateDom.
  7031. var getNextNode = function (iterator) {
  7032. if (iterator.node.firstChild) {
  7033. iterator.node = iterator.node.firstChild;
  7034. iterator.depth += 1;
  7035. return iterator;
  7036. }
  7037. while (iterator.node) {
  7038. if (iterator.node.nextSibling) {
  7039. iterator.node = iterator.node.nextSibling;
  7040. return iterator;
  7041. }
  7042. iterator.node = iterator.node.parentNode;
  7043. iterator.depth -= 1;
  7044. }
  7045. return iterator;
  7046. };
  7047. /**
  7048. * Walks the DOM, applying the specified acceptor function to each element.
  7049. * There is a special case for the acceptor, allowing for quick deletion of elements and their children.
  7050. * Return "delete" from your acceptor function if you want to delete the element in question.
  7051. * Return "stop" to terminate iteration.
  7052. *
  7053. * @param {Element} node the node to start walking from
  7054. * @param {Function} acceptor the function to invoke with each DOM element
  7055. * @param {Boolean} allnodes Use <code>true</code> to call acceptor on all nodes,
  7056. * rather than just element nodes (type 1)
  7057. */
  7058. fluid.dom.iterateDom = function (node, acceptor, allNodes) {
  7059. var currentNode = {node: node, depth: 0};
  7060. var prevNode = node;
  7061. var condition;
  7062. while (currentNode.node !== null && currentNode.depth >= 0 && currentNode.depth < fluid.dom.iterateDom.DOM_BAIL_DEPTH) {
  7063. condition = null;
  7064. if (currentNode.node.nodeType === 1 || allNodes) {
  7065. condition = acceptor(currentNode.node, currentNode.depth);
  7066. }
  7067. if (condition) {
  7068. if (condition === "delete") {
  7069. currentNode.node.parentNode.removeChild(currentNode.node);
  7070. currentNode.node = prevNode;
  7071. }
  7072. else if (condition === "stop") {
  7073. return currentNode.node;
  7074. }
  7075. }
  7076. prevNode = currentNode.node;
  7077. currentNode = getNextNode(currentNode);
  7078. }
  7079. };
  7080. // Work around IE circular DOM issue. This is the default max DOM depth on IE.
  7081. // http://msdn2.microsoft.com/en-us/library/ms761392(VS.85).aspx
  7082. fluid.dom.iterateDom.DOM_BAIL_DEPTH = 256;
  7083. /**
  7084. * Returns the absolute position of a supplied DOM node in pixels.
  7085. * Implementation taken from quirksmode http://www.quirksmode.org/js/findpos.html
  7086. */
  7087. fluid.dom.computeAbsolutePosition = function (element) {
  7088. var curleft = 0, curtop = 0;
  7089. if (element.offsetParent) {
  7090. do {
  7091. curleft += element.offsetLeft;
  7092. curtop += element.offsetTop;
  7093. element = element.offsetParent;
  7094. } while (element);
  7095. return [curleft, curtop];
  7096. }
  7097. };
  7098. /**
  7099. * Checks if the sepcified container is actually the parent of containee.
  7100. *
  7101. * @param {Element} container the potential parent
  7102. * @param {Element} containee the child in question
  7103. */
  7104. fluid.dom.isContainer = function (container, containee) {
  7105. for (; containee; containee = containee.parentNode) {
  7106. if (container === containee) {
  7107. return true;
  7108. }
  7109. }
  7110. return false;
  7111. };
  7112. /**
  7113. * Inserts newChild as the next sibling of refChild.
  7114. * @param {Object} newChild
  7115. * @param {Object} refChild
  7116. */
  7117. fluid.dom.insertAfter = function (newChild, refChild) {
  7118. var nextSib = refChild.nextSibling;
  7119. if (!nextSib) {
  7120. refChild.parentNode.appendChild(newChild);
  7121. }
  7122. else {
  7123. refChild.parentNode.insertBefore(newChild, nextSib);
  7124. }
  7125. };
  7126. // The following two functions taken from http://developer.mozilla.org/En/Whitespace_in_the_DOM
  7127. /**
  7128. * Determine whether a node's text content is entirely whitespace.
  7129. *
  7130. * @param node A node implementing the |CharacterData| interface (i.e.,
  7131. * a |Text|, |Comment|, or |CDATASection| node
  7132. * @return True if all of the text content of |nod| is whitespace,
  7133. * otherwise false.
  7134. */
  7135. fluid.dom.isWhitespaceNode = function (node) {
  7136. // Use ECMA-262 Edition 3 String and RegExp features
  7137. return !(/[^\t\n\r ]/.test(node.data));
  7138. };
  7139. /**
  7140. * Determine if a node should be ignored by the iterator functions.
  7141. *
  7142. * @param nod An object implementing the DOM1 |Node| interface.
  7143. * @return true if the node is:
  7144. * 1) A |Text| node that is all whitespace
  7145. * 2) A |Comment| node
  7146. * and otherwise false.
  7147. */
  7148. fluid.dom.isIgnorableNode = function (node) {
  7149. return (node.nodeType === 8) || // A comment node
  7150. ((node.nodeType === 3) && fluid.dom.isWhitespaceNode(node)); // a text node, all ws
  7151. };
  7152. /** Return the element text from the supplied DOM node as a single String */
  7153. fluid.dom.getElementText = function(element) {
  7154. var nodes = element.childNodes;
  7155. var text = "";
  7156. for (var i = 0; i < nodes.length; ++ i) {
  7157. var child = nodes[i];
  7158. if (child.nodeType == 3) {
  7159. text = text + child.nodeValue;
  7160. }
  7161. }
  7162. return text;
  7163. };
  7164. /**
  7165. * Cleanse the children of a DOM node by removing all <script> tags.
  7166. * This is necessary to prevent the possibility that these blocks are
  7167. * reevaluated if the node were reattached to the document.
  7168. */
  7169. fluid.dom.cleanseScripts = function (element) {
  7170. var cleansed = $.data(element, fluid.dom.cleanseScripts.MARKER);
  7171. if (!cleansed) {
  7172. fluid.dom.iterateDom(element, function (node) {
  7173. return node.tagName.toLowerCase() === "script"? "delete" : null;
  7174. });
  7175. $.data(element, fluid.dom.cleanseScripts.MARKER, true);
  7176. }
  7177. };
  7178. fluid.dom.cleanseScripts.MARKER = "fluid-scripts-cleansed";
  7179. })(jQuery, fluid_1_1);
  7180. /*
  7181. Copyright 2008-2009 University of Cambridge
  7182. Copyright 2008-2009 University of Toronto
  7183. Copyright 2007-2009 University of California, Berkeley
  7184. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  7185. BSD license. You may not use this file except in compliance with one these
  7186. Licenses.
  7187. You may obtain a copy of the ECL 2.0 License and BSD License at
  7188. https://source.fluidproject.org/svn/LICENSE.txt
  7189. */
  7190. /*global jQuery*/
  7191. /*global fluid_1_1*/
  7192. fluid_1_1 = fluid_1_1 || {};
  7193. (function ($, fluid) {
  7194. fluid.VALUE = {};
  7195. fluid.BINDING_ROOT_KEY = "fluid-binding-root";
  7196. /** Recursively find any data stored under a given name from a node upwards
  7197. * in its DOM hierarchy **/
  7198. fluid.findData = function(elem, name) {
  7199. while (elem) {
  7200. var data = $.data(elem, name);
  7201. if (data) {return data;}
  7202. elem = elem.parentNode;
  7203. }
  7204. };
  7205. fluid.bindFossils = function(node, data, fossils) {
  7206. $.data(node, fluid.BINDING_ROOT_KEY, {data: data, fossils: fossils});
  7207. };
  7208. fluid.findForm = function (node) {
  7209. return fluid.findAncestor(node,
  7210. function(element) {return element.nodeName.toLowerCase() === "form";});
  7211. };
  7212. /** A generalisation of jQuery.val to correctly handle the case of acquiring and
  7213. * setting the value of clustered radio button/checkbox sets, potentially, given
  7214. * a node corresponding to just one element.
  7215. */
  7216. fluid.value = function (nodeIn, newValue) {
  7217. var node = fluid.unwrap(nodeIn);
  7218. var multiple = false;
  7219. if (node.nodeType === undefined && node.length > 1) {
  7220. node = node[0];
  7221. multiple = true;
  7222. }
  7223. var jNode = $(node);
  7224. if ("input" !== node.nodeName.toLowerCase()
  7225. || ! /radio|checkbox/.test(node.type)) {return $(node).val(newValue);}
  7226. var name = node.name;
  7227. if (name === undefined) {
  7228. fluid.fail("Cannot acquire value from node " + fluid.dumpEl(node) + " which does not have name attribute set");
  7229. }
  7230. var elements;
  7231. if (multiple) {
  7232. elements = nodeIn;
  7233. }
  7234. else {
  7235. var elements = document.getElementsByName(name);
  7236. var scope = fluid.findForm(node);
  7237. elements = $.grep(elements,
  7238. function(element) {
  7239. if (element.name !== name) {return false;}
  7240. return !scope || fluid.dom.isContainer(scope, element);
  7241. });
  7242. }
  7243. if (newValue !== undefined) {
  7244. if (typeof(newValue) === "boolean") {
  7245. newValue = (newValue? "true" : "false");
  7246. }
  7247. // jQuery gets this partially right, but when dealing with radio button array will
  7248. // set all of their values to "newValue" rather than setting the checked property
  7249. // of the corresponding control.
  7250. $.each(elements, function() {
  7251. this.checked = (newValue instanceof Array?
  7252. $.inArray(this.value, newValue) !== -1 : newValue === this.value);
  7253. });
  7254. }
  7255. else { // this part jQuery will not do - extracting value from <input> array
  7256. var checked = $.map(elements, function(element) {
  7257. return element.checked? element.value : null;
  7258. });
  7259. return node.type === "radio"? checked[0] : checked;
  7260. }
  7261. };
  7262. /** "Automatically" apply to whatever part of the data model is
  7263. * relevant, the changed value received at the given DOM node*/
  7264. fluid.applyChange = function(node, newValue, applier) {
  7265. node = fluid.unwrap(node);
  7266. if (newValue === undefined) {
  7267. newValue = fluid.value(node);
  7268. }
  7269. if (node.nodeType === undefined && node.length > 0) {node = node[0];} // assume here that they share name and parent
  7270. var root = fluid.findData(node, fluid.BINDING_ROOT_KEY);
  7271. if (!root) {
  7272. fluid.fail("Bound data could not be discovered in any node above " + fluid.dumpEl(node));
  7273. }
  7274. var name = node.name;
  7275. var fossil = root.fossils[name];
  7276. if (!fossil) {
  7277. fluid.fail("No fossil discovered for name " + name + " in fossil record above " + fluid.dumpEl(node));
  7278. }
  7279. if (typeof(fossil.oldvalue) === "boolean") { // deal with the case of an "isolated checkbox"
  7280. newValue = newValue[0]? true: false;
  7281. }
  7282. var EL = root.fossils[name].EL;
  7283. if (applier) {
  7284. applier.fireChangeRequest({path: EL, value: newValue, source: node.id});
  7285. }
  7286. else {
  7287. fluid.model.setBeanValue(root.data, EL, newValue);
  7288. }
  7289. };
  7290. fluid.pathUtil = {};
  7291. var getPathSegmentImpl = function(accept, path, i) {
  7292. var segment = null; // TODO: rewrite this with regexes and replaces
  7293. if (accept) {
  7294. segment = "";
  7295. }
  7296. var escaped = false;
  7297. var limit = path.length;
  7298. for (; i < limit; ++i) {
  7299. var c = path.charAt(i);
  7300. if (!escaped) {
  7301. if (c === '.') {
  7302. break;
  7303. }
  7304. else if (c === '\\') {
  7305. escaped = true;
  7306. }
  7307. else if (segment !== null) {
  7308. segment += c;
  7309. }
  7310. }
  7311. else {
  7312. escaped = false;
  7313. if (segment !== null)
  7314. accept += c;
  7315. }
  7316. }
  7317. if (segment !== null) {
  7318. accept[0] = segment;
  7319. }
  7320. return i;
  7321. };
  7322. var globalAccept = []; // reentrancy risk
  7323. fluid.pathUtil.getPathSegment = function(path, i) {
  7324. getPathSegmentImpl(globalAccept, path, i);
  7325. return globalAccept[0];
  7326. };
  7327. fluid.pathUtil.getHeadPath = function(path) {
  7328. return fluid.pathUtil.getPathSegment(path, 0);
  7329. };
  7330. fluid.pathUtil.getFromHeadPath = function(path) {
  7331. var firstdot = getPathSegmentImpl(null, path, 0);
  7332. return firstdot === path.length ? null
  7333. : path.substring(firstdot + 1);
  7334. };
  7335. function lastDotIndex(path) {
  7336. // TODO: proper escaping rules
  7337. return path.lastIndexOf(".");
  7338. }
  7339. fluid.pathUtil.getToTailPath = function(path) {
  7340. var lastdot = lastDotIndex(path);
  7341. return lastdot == -1 ? null : path.substring(0, lastdot);
  7342. };
  7343. /** Returns the very last path component of a bean path */
  7344. fluid.pathUtil.getTailPath = function(path) {
  7345. var lastdot = lastDotIndex(path);
  7346. return fluid.pathUtil.getPathSegment(path, lastdot + 1);
  7347. };
  7348. var composeSegment = function(prefix, toappend) {
  7349. for (var i = 0; i < toappend.length; ++i) {
  7350. var c = toappend.charAt(i);
  7351. if (c === '.' || c === '\\' || c === '}') {
  7352. prefix += '\\';
  7353. }
  7354. prefix += c;
  7355. }
  7356. return prefix;
  7357. };
  7358. /**
  7359. * Compose a prefix and suffix EL path, where the prefix is already escaped.
  7360. * Prefix may be empty, but not null. The suffix will become escaped.
  7361. */
  7362. fluid.pathUtil.composePath = function(prefix, suffix) {
  7363. if (prefix.length !== 0) {
  7364. prefix += '.';
  7365. }
  7366. return composeSegment(prefix, suffix);
  7367. };
  7368. fluid.pathUtil.matchPath = function(spec, path) {
  7369. var togo = "";
  7370. while (true) {
  7371. if (!spec) {break;}
  7372. if (!path) {return null;}
  7373. var spechead = fluid.pathUtil.getHeadPath(spec);
  7374. var pathhead = fluid.pathUtil.getHeadPath(path);
  7375. // if we fail to match on a specific component, fail.
  7376. if (spechead !== "*" && spechead !== pathhead) {
  7377. return null;
  7378. }
  7379. togo = fluid.pathUtil.composePath(togo, pathhead);
  7380. spec = fluid.pathUtil.getFromHeadPath(spec);
  7381. path = fluid.pathUtil.getFromHeadPath(path);
  7382. }
  7383. return togo;
  7384. };
  7385. fluid.model.applyChangeRequest = function(model, request) {
  7386. if (request.type === "ADD") {
  7387. fluid.model.setBeanValue(model, request.path, request.value);
  7388. }
  7389. else if (request.type === "DELETE") {
  7390. var totail = fluid.pathUtil.getToTailPath(request.path);
  7391. var tail = fluid.pathUtil.getTailPath(request.path);
  7392. var penult = fluid.model.getBeanValue(model, penult);
  7393. delete penult[tail];
  7394. }
  7395. };
  7396. fluid.makeChangeApplier = function(model) {
  7397. var baseEvents = {
  7398. guards: fluid.event.getEventFirer(false, true),
  7399. modelChanged: fluid.event.getEventFirer(false, false)
  7400. };
  7401. var that = {
  7402. model: model
  7403. };
  7404. function makePredicate(listenerMember, requestIndex) {
  7405. return function(listener, args) {
  7406. var changeRequest = args[requestIndex];
  7407. return fluid.pathUtil.matchPath(listener[listenerMember], changeRequest.path);
  7408. };
  7409. }
  7410. function adaptListener(that, name, listenerMember, requestIndex) {
  7411. var predicate = makePredicate(listenerMember, requestIndex);
  7412. that[name] = {
  7413. addListener: function(pathSpec, listener, namespace) {
  7414. listener[listenerMember] = pathSpec;
  7415. baseEvents[name].addListener(listener, namespace, predicate);
  7416. },
  7417. removeListener: function(listener) {
  7418. baseEvents[name].removeListener(listener);
  7419. }
  7420. };
  7421. }
  7422. adaptListener(that, "guards", "guardedPathSpec", 1);
  7423. adaptListener(that, "modelChanged", "triggerPathSpec", 2);
  7424. that.fireChangeRequest = function(changeRequest) {
  7425. if (!changeRequest.type) {
  7426. changeRequest.type = "ADD";
  7427. }
  7428. var prevent = baseEvents.guards.fire(model, changeRequest);
  7429. if (prevent === false) {
  7430. return;
  7431. }
  7432. var oldModel = {};
  7433. fluid.model.copyModel(oldModel, model);
  7434. fluid.model.applyChangeRequest(model, changeRequest);
  7435. baseEvents.modelChanged.fire(model, oldModel, changeRequest);
  7436. };
  7437. that.requestChange = function(path, value, type) {
  7438. var changeRequest = {
  7439. path: path,
  7440. value: value,
  7441. type: type
  7442. };
  7443. that.fireChangeRequest(changeRequest);
  7444. };
  7445. return that;
  7446. };
  7447. fluid.makeSuperApplier = function() {
  7448. var subAppliers = [];
  7449. var that = {};
  7450. that.addSubApplier = function(path, subApplier) {
  7451. subAppliers.push({path: path, subApplier: subApplier});
  7452. };
  7453. that.fireChangeRequest = function(request) {
  7454. for (var i = 0; i < subAppliers.length; ++ i) {
  7455. var path = subAppliers[i].path;
  7456. if (request.path.indexOf(path) === 0) {
  7457. var subpath = request.path.substring(path.length + 1);
  7458. var subRequest = fluid.copy(request);
  7459. subRequest.path = subpath;
  7460. // TODO: Deal with the as yet unsupported case of an EL rvalue DAR
  7461. subAppliers[i].subApplier.fireChangeRequest(subRequest);
  7462. }
  7463. }
  7464. };
  7465. return that;
  7466. };
  7467. fluid.attachModel = function(baseModel, path, model) {
  7468. var segs = fluid.model.parseEL(path);
  7469. for (var i = 0; i < segs.length - 1; ++ i) {
  7470. var seg = segs[i];
  7471. var subModel = baseModel[seg];
  7472. if (!subModel) {
  7473. baseModel[seg] = subModel = {};
  7474. }
  7475. baseModel = subModel;
  7476. }
  7477. baseModel[segs[segs.length - 1]] = model;
  7478. };
  7479. fluid.assembleModel = function (modelSpec) {
  7480. var model = {};
  7481. var superApplier = fluid.makeSuperApplier();
  7482. var togo = {model: model, applier: superApplier};
  7483. for (path in modelSpec) {
  7484. var rec = modelSpec[path];
  7485. fluid.attachModel(model, path, rec.model);
  7486. if (rec.applier) {
  7487. superApplier.addSubApplier(path, rec.applier);
  7488. }
  7489. }
  7490. return togo;
  7491. };
  7492. })(jQuery, fluid_1_1);
  7493. /*
  7494. Copyright 2008-2009 University of Cambridge
  7495. Copyright 2008-2009 University of Toronto
  7496. Copyright 2007-2009 University of California, Berkeley
  7497. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  7498. BSD license. You may not use this file except in compliance with one these
  7499. Licenses.
  7500. You may obtain a copy of the ECL 2.0 License and BSD License at
  7501. https://source.fluidproject.org/svn/LICENSE.txt
  7502. */
  7503. /*global jQuery*/
  7504. var fluid_1_1 = fluid_1_1 || {};
  7505. var fluid = fluid || fluid_1_1;
  7506. (function ($, fluid) {
  7507. // $().fluid("selectable", args)
  7508. // $().fluid("selectable".that()
  7509. // $().fluid("pager.pagerBar", args)
  7510. // $().fluid("reorderer", options)
  7511. /** Create a "bridge" from code written in the Fluid standard "that-ist" style,
  7512. * to the standard JQuery UI plugin architecture specified at http://docs.jquery.com/UI/Guidelines .
  7513. * Every Fluid component corresponding to the top-level standard signature (JQueryable, options)
  7514. * will automatically convert idiomatically to the JQuery UI standard via this adapter.
  7515. * Any return value which is a primitive or array type will become the return value
  7516. * of the "bridged" function - however, where this function returns a general hash
  7517. * (object) this is interpreted as forming part of the Fluid "return that" pattern,
  7518. * and the function will instead be bridged to "return this" as per JQuery standard,
  7519. * permitting chaining to occur. However, as a courtesy, the particular "this" returned
  7520. * will be augmented with a function that() which will allow the original return
  7521. * value to be retrieved if desired.
  7522. * @param {String} name The name under which the "plugin space" is to be injected into
  7523. * JQuery
  7524. * @param {Object} peer The root of the namespace corresponding to the peer object.
  7525. */
  7526. fluid.thatistBridge = function (name, peer) {
  7527. var togo = function(funcname) {
  7528. var segs = funcname.split(".");
  7529. var move = peer;
  7530. for (var i = 0; i < segs.length; ++i) {
  7531. move = move[segs[i]];
  7532. }
  7533. var args = [this];
  7534. if (arguments.length === 2) {
  7535. args = args.concat($.makeArray(arguments[1]));
  7536. }
  7537. var ret = move.apply(null, args);
  7538. this.that = function() {
  7539. return ret;
  7540. }
  7541. var type = typeof(ret);
  7542. return !ret || type === "string" || type === "number" || type === "boolean"
  7543. || ret && ret.length !== undefined? ret: this;
  7544. };
  7545. $.fn[name] = togo;
  7546. return togo;
  7547. };
  7548. fluid.thatistBridge("fluid", fluid);
  7549. fluid.thatistBridge("fluid_1_1", fluid_1_1);
  7550. // Private constants.
  7551. var NAMESPACE_KEY = "fluid-keyboard-a11y";
  7552. /**
  7553. * Gets stored state from the jQuery instance's data map.
  7554. */
  7555. var getData = function(target, key) {
  7556. var data = $(target).data(NAMESPACE_KEY);
  7557. return data ? data[key] : undefined;
  7558. };
  7559. /**
  7560. * Stores state in the jQuery instance's data map. Unlike jQuery's version,
  7561. * accepts multiple-element jQueries.
  7562. */
  7563. var setData = function(target, key, value) {
  7564. $(target).each(function() {
  7565. var data = $.data(this, NAMESPACE_KEY) || {};
  7566. data[key] = value;
  7567. $.data(this, NAMESPACE_KEY, data);
  7568. });
  7569. };
  7570. /** Global focus manager - makes use of jQuery delegate plugin if present,
  7571. * detecting presence of "focusin" event.
  7572. */
  7573. var lastFocusedElement = "disabled";
  7574. if ($.event.special["focusin"]) {
  7575. lastFocusedElement = null;
  7576. $(document).bind("focusin", function(event){
  7577. lastFocusedElement = event.target;
  7578. });
  7579. }
  7580. fluid.getLastFocusedElement = function () {
  7581. if (lastFocusedElement === "disabled") {
  7582. fluid.fail("Focus manager not enabled - please include jquery.delegate.js or equivalent for support of 'focusin' event");
  7583. }
  7584. return lastFocusedElement;
  7585. }
  7586. /*************************************************************************
  7587. * Tabindex normalization - compensate for browser differences in naming
  7588. * and function of "tabindex" attribute and tabbing order.
  7589. */
  7590. // -- Private functions --
  7591. var normalizeTabindexName = function() {
  7592. return $.browser.msie ? "tabIndex" : "tabindex";
  7593. };
  7594. var canHaveDefaultTabindex = function(elements) {
  7595. if (elements.length <= 0) {
  7596. return false;
  7597. }
  7598. return $(elements[0]).is("a, input, button, select, area, textarea, object");
  7599. };
  7600. var getValue = function(elements) {
  7601. if (elements.length <= 0) {
  7602. return undefined;
  7603. }
  7604. if (!fluid.tabindex.hasAttr(elements)) {
  7605. return canHaveDefaultTabindex(elements) ? Number(0) : undefined;
  7606. }
  7607. // Get the attribute and return it as a number value.
  7608. var value = elements.attr(normalizeTabindexName());
  7609. return Number(value);
  7610. };
  7611. var setValue = function(elements, toIndex) {
  7612. return elements.each(function(i, item) {
  7613. $(item).attr(normalizeTabindexName(), toIndex);
  7614. });
  7615. };
  7616. // -- Public API --
  7617. /**
  7618. * Gets the value of the tabindex attribute for the first item, or sets the tabindex value of all elements
  7619. * if toIndex is specified.
  7620. *
  7621. * @param {String|Number} toIndex
  7622. */
  7623. fluid.tabindex = function(target, toIndex) {
  7624. target = $(target);
  7625. if (toIndex !== null && toIndex !== undefined) {
  7626. return setValue(target, toIndex);
  7627. } else {
  7628. return getValue(target);
  7629. }
  7630. };
  7631. /**
  7632. * Removes the tabindex attribute altogether from each element.
  7633. */
  7634. fluid.tabindex.remove = function(target) {
  7635. target = $(target);
  7636. return target.each(function(i, item) {
  7637. $(item).removeAttr(normalizeTabindexName());
  7638. });
  7639. };
  7640. /**
  7641. * Determines if an element actually has a tabindex attribute present.
  7642. */
  7643. fluid.tabindex.hasAttr = function(target) {
  7644. target = $(target);
  7645. if (target.length <= 0) {
  7646. return false;
  7647. }
  7648. var togo = target.map(
  7649. function() {
  7650. var attributeNode = this.getAttributeNode(normalizeTabindexName());
  7651. return attributeNode ? attributeNode.specified : false;
  7652. }
  7653. );
  7654. return togo.length === 1? togo[0] : togo;
  7655. };
  7656. /**
  7657. * Determines if an element either has a tabindex attribute or is naturally tab-focussable.
  7658. */
  7659. fluid.tabindex.has = function(target) {
  7660. target = $(target);
  7661. return fluid.tabindex.hasAttr(target) || canHaveDefaultTabindex(target);
  7662. };
  7663. var ENABLEMENT_KEY = "enablement";
  7664. /** Queries or sets the enabled status of a control. An activatable node
  7665. * may be "disabled" in which case its keyboard bindings will be inoperable
  7666. * (but still stored) until it is reenabled again.
  7667. */
  7668. fluid.enabled = function(target, state) {
  7669. target = $(target);
  7670. if (state === undefined) {
  7671. return getData(target, ENABLEMENT_KEY) !== false;
  7672. }
  7673. else {
  7674. $("*", target).each(function() {
  7675. if (getData(this, ENABLEMENT_KEY) !== undefined) {
  7676. setData(this, ENABLEMENT_KEY, state);
  7677. }
  7678. else if (/select|textarea|input/i.test(this.nodeName)) {
  7679. $(this).attr("disabled", !state);
  7680. }
  7681. });
  7682. setData(target, ENABLEMENT_KEY, state);
  7683. }
  7684. };
  7685. // Keyboard navigation
  7686. // Public, static constants needed by the rest of the library.
  7687. fluid.a11y = $.a11y || {};
  7688. fluid.a11y.orientation = {
  7689. HORIZONTAL: 0,
  7690. VERTICAL: 1,
  7691. BOTH: 2
  7692. };
  7693. var UP_DOWN_KEYMAP = {
  7694. next: $.ui.keyCode.DOWN,
  7695. previous: $.ui.keyCode.UP
  7696. };
  7697. var LEFT_RIGHT_KEYMAP = {
  7698. next: $.ui.keyCode.RIGHT,
  7699. previous: $.ui.keyCode.LEFT
  7700. };
  7701. // Private functions.
  7702. var unwrap = function(element) {
  7703. return element.jquery ? element[0] : element; // Unwrap the element if it's a jQuery.
  7704. };
  7705. var makeElementsTabFocussable = function(elements) {
  7706. // If each element doesn't have a tabindex, or has one set to a negative value, set it to 0.
  7707. elements.each(function(idx, item) {
  7708. item = $(item);
  7709. if (!item.fluid("tabindex.has") || item.fluid("tabindex") < 0) {
  7710. item.fluid("tabindex", 0);
  7711. }
  7712. });
  7713. };
  7714. // Public API.
  7715. /**
  7716. * Makes all matched elements available in the tab order by setting their tabindices to "0".
  7717. */
  7718. fluid.tabbable = function(target) {
  7719. target = $(target);
  7720. makeElementsTabFocussable(target);
  7721. };
  7722. /***********************************************************************
  7723. * Selectable functionality - geometrising a set of nodes such that they
  7724. * can be navigated (by setting focus) using a set of directional keys
  7725. */
  7726. var CONTEXT_KEY = "selectionContext";
  7727. var NO_SELECTION = -32768;
  7728. var cleanUpWhenLeavingContainer = function(selectionContext) {
  7729. if (selectionContext.options.onLeaveContainer) {
  7730. selectionContext.options.onLeaveContainer(
  7731. selectionContext.selectables[selectionContext.activeItemIndex]);
  7732. } else if (selectionContext.options.onUnselect) {
  7733. selectionContext.options.onUnselect(
  7734. selectionContext.selectables[selectionContext.activeItemIndex]);
  7735. }
  7736. if (!selectionContext.options.rememberSelectionState) {
  7737. selectionContext.activeItemIndex = NO_SELECTION;
  7738. }
  7739. };
  7740. /**
  7741. * Does the work of selecting an element and delegating to the client handler.
  7742. */
  7743. var drawSelection = function(elementToSelect, handler) {
  7744. if (handler) {
  7745. handler(elementToSelect);
  7746. }
  7747. };
  7748. /**
  7749. * Does does the work of unselecting an element and delegating to the client handler.
  7750. */
  7751. var eraseSelection = function(selectedElement, handler) {
  7752. if (handler && selectedElement) {
  7753. handler(selectedElement);
  7754. }
  7755. };
  7756. var unselectElement = function(selectedElement, selectionContext) {
  7757. eraseSelection(selectedElement, selectionContext.options.onUnselect);
  7758. };
  7759. var selectElement = function(elementToSelect, selectionContext) {
  7760. // It's possible that we're being called programmatically, in which case we should clear any previous selection.
  7761. unselectElement(selectionContext.selectedElement(), selectionContext);
  7762. elementToSelect = unwrap(elementToSelect);
  7763. var newIndex = selectionContext.selectables.index(elementToSelect);
  7764. // Next check if the element is a known selectable. If not, do nothing.
  7765. if (newIndex === -1) {
  7766. return;
  7767. }
  7768. // Select the new element.
  7769. selectionContext.activeItemIndex = newIndex;
  7770. drawSelection(elementToSelect, selectionContext.options.onSelect);
  7771. };
  7772. var selectableFocusHandler = function(selectionContext) {
  7773. return function(evt) {
  7774. selectElement(evt.target, selectionContext);
  7775. // Force focus not to bubble on some browsers.
  7776. return evt.stopPropagation();
  7777. };
  7778. };
  7779. var selectableBlurHandler = function(selectionContext) {
  7780. return function(evt) {
  7781. unselectElement(evt.target, selectionContext);
  7782. // Force blur not to bubble on some browsers.
  7783. return evt.stopPropagation();
  7784. };
  7785. };
  7786. var reifyIndex = function(sc_that) {
  7787. var elements = sc_that.selectables;
  7788. if (sc_that.activeItemIndex >= elements.length) {
  7789. sc_that.activeItemIndex = 0;
  7790. }
  7791. if (sc_that.activeItemIndex < 0 && sc_that.activeItemIndex !== NO_SELECTION) {
  7792. sc_that.activeItemIndex = elements.length - 1;
  7793. }
  7794. if (sc_that.activeItemIndex >= 0) {
  7795. $(elements[sc_that.activeItemIndex]).focus();
  7796. }
  7797. };
  7798. var prepareShift = function(selectionContext) {
  7799. unselectElement(selectionContext.selectedElement(), selectionContext);
  7800. if (selectionContext.activeItemIndex === NO_SELECTION) {
  7801. selectionContext.activeItemIndex = -1;
  7802. }
  7803. };
  7804. var focusNextElement = function(selectionContext) {
  7805. prepareShift(selectionContext);
  7806. ++selectionContext.activeItemIndex;
  7807. reifyIndex(selectionContext);
  7808. };
  7809. var focusPreviousElement = function(selectionContext) {
  7810. prepareShift(selectionContext);
  7811. --selectionContext.activeItemIndex;
  7812. reifyIndex(selectionContext);
  7813. };
  7814. var arrowKeyHandler = function(selectionContext, keyMap, userHandlers) {
  7815. return function(evt) {
  7816. if (evt.which === keyMap.next) {
  7817. focusNextElement(selectionContext);
  7818. evt.preventDefault();
  7819. } else if (evt.which === keyMap.previous) {
  7820. focusPreviousElement(selectionContext);
  7821. evt.preventDefault();
  7822. }
  7823. };
  7824. };
  7825. var getKeyMapForDirection = function(direction) {
  7826. // Determine the appropriate mapping for next and previous based on the specified direction.
  7827. var keyMap;
  7828. if (direction === fluid.a11y.orientation.HORIZONTAL) {
  7829. keyMap = LEFT_RIGHT_KEYMAP;
  7830. }
  7831. else if (direction === fluid.a11y.orientation.VERTICAL) {
  7832. // Assume vertical in any other case.
  7833. keyMap = UP_DOWN_KEYMAP;
  7834. }
  7835. return keyMap;
  7836. };
  7837. var tabKeyHandler = function(selectionContext) {
  7838. return function(evt) {
  7839. if (evt.which !== $.ui.keyCode.TAB) {
  7840. return;
  7841. }
  7842. cleanUpWhenLeavingContainer(selectionContext);
  7843. // Catch Shift-Tab and note that focus is on its way out of the container.
  7844. if (evt.shiftKey) {
  7845. selectionContext.focusIsLeavingContainer = true;
  7846. }
  7847. };
  7848. };
  7849. var containerFocusHandler = function(selectionContext) {
  7850. return function(evt) {
  7851. var shouldOrig = selectionContext.options.autoSelectFirstItem;
  7852. var shouldSelect = typeof(shouldOrig) === "function" ?
  7853. shouldOrig() : shouldOrig;
  7854. // Override the autoselection if we're on the way out of the container.
  7855. if (selectionContext.focusIsLeavingContainer) {
  7856. shouldSelect = false;
  7857. }
  7858. // This target check works around the fact that sometimes focus bubbles, even though it shouldn't.
  7859. if (shouldSelect && evt.target === selectionContext.container.get(0)) {
  7860. if (selectionContext.activeItemIndex === NO_SELECTION) {
  7861. selectionContext.activeItemIndex = 0;
  7862. }
  7863. $(selectionContext.selectables[selectionContext.activeItemIndex]).focus();
  7864. }
  7865. // Force focus not to bubble on some browsers.
  7866. return evt.stopPropagation();
  7867. };
  7868. };
  7869. var containerBlurHandler = function(selectionContext) {
  7870. return function(evt) {
  7871. selectionContext.focusIsLeavingContainer = false;
  7872. // Force blur not to bubble on some browsers.
  7873. return evt.stopPropagation();
  7874. };
  7875. };
  7876. var makeElementsSelectable = function(container, defaults, userOptions) {
  7877. var options = $.extend(true, {}, defaults, userOptions);
  7878. var keyMap = getKeyMapForDirection(options.direction);
  7879. var selectableElements = options.selectableElements? options.selectableElements :
  7880. container.find(options.selectableSelector);
  7881. // Context stores the currently active item(undefined to start) and list of selectables.
  7882. var that = {
  7883. container: container,
  7884. activeItemIndex: NO_SELECTION,
  7885. selectables: selectableElements,
  7886. focusIsLeavingContainer: false,
  7887. options: options
  7888. };
  7889. that.selectablesUpdated = function(focusedItem) {
  7890. // Remove selectables from the tab order and add focus/blur handlers
  7891. if (typeof(that.options.selectablesTabindex) === "number") {
  7892. that.selectables.fluid("tabindex", that.options.selectablesTabindex);
  7893. }
  7894. that.selectables.unbind("focus." + NAMESPACE_KEY);
  7895. that.selectables.unbind("blur." + NAMESPACE_KEY);
  7896. that.selectables.bind("focus."+ NAMESPACE_KEY, selectableFocusHandler(that));
  7897. that.selectables.bind("blur." + NAMESPACE_KEY, selectableBlurHandler(that));
  7898. if (focusedItem) {
  7899. selectElement(focusedItem, that);
  7900. }
  7901. else {
  7902. reifyIndex(that);
  7903. }
  7904. };
  7905. that.refresh = function() {
  7906. if (!that.options.selectableSelector) {
  7907. throw("Cannot refresh selectable context which was not initialised by a selector");
  7908. }
  7909. that.selectables = container.find(options.selectableSelector);
  7910. that.selectablesUpdated();
  7911. };
  7912. that.selectedElement = function() {
  7913. return that.activeItemIndex < 0? null : that.selectables[that.activeItemIndex];
  7914. };
  7915. // Add various handlers to the container.
  7916. if (keyMap) {
  7917. container.keydown(arrowKeyHandler(that, keyMap));
  7918. }
  7919. container.keydown(tabKeyHandler(that));
  7920. container.focus(containerFocusHandler(that));
  7921. container.blur(containerBlurHandler(that));
  7922. that.selectablesUpdated();
  7923. return that;
  7924. };
  7925. /**
  7926. * Makes all matched elements selectable with the arrow keys.
  7927. * Supply your own handlers object with onSelect: and onUnselect: properties for custom behaviour.
  7928. * Options provide configurability, including direction: and autoSelectFirstItem:
  7929. * Currently supported directions are jQuery.a11y.directions.HORIZONTAL and VERTICAL.
  7930. */
  7931. fluid.selectable = function(target, options) {
  7932. target = $(target);
  7933. var that = makeElementsSelectable(target, fluid.selectable.defaults, options);
  7934. setData(target, CONTEXT_KEY, that);
  7935. return that;
  7936. };
  7937. /**
  7938. * Selects the specified element.
  7939. */
  7940. fluid.selectable.select = function(target, toSelect) {
  7941. $(toSelect).focus();
  7942. };
  7943. /**
  7944. * Selects the next matched element.
  7945. */
  7946. fluid.selectable.selectNext = function(target) {
  7947. target = $(target);
  7948. focusNextElement(getData(target, CONTEXT_KEY));
  7949. };
  7950. /**
  7951. * Selects the previous matched element.
  7952. */
  7953. fluid.selectable.selectPrevious = function(target) {
  7954. target = $(target);
  7955. focusPreviousElement(getData(target, CONTEXT_KEY));
  7956. };
  7957. /**
  7958. * Returns the currently selected item wrapped as a jQuery object.
  7959. */
  7960. fluid.selectable.currentSelection = function(target) {
  7961. target = $(target);
  7962. var that = getData(target, CONTEXT_KEY);
  7963. return $(that.selectedElement());
  7964. };
  7965. fluid.selectable.defaults = {
  7966. direction: fluid.a11y.orientation.VERTICAL,
  7967. selectablesTabindex: -1,
  7968. autoSelectFirstItem: true,
  7969. rememberSelectionState: true,
  7970. selectableSelector: ".selectable",
  7971. selectableElements: null,
  7972. onSelect: null,
  7973. onUnselect: null,
  7974. onLeaveContainer: null
  7975. };
  7976. /********************************************************************
  7977. * Activation functionality - declaratively associating actions with
  7978. * a set of keyboard bindings.
  7979. */
  7980. var checkForModifier = function(binding, evt) {
  7981. // If no modifier was specified, just return true.
  7982. if (!binding.modifier) {
  7983. return true;
  7984. }
  7985. var modifierKey = binding.modifier;
  7986. var isCtrlKeyPresent = modifierKey && evt.ctrlKey;
  7987. var isAltKeyPresent = modifierKey && evt.altKey;
  7988. var isShiftKeyPresent = modifierKey && evt.shiftKey;
  7989. return isCtrlKeyPresent || isAltKeyPresent || isShiftKeyPresent;
  7990. };
  7991. /** Constructs a raw "keydown"-facing handler, given a binding entry. This
  7992. * checks whether the key event genuinely triggers the event and forwards it
  7993. * to any "activateHandler" registered in the binding.
  7994. */
  7995. var makeActivationHandler = function(binding) {
  7996. return function(evt) {
  7997. var target = evt.target;
  7998. if (!fluid.enabled(evt.target)) {
  7999. return;
  8000. }
  8001. // The following 'if' clause works in the real world, but there's a bug in the jQuery simulation
  8002. // that causes keyboard simulation to fail in Safari, causing our tests to fail:
  8003. // http://ui.jquery.com/bugs/ticket/3229
  8004. // The replacement 'if' clause works around this bug.
  8005. // When this issue is resolved, we should revert to the original clause.
  8006. // if (evt.which === binding.key && binding.activateHandler && checkForModifier(binding, evt)) {
  8007. var code = evt.which? evt.which : evt.keyCode;
  8008. if (code === binding.key && binding.activateHandler && checkForModifier(binding, evt)) {
  8009. var event = $.Event("fluid-activate");
  8010. $(evt.target).trigger(event, [binding.activateHandler]);
  8011. if (event.isDefaultPrevented()) {
  8012. evt.preventDefault();
  8013. }
  8014. }
  8015. };
  8016. };
  8017. var makeElementsActivatable = function(elements, onActivateHandler, defaultKeys, options) {
  8018. // Create bindings for each default key.
  8019. var bindings = [];
  8020. $(defaultKeys).each(function(index, key) {
  8021. bindings.push({
  8022. modifier: null,
  8023. key: key,
  8024. activateHandler: onActivateHandler
  8025. });
  8026. });
  8027. // Merge with any additional key bindings.
  8028. if (options && options.additionalBindings) {
  8029. bindings = bindings.concat(options.additionalBindings);
  8030. }
  8031. setData(elements, ENABLEMENT_KEY, true);
  8032. // Add listeners for each key binding.
  8033. for (var i = 0; i < bindings.length; ++ i) {
  8034. var binding = bindings[i];
  8035. elements.keydown(makeActivationHandler(binding));
  8036. }
  8037. elements.bind("fluid-activate", function(evt, handler) {
  8038. handler = handler || onActivateHandler;
  8039. return handler? handler(evt): null;
  8040. });
  8041. };
  8042. /**
  8043. * Makes all matched elements activatable with the Space and Enter keys.
  8044. * Provide your own handler function for custom behaviour.
  8045. * Options allow you to provide a list of additionalActivationKeys.
  8046. */
  8047. fluid.activatable = function(target, fn, options) {
  8048. target = $(target);
  8049. makeElementsActivatable(target, fn, fluid.activatable.defaults.keys, options);
  8050. };
  8051. /**
  8052. * Activates the specified element.
  8053. */
  8054. fluid.activate = function(target) {
  8055. $(target).trigger("fluid-activate");
  8056. };
  8057. // Public Defaults.
  8058. fluid.activatable.defaults = {
  8059. keys: [$.ui.keyCode.ENTER, $.ui.keyCode.SPACE]
  8060. };
  8061. })(jQuery, fluid_1_1);
  8062. /*
  8063. Copyright 2008-2009 University of Cambridge
  8064. Copyright 2008-2009 University of Toronto
  8065. Copyright 2007-2009 University of California, Berkeley
  8066. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  8067. BSD license. You may not use this file except in compliance with one these
  8068. Licenses.
  8069. You may obtain a copy of the ECL 2.0 License and BSD License at
  8070. https://source.fluidproject.org/svn/LICENSE.txt
  8071. */
  8072. // Declare dependencies.
  8073. /*global jQuery*/
  8074. /*global fluid_1_1*/
  8075. var fluid_1_1 = fluid_1_1 || {};
  8076. (function ($, fluid) {
  8077. fluid.orientation = {
  8078. HORIZONTAL: 4,
  8079. VERTICAL: 1
  8080. };
  8081. fluid.rectSides = {
  8082. // agree with fluid.orientation
  8083. 4: ["left", "right"],
  8084. 1: ["top", "bottom"],
  8085. // agree with fluid.direction
  8086. 8: "top",
  8087. 12: "bottom",
  8088. 2: "left",
  8089. 3: "right"
  8090. };
  8091. /**
  8092. * This is the position, relative to a given drop target, that a dragged item should be dropped.
  8093. */
  8094. fluid.position = {
  8095. BEFORE: -1,
  8096. AFTER: 1,
  8097. INSIDE: 2,
  8098. REPLACE: 3
  8099. };
  8100. /**
  8101. * For incrementing/decrementing a count or index, or moving in a rectilinear direction.
  8102. */
  8103. fluid.direction = {
  8104. NEXT: 1,
  8105. PREVIOUS: -1,
  8106. UP: 8,
  8107. DOWN: 12,
  8108. LEFT: 2,
  8109. RIGHT: 3
  8110. };
  8111. fluid.directionSign = function (direction) {
  8112. return direction === fluid.direction.UP || direction === fluid.direction.LEFT?
  8113. fluid.direction.PREVIOUS : fluid.direction.NEXT;
  8114. };
  8115. fluid.directionAxis = function (direction) {
  8116. return direction === fluid.direction.LEFT || direction === fluid.direction.RIGHT?
  8117. 0 : 1;
  8118. };
  8119. fluid.directionOrientation = function (direction) {
  8120. return fluid.directionAxis(direction)? fluid.orientation.VERTICAL : fluid.orientation.HORIZONTAL;
  8121. };
  8122. fluid.keycodeDirection = {
  8123. up: fluid.direction.UP,
  8124. down: fluid.direction.DOWN,
  8125. left: fluid.direction.LEFT,
  8126. right: fluid.direction.RIGHT
  8127. };
  8128. // moves a single node in the DOM to a new position relative to another
  8129. fluid.moveDom = function (source, target, position) {
  8130. source = fluid.unwrap(source);
  8131. target = fluid.unwrap(target);
  8132. var scan;
  8133. // fluid.log("moveDom source " + fluid.dumpEl(source) + " target " + fluid.dumpEl(target) + " position " + position);
  8134. if (position === fluid.position.INSIDE) {
  8135. target.appendChild(source);
  8136. }
  8137. else if (position === fluid.position.BEFORE) {
  8138. for (scan = target.previousSibling; ; scan = scan.previousSibling) {
  8139. if (!scan || !fluid.dom.isIgnorableNode(scan)) {
  8140. if (scan !== source) {
  8141. fluid.dom.cleanseScripts(source);
  8142. target.parentNode.insertBefore(source, target);
  8143. }
  8144. break;
  8145. }
  8146. }
  8147. }
  8148. else if (position === fluid.position.AFTER) {
  8149. for (scan = target.nextSibling; ; scan = scan.nextSibling) {
  8150. if (!scan || !fluid.dom.isIgnorableNode(scan)) {
  8151. if (scan !== source) {
  8152. fluid.dom.cleanseScripts(source);
  8153. fluid.dom.insertAfter(source, target);
  8154. }
  8155. break;
  8156. }
  8157. }
  8158. }
  8159. else {
  8160. fluid.fail("Unrecognised position supplied to fluid.moveDom: " + position);
  8161. }
  8162. };
  8163. fluid.normalisePosition = function (position, samespan, targeti, sourcei) {
  8164. // convert a REPLACE into a primitive BEFORE/AFTER
  8165. if (position === fluid.position.REPLACE) {
  8166. position = samespan && targeti >= sourcei? fluid.position.AFTER: fluid.position.BEFORE;
  8167. }
  8168. return position;
  8169. };
  8170. fluid.permuteDom = function (element, target, position, sourceelements, targetelements) {
  8171. element = fluid.unwrap(element);
  8172. target = fluid.unwrap(target);
  8173. var sourcei = $.inArray(element, sourceelements);
  8174. if (sourcei === -1) {
  8175. fluid.fail("Error in permuteDom: source element " + fluid.dumpEl(element)
  8176. + " not found in source list " + fluid.dumpEl(sourceelements));
  8177. }
  8178. var targeti = $.inArray(target, targetelements);
  8179. if (targeti === -1) {
  8180. fluid.fail("Error in permuteDom: target element " + fluid.dumpEl(target)
  8181. + " not found in source list " + fluid.dumpEl(targetelements));
  8182. }
  8183. var samespan = sourceelements === targetelements;
  8184. position = fluid.normalisePosition(position, samespan, targeti, sourcei);
  8185. //fluid.log("permuteDom sourcei " + sourcei + " targeti " + targeti);
  8186. // cache the old neighbourhood of the element for the final move
  8187. var oldn = {};
  8188. oldn[fluid.position.AFTER] = element.nextSibling;
  8189. oldn[fluid.position.BEFORE] = element.previousSibling;
  8190. fluid.moveDom(sourceelements[sourcei], targetelements[targeti], position);
  8191. // perform the leftward-moving, AFTER shift
  8192. var frontlimit = samespan? targeti - 1: sourceelements.length - 2;
  8193. var i;
  8194. if (position === fluid.position.BEFORE && samespan) {
  8195. // we cannot do skip processing if the element was "fused against the grain"
  8196. frontlimit--;
  8197. }
  8198. if (!samespan || targeti > sourcei) {
  8199. for (i = frontlimit; i > sourcei; -- i) {
  8200. fluid.moveDom(sourceelements[i + 1], sourceelements[i], fluid.position.AFTER);
  8201. }
  8202. if (sourcei + 1 < sourceelements.length) {
  8203. fluid.moveDom(sourceelements[sourcei + 1], oldn[fluid.position.AFTER], fluid.position.BEFORE);
  8204. }
  8205. }
  8206. // perform the rightward-moving, BEFORE shift
  8207. var backlimit = samespan? sourcei - 1: targetelements.length - 1;
  8208. if (position === fluid.position.AFTER) {
  8209. // we cannot do skip processing if the element was "fused against the grain"
  8210. targeti++;
  8211. }
  8212. if (!samespan || targeti < sourcei) {
  8213. for (i = targeti; i < backlimit; ++ i) {
  8214. fluid.moveDom(targetelements[i], targetelements[i + 1], fluid.position.BEFORE);
  8215. }
  8216. if (backlimit >= 0 && backlimit < targetelements.length - 1) {
  8217. fluid.moveDom(targetelements[backlimit], oldn[fluid.position.BEFORE], fluid.position.AFTER);
  8218. }
  8219. }
  8220. };
  8221. var curCss = function (a, name) {
  8222. return window.getComputedStyle? window.getComputedStyle(a, null).getPropertyValue(name) :
  8223. a.currentStyle[name];
  8224. };
  8225. var isAttached = function (node) {
  8226. while (node && node.nodeName) {
  8227. if (node.nodeName === "BODY") {
  8228. return true;
  8229. }
  8230. node = node.parentNode;
  8231. }
  8232. return false;
  8233. };
  8234. var generalHidden = function (a) {
  8235. return "hidden" === a.type || curCss(a, "display") === "none" || curCss(a, "visibility") === "hidden" || !isAttached(a);
  8236. };
  8237. var computeGeometry = function (element, orientation, disposition) {
  8238. var elem = {};
  8239. elem.element = element;
  8240. elem.orientation = orientation;
  8241. if (disposition === fluid.position.INSIDE) {
  8242. elem.position = disposition;
  8243. }
  8244. if (generalHidden(element)) {
  8245. elem.clazz = "hidden";
  8246. }
  8247. var pos = fluid.dom.computeAbsolutePosition(element) || [0, 0];
  8248. var width = element.offsetWidth;
  8249. var height = element.offsetHeight;
  8250. elem.rect = {left: pos[0], top: pos[1]};
  8251. elem.rect.right = pos[0] + width;
  8252. elem.rect.bottom = pos[1] + height;
  8253. return elem;
  8254. };
  8255. // A "suitable large" value for the sentinel blocks at the ends of spans
  8256. var SENTINEL_DIMENSION = 10000;
  8257. function dumprect(rect) {
  8258. return "Rect top: " + rect.top +
  8259. " left: " + rect.left +
  8260. " bottom: " + rect.bottom +
  8261. " right: " + rect.right;
  8262. }
  8263. function dumpelem(cacheelem) {
  8264. if (!cacheelem || !cacheelem.rect) {
  8265. return "null";
  8266. } else {
  8267. return dumprect(cacheelem.rect) + " position: " +
  8268. cacheelem.position +
  8269. " for " +
  8270. fluid.dumpEl(cacheelem.element);
  8271. }
  8272. }
  8273. fluid.dropManager = function () {
  8274. var targets = [];
  8275. var cache = {};
  8276. var that = {};
  8277. var lastClosest;
  8278. function cacheKey(element) {
  8279. return $(element).data("");
  8280. }
  8281. function sentinelizeElement(targets, sides, cacheelem, fc, disposition, clazz) {
  8282. var elemCopy = $.extend(true, {}, cacheelem);
  8283. elemCopy.rect[sides[fc]] = elemCopy.rect[sides[1 - fc]] + (fc? 1: -1);
  8284. elemCopy.rect[sides[1 - fc]] = (fc? -1 : 1) * SENTINEL_DIMENSION;
  8285. elemCopy.position = disposition === fluid.position.INSIDE?
  8286. disposition : (fc? fluid.position.BEFORE : fluid.position.AFTER);
  8287. elemCopy.clazz = clazz;
  8288. targets[targets.length] = elemCopy;
  8289. }
  8290. function splitElement(targets, sides, cacheelem, disposition, clazz1, clazz2) {
  8291. var elem1 = $.extend(true, {}, cacheelem);
  8292. var elem2 = $.extend(true, {}, cacheelem);
  8293. var midpoint = (elem1.rect[sides[0]] + elem1.rect[sides[1]]) / 2;
  8294. elem1.rect[sides[1]] = midpoint;
  8295. elem1.position = fluid.position.BEFORE;
  8296. elem2.rect[sides[0]] = midpoint;
  8297. elem2.position = fluid.position.AFTER;
  8298. elem1.clazz = clazz1;
  8299. elem2.clazz = clazz2;
  8300. targets[targets.length] = elem1;
  8301. targets[targets.length] = elem2;
  8302. }
  8303. // Expand this configuration point if we ever go back to a full "permissions" model
  8304. function getRelativeClass(thisElements, index, relative, thisclazz, mapper) {
  8305. index += relative;
  8306. if (index < 0 && thisclazz === "locked") {
  8307. return "locked";
  8308. }
  8309. if (index >= thisElements.length || mapper === null) {
  8310. return null;
  8311. } else {
  8312. relative = thisElements[index];
  8313. return mapper(relative) === "locked" && thisclazz === "locked" ? "locked" : null;
  8314. }
  8315. }
  8316. var lastGeometry;
  8317. var displacementX, displacementY;
  8318. that.updateGeometry = function (geometricInfo) {
  8319. lastGeometry = geometricInfo;
  8320. targets = [];
  8321. cache = {};
  8322. var mapper = geometricInfo.elementMapper;
  8323. for (var i = 0; i < geometricInfo.extents.length; ++ i) {
  8324. var thisInfo = geometricInfo.extents[i];
  8325. var orientation = thisInfo.orientation;
  8326. var sides = fluid.rectSides[orientation];
  8327. var processElement = function (element, sentB, sentF, disposition, j) {
  8328. var cacheelem = computeGeometry(element, orientation, disposition);
  8329. cacheelem.owner = thisInfo;
  8330. if (cacheelem.clazz !== "hidden" && mapper) {
  8331. cacheelem.clazz = mapper(element);
  8332. }
  8333. cache[$.data(element)] = cacheelem;
  8334. var backClass = getRelativeClass(thisInfo.elements, j, fluid.position.BEFORE, cacheelem.clazz, mapper);
  8335. var frontClass = getRelativeClass(thisInfo.elements, j, fluid.position.AFTER, cacheelem.clazz, mapper);
  8336. if (disposition === fluid.position.INSIDE) {
  8337. targets[targets.length] = cacheelem;
  8338. }
  8339. else {
  8340. splitElement(targets, sides, cacheelem, disposition, backClass, frontClass);
  8341. }
  8342. // deal with sentinel blocks by creating near-copies of the end elements
  8343. if (sentB && geometricInfo.sentinelize) {
  8344. sentinelizeElement(targets, sides, cacheelem, 1, disposition, backClass);
  8345. }
  8346. if (sentF && geometricInfo.sentinelize) {
  8347. sentinelizeElement(targets, sides, cacheelem, 0, disposition, frontClass);
  8348. }
  8349. //fluid.log(dumpelem(cacheelem));
  8350. return cacheelem;
  8351. };
  8352. var allHidden = true;
  8353. for (var j = 0; j < thisInfo.elements.length; ++ j) {
  8354. var element = thisInfo.elements[j];
  8355. var cacheelem = processElement(element, j === 0, j === thisInfo.elements.length - 1,
  8356. fluid.position.INTERLEAVED, j);
  8357. if (cacheelem.clazz !== "hidden") {
  8358. allHidden = false;
  8359. }
  8360. }
  8361. if (allHidden && thisInfo.parentElement) {
  8362. processElement(thisInfo.parentElement, true, true,
  8363. fluid.position.INSIDE);
  8364. }
  8365. }
  8366. };
  8367. that.startDrag = function (event, handlePos, handleWidth, handleHeight) {
  8368. var handleMidX = handlePos[0] + handleWidth / 2;
  8369. var handleMidY = handlePos[1] + handleHeight / 2;
  8370. var dX = handleMidX - event.pageX;
  8371. var dY = handleMidY - event.pageY;
  8372. that.updateGeometry(lastGeometry);
  8373. lastClosest = null;
  8374. displacementX = dX;
  8375. displacementY = dY;
  8376. $("").bind("mousemove.fluid-dropManager", that.mouseMove);
  8377. };
  8378. that.lastPosition = function () {
  8379. return lastClosest;
  8380. };
  8381. that.endDrag = function () {
  8382. $("").unbind("mousemove.fluid-dropManager");
  8383. };
  8384. that.mouseMove = function (evt) {
  8385. var x = evt.pageX + displacementX;
  8386. var y = evt.pageY + displacementY;
  8387. //fluid.log("Mouse x " + x + " y " + y );
  8388. var closestTarget = that.closestTarget(x, y, lastClosest);
  8389. if (closestTarget && closestTarget !== fluid.dropManager.NO_CHANGE) {
  8390. lastClosest = closestTarget;
  8391. that.dropChangeFirer.fire(closestTarget);
  8392. }
  8393. };
  8394. that.dropChangeFirer = fluid.event.getEventFirer();
  8395. var blankHolder = {
  8396. element: null
  8397. };
  8398. that.closestTarget = function (x, y, lastClosest) {
  8399. var mindistance = Number.MAX_VALUE;
  8400. var minelem = blankHolder;
  8401. var minlockeddistance = Number.MAX_VALUE;
  8402. var minlockedelem = blankHolder;
  8403. for (var i = 0; i < targets.length; ++ i) {
  8404. var cacheelem = targets[i];
  8405. if (cacheelem.clazz === "hidden") {
  8406. continue;
  8407. }
  8408. var distance = fluid.geom.minPointRectangle(x, y, cacheelem.rect);
  8409. if (cacheelem.clazz === "locked") {
  8410. if (distance < minlockeddistance) {
  8411. minlockeddistance = distance;
  8412. minlockedelem = cacheelem;
  8413. }
  8414. } else {
  8415. if (distance < mindistance) {
  8416. mindistance = distance;
  8417. minelem = cacheelem;
  8418. }
  8419. if (distance === 0) {
  8420. break;
  8421. }
  8422. }
  8423. }
  8424. if (!minelem) {
  8425. return minelem;
  8426. }
  8427. if (minlockeddistance >= mindistance) {
  8428. minlockedelem = blankHolder;
  8429. }
  8430. //fluid.log("PRE: mindistance " + mindistance + " element " +
  8431. // fluid.dumpEl(minelem.element) + " minlockeddistance " + minlockeddistance
  8432. // + " locked elem " + dumpelem(minlockedelem));
  8433. if (lastClosest && lastClosest.position === minelem.position &&
  8434. fluid.unwrap(lastClosest.element) === fluid.unwrap(minelem.element) &&
  8435. fluid.unwrap(lastClosest.lockedelem) === fluid.unwrap(minlockedelem.element)
  8436. ) {
  8437. return fluid.dropManager.NO_CHANGE;
  8438. }
  8439. //fluid.log("mindistance " + mindistance + " minlockeddistance " + minlockeddistance);
  8440. return {
  8441. position: minelem.position,
  8442. element: minelem.element,
  8443. lockedelem: minlockedelem.element
  8444. };
  8445. };
  8446. that.shuffleProjectFrom = function (element, direction, includeLocked) {
  8447. var togo = that.projectFrom(element, direction, includeLocked);
  8448. togo.position = fluid.position.REPLACE;
  8449. return togo;
  8450. };
  8451. that.projectFrom = function (element, direction, includeLocked) {
  8452. that.updateGeometry(lastGeometry);
  8453. var cacheelem = cache[cacheKey(element)];
  8454. var projected = fluid.geom.projectFrom(cacheelem.rect, direction, targets, includeLocked);
  8455. if (!projected.cacheelem) {
  8456. return null;
  8457. }
  8458. var retpos = projected.cacheelem.position;
  8459. return {element: projected.cacheelem.element,
  8460. position: retpos? retpos : fluid.position.BEFORE
  8461. };
  8462. };
  8463. function getRelativeElement(element, direction, elements) {
  8464. var folded = fluid.directionSign(direction);
  8465. var index = $(elements).index(element) + folded;
  8466. if (index < 0) {
  8467. index += elements.length;
  8468. }
  8469. index %= elements.length;
  8470. return elements[index];
  8471. }
  8472. that.logicalFrom = function (element, direction, includeLocked) {
  8473. var orderables = that.getOwningSpan(element, fluid.position.INTERLEAVED, includeLocked);
  8474. return {element: getRelativeElement(element, direction, orderables),
  8475. position: fluid.position.REPLACE};
  8476. };
  8477. that.lockedWrapFrom = function (element, direction, includeLocked) {
  8478. var base = that.logicalFrom(element, direction, includeLocked);
  8479. var selectables = that.getOwningSpan(element, fluid.position.INTERLEAVED, includeLocked);
  8480. var allElements = cache[cacheKey(element)].owner.elements;
  8481. if (includeLocked || selectables[0] === allElements[0]) {
  8482. return base;
  8483. }
  8484. var directElement = getRelativeElement(element, direction, allElements);
  8485. if (lastGeometry.elementMapper(directElement) === "locked") {
  8486. base.element = null;
  8487. base.clazz = "locked";
  8488. }
  8489. return base;
  8490. };
  8491. that.getOwningSpan = function (element, position, includeLocked) {
  8492. var owner = cache[cacheKey(element)].owner;
  8493. var elements = position === fluid.position.INSIDE? [owner.parentElement] : owner.elements;
  8494. if (!includeLocked && lastGeometry.elementMapper) {
  8495. elements = $.makeArray(elements);
  8496. fluid.remove_if(elements, function (element) {
  8497. return lastGeometry.elementMapper(element) === "locked";
  8498. });
  8499. }
  8500. return elements;
  8501. };
  8502. that.geometricMove = function (element, target, position) {
  8503. var sourceElements = that.getOwningSpan(element, null, true);
  8504. var targetElements = that.getOwningSpan(target, position, true);
  8505. fluid.permuteDom(element, target, position, sourceElements, targetElements);
  8506. };
  8507. return that;
  8508. };
  8509. fluid.dropManager.NO_CHANGE = "no change";
  8510. fluid.geom = fluid.geom || {};
  8511. // These distance algorithms have been taken from
  8512. // http://www.cs.mcgill.ca/~cs644/Godfried/2005/Fall/fzamal/concepts.htm
  8513. /** Returns the minimum squared distance between a point and a rectangle **/
  8514. fluid.geom.minPointRectangle = function (x, y, rectangle) {
  8515. var dx = x < rectangle.left? (rectangle.left - x) :
  8516. (x > rectangle.right? (x - rectangle.right) : 0);
  8517. var dy = y < rectangle.top? (rectangle.top - y) :
  8518. (y > rectangle.bottom? (y - rectangle.bottom) : 0);
  8519. return dx * dx + dy * dy;
  8520. };
  8521. /** Returns the minimum squared distance between two rectangles **/
  8522. fluid.geom.minRectRect = function (rect1, rect2) {
  8523. var dx = rect1.right < rect2.left? rect2.left - rect1.right :
  8524. rect2.right < rect1.left? rect1.left - rect2.right :0;
  8525. var dy = rect1.bottom < rect2.top? rect2.top - rect1.bottom :
  8526. rect2.bottom < rect1.top? rect1.top - rect2.bottom :0;
  8527. return dx * dx + dy * dy;
  8528. };
  8529. var makePenCollect = function () {
  8530. return {
  8531. mindist: Number.MAX_VALUE,
  8532. minrdist: Number.MAX_VALUE
  8533. };
  8534. };
  8535. /** Determine the one amongst a set of rectangle targets which is the "best fit"
  8536. * for an axial motion from a "base rectangle" (commonly arising from the case
  8537. * of cursor key navigation).
  8538. * @param {Rectangle} baserect The base rectangl from which the motion is to be referred
  8539. * @param {fluid.direction} direction The direction of motion
  8540. * @param {Array of Rectangle holders} targets An array of objects "cache elements"
  8541. * for which the member <code>rect</code> is the holder of the rectangle to be tested.
  8542. * @return The cache element which is the most appropriate for the requested motion.
  8543. */
  8544. fluid.geom.projectFrom = function (baserect, direction, targets, forSelection) {
  8545. var axis = fluid.directionAxis(direction);
  8546. var frontSide = fluid.rectSides[direction];
  8547. var backSide = fluid.rectSides[axis * 15 + 5 - direction];
  8548. var dirSign = fluid.directionSign(direction);
  8549. var penrect = {left: (7 * baserect.left + 1 * baserect.right) / 8,
  8550. right: (5 * baserect.left + 3 * baserect.right) / 8,
  8551. top: (7 * baserect.top + 1 * baserect.bottom) / 8,
  8552. bottom: (5 * baserect.top + 3 * baserect.bottom) / 8};
  8553. penrect[frontSide] = dirSign * SENTINEL_DIMENSION;
  8554. penrect[backSide] = -penrect[frontSide];
  8555. function accPen(collect, cacheelem, backSign) {
  8556. var thisrect = cacheelem.rect;
  8557. var pdist = fluid.geom.minRectRect(penrect, thisrect);
  8558. var rdist = -dirSign * backSign * (baserect[backSign === 1 ? frontSide:backSide]
  8559. - thisrect[backSign === 1 ? backSide:frontSide]);
  8560. // fluid.log("pdist: " + pdist + " rdist: " + rdist);
  8561. // the oddity in the rdist comparison is intended to express "half-open"-ness of rectangles
  8562. // (backSign === 1? 0 : 1) - this is now gone - must be possible to move to perpendicularly abutting regions
  8563. if (pdist <= collect.mindist && rdist >= 0) {
  8564. if (pdist === collect.mindist && rdist * backSign > collect.minrdist) {
  8565. return;
  8566. }
  8567. collect.minrdist = rdist * backSign;
  8568. collect.mindist = pdist;
  8569. collect.minelem = cacheelem;
  8570. }
  8571. }
  8572. var collect = makePenCollect();
  8573. var backcollect = makePenCollect();
  8574. var lockedcollect = makePenCollect();
  8575. for (var i = 0; i < targets.length; ++ i) {
  8576. var elem = targets[i];
  8577. var isPure = elem.owner && elem.element === elem.owner.parentElement;
  8578. if (elem.clazz === "hidden" || forSelection && isPure) {
  8579. continue;
  8580. }
  8581. else if (!forSelection && elem.clazz === "locked") {
  8582. accPen(lockedcollect, elem, 1);
  8583. }
  8584. else {
  8585. accPen(collect, elem, 1);
  8586. accPen(backcollect, elem, -1);
  8587. }
  8588. //fluid.log("Element " + i + " " + dumpelem(elem) + " mindist " + collect.mindist);
  8589. }
  8590. var wrap = !collect.minelem || backcollect.mindist < collect.mindist;
  8591. var mincollect = wrap? backcollect: collect;
  8592. var togo = {
  8593. wrapped: wrap,
  8594. cacheelem: mincollect.minelem
  8595. };
  8596. if (lockedcollect.mindist < mincollect.mindist) {
  8597. togo.lockedelem = lockedcollect.minelem;
  8598. }
  8599. return togo;
  8600. };
  8601. })(jQuery, fluid_1_1);
  8602. /*
  8603. Copyright 2007-2009 University of Toronto
  8604. Copyright 2007-2009 University of Cambridge
  8605. Copyright 2007-2009 University of California, Berkeley
  8606. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  8607. BSD license. You may not use this file except in compliance with one these
  8608. Licenses.
  8609. You may obtain a copy of the ECL 2.0 License and BSD License at
  8610. https://source.fluidproject.org/svn/LICENSE.txt
  8611. */
  8612. // Declare dependencies.
  8613. /*global $, jQuery*/
  8614. /*global fluid_1_1*/
  8615. fluid_1_1 = fluid_1_1 || {};
  8616. (function ($, fluid) {
  8617. var defaultAvatarCreator = function (item, cssClass, dropWarning) {
  8618. var avatar = $(item).clone();
  8619. fluid.dom.iterateDom(avatar.get(0), function (node) {
  8620. if (node.tagName.toLowerCase() === "script") {
  8621. return "delete";
  8622. }
  8623. node.removeAttribute("id");
  8624. if (node.tagName.toLowerCase() === "input") {
  8625. node.setAttribute("disabled", "disabled");
  8626. }
  8627. });
  8628. avatar.removeAttr("id");
  8629. avatar.removeClass("ui-droppable");
  8630. avatar.addClass(cssClass);
  8631. if (dropWarning) {
  8632. // Will a 'div' always be valid in this position?
  8633. var avatarContainer = $(document.createElement("div"));
  8634. avatarContainer.append(avatar);
  8635. avatarContainer.append(dropWarning);
  8636. avatar = avatarContainer;
  8637. }
  8638. $("body").append(avatar);
  8639. if (!$.browser.safari) {
  8640. // FLUID-1597: Safari appears incapable of correctly determining the dimensions of elements
  8641. avatar.css("display", "block").width(item.offsetWidth).height(item.offsetHeight);
  8642. }
  8643. if ($.browser.opera) { // FLUID-1490. Without this detect, curCSS explodes on the avatar on Firefox.
  8644. avatar.hide();
  8645. }
  8646. return avatar;
  8647. };
  8648. function firstSelectable(that) {
  8649. var selectables = that.dom.fastLocate("selectables");
  8650. if (selectables.length <= 0) {
  8651. return null;
  8652. }
  8653. return selectables[0];
  8654. }
  8655. function bindHandlersToContainer(container, keyDownHandler, keyUpHandler, mouseMoveHandler) {
  8656. var actualKeyDown = keyDownHandler;
  8657. var advancedPrevention = false;
  8658. // FLUID-1598 and others: Opera will refuse to honour a "preventDefault" on a keydown.
  8659. // http://forums.devshed.com/javascript-development-115/onkeydown-preventdefault-opera-485371.html
  8660. if ($.browser.opera) {
  8661. container.keypress(function (evt) {
  8662. if (advancedPrevention) {
  8663. advancedPrevention = false;
  8664. evt.preventDefault();
  8665. return false;
  8666. }
  8667. });
  8668. actualKeyDown = function (evt) {
  8669. var oldret = keyDownHandler(evt);
  8670. if (oldret === false) {
  8671. advancedPrevention = true;
  8672. }
  8673. };
  8674. }
  8675. container.keydown(actualKeyDown);
  8676. container.keyup(keyUpHandler);
  8677. }
  8678. function addRolesToContainer(that) {
  8679. var first = that.dom.fastLocate("selectables")[0];
  8680. that.container.attr("role", that.options.containerRole.container);
  8681. that.container.attr("aria-multiselectable", "false");
  8682. that.container.attr("aria-readonly", "false");
  8683. that.container.attr("aria-disabled", "false");
  8684. }
  8685. function createAvatarId(parentId) {
  8686. // Generating the avatar's id to be containerId_avatar
  8687. // This is safe since there is only a single avatar at a time
  8688. return parentId + "_avatar";
  8689. }
  8690. var adaptKeysets = function (options) {
  8691. if (options.keysets && !(options.keysets instanceof Array)) {
  8692. options.keysets = [options.keysets];
  8693. }
  8694. };
  8695. /**
  8696. * @param container - the root node of the Reorderer.
  8697. * @param options - an object containing any of the available options:
  8698. * containerRole - indicates the role, or general use, for this instance of the Reorderer
  8699. * keysets - an object containing sets of keycodes to use for directional navigation. Must contain:
  8700. * modifier - a function that returns a boolean, indicating whether or not the required modifier(s) are activated
  8701. * up
  8702. * down
  8703. * right
  8704. * left
  8705. * styles - an object containing class names for styling the Reorderer
  8706. * defaultStyle
  8707. * selected
  8708. * dragging
  8709. * hover
  8710. * dropMarker
  8711. * mouseDrag
  8712. * avatar
  8713. * avatarCreator - a function that returns a valid DOM node to be used as the dragging avatar
  8714. */
  8715. fluid.reorderer = function (container, options) {
  8716. if (!container) {
  8717. fluid.fail("Reorderer initialised with no container");
  8718. }
  8719. var thatReorderer = fluid.initView("fluid.reorderer", container, options);
  8720. options = thatReorderer.options;
  8721. var dropManager = fluid.dropManager();
  8722. thatReorderer.layoutHandler = fluid.initSubcomponent(thatReorderer,
  8723. "layoutHandler", [container, options, dropManager, thatReorderer.dom]);
  8724. thatReorderer.activeItem = undefined;
  8725. adaptKeysets(options);
  8726. var kbDropWarning = thatReorderer.locate("dropWarning");
  8727. var mouseDropWarning;
  8728. if (kbDropWarning) {
  8729. mouseDropWarning = kbDropWarning.clone();
  8730. }
  8731. var isMove = function (evt) {
  8732. var keysets = options.keysets;
  8733. for (var i = 0; i < keysets.length; i++) {
  8734. if (keysets[i].modifier(evt)) {
  8735. return true;
  8736. }
  8737. }
  8738. return false;
  8739. };
  8740. var isActiveItemMovable = function () {
  8741. return $.inArray(thatReorderer.activeItem, thatReorderer.dom.fastLocate("movables")) >= 0;
  8742. };
  8743. var setDropEffects = function (value) {
  8744. thatReorderer.dom.fastLocate("dropTargets").attr("aria-dropeffect", value);
  8745. };
  8746. var styles = options.styles;
  8747. var noModifier = function (evt) {
  8748. return (!evt.ctrlKey && !evt.altKey && !evt.shiftKey && !evt.metaKey);
  8749. };
  8750. var handleDirectionKeyDown = function (evt) {
  8751. var item = thatReorderer.activeItem;
  8752. if (!item) {
  8753. return true;
  8754. }
  8755. var keysets = options.keysets;
  8756. for (var i = 0; i < keysets.length; i++) {
  8757. var keyset = keysets[i];
  8758. var didProcessKey = false;
  8759. var keydir = fluid.keyForValue(keyset, evt.keyCode);
  8760. if (!keydir) {
  8761. continue;
  8762. }
  8763. var isMovement = keyset.modifier(evt);
  8764. var dirnum = fluid.keycodeDirection[keydir];
  8765. var relativeItem = thatReorderer.layoutHandler.getRelativePosition(item, dirnum, !isMovement);
  8766. if (!relativeItem) {
  8767. continue;
  8768. }
  8769. if (isMovement) {
  8770. var prevent = thatReorderer.events.onBeginMove.fire(item);
  8771. if (prevent === false) {
  8772. return false;
  8773. }
  8774. if (kbDropWarning.length > 0) {
  8775. if (relativeItem.clazz === "locked") {
  8776. thatReorderer.events.onShowKeyboardDropWarning.fire(item, kbDropWarning);
  8777. kbDropWarning.show();
  8778. }
  8779. else {
  8780. kbDropWarning.hide();
  8781. }
  8782. }
  8783. if (relativeItem.element) {
  8784. thatReorderer.requestMovement(relativeItem, item);
  8785. }
  8786. } else if (noModifier(evt)) {
  8787. $(relativeItem.element).focus();
  8788. }
  8789. return false;
  8790. }
  8791. return true;
  8792. };
  8793. thatReorderer.handleKeyDown = function (evt) {
  8794. if (!thatReorderer.activeItem || thatReorderer.activeItem !== evt.target) {
  8795. return true;
  8796. }
  8797. // If the key pressed is ctrl, and the active item is movable we want to restyle the active item.
  8798. var jActiveItem = $(thatReorderer.activeItem);
  8799. if (!jActiveItem.hasClass(styles.dragging) && isMove(evt)) {
  8800. // Don't treat the active item as dragging unless it is a movable.
  8801. if (isActiveItemMovable()) {
  8802. jActiveItem.removeClass(styles.selected);
  8803. jActiveItem.addClass(styles.dragging);
  8804. jActiveItem.attr("aria-grabbed", "true");
  8805. setDropEffects("move");
  8806. }
  8807. return false;
  8808. }
  8809. // The only other keys we listen for are the arrows.
  8810. return handleDirectionKeyDown(evt);
  8811. };
  8812. thatReorderer.handleKeyUp = function (evt) {
  8813. if (!thatReorderer.activeItem || thatReorderer.activeItem !== evt.target) {
  8814. return true;
  8815. }
  8816. var jActiveItem = $(thatReorderer.activeItem);
  8817. // Handle a key up event for the modifier
  8818. if (jActiveItem.hasClass(styles.dragging) && !isMove(evt)) {
  8819. if (kbDropWarning) {
  8820. kbDropWarning.hide();
  8821. }
  8822. jActiveItem.removeClass(styles.dragging);
  8823. jActiveItem.addClass(styles.selected);
  8824. jActiveItem.attr("aria-grabbed", "false");
  8825. setDropEffects("none");
  8826. return false;
  8827. }
  8828. return false;
  8829. };
  8830. var dropMarker;
  8831. var createDropMarker = function (tagName) {
  8832. var dropMarker = $(document.createElement(tagName));
  8833. dropMarker.addClass(options.styles.dropMarker);
  8834. dropMarker.hide();
  8835. return dropMarker;
  8836. };
  8837. fluid.logEnabled = true;
  8838. thatReorderer.requestMovement = function (requestedPosition, item) {
  8839. // Temporary censoring to get around ModuleLayout inability to update relative to self.
  8840. if (!requestedPosition || fluid.unwrap(requestedPosition.element) === fluid.unwrap(item)) {
  8841. return;
  8842. }
  8843. thatReorderer.events.onMove.fire(item, requestedPosition);
  8844. dropManager.geometricMove(item, requestedPosition.element, requestedPosition.position);
  8845. //$(thatReorderer.activeItem).removeClass(options.styles.selected);
  8846. // refocus on the active item because moving places focus on the body
  8847. $(thatReorderer.activeItem).focus();
  8848. thatReorderer.refresh();
  8849. dropManager.updateGeometry(thatReorderer.layoutHandler.getGeometricInfo());
  8850. thatReorderer.events.afterMove.fire(item, requestedPosition, thatReorderer.dom.fastLocate("movables"));
  8851. };
  8852. var hoverStyleHandler = function (item, state) {
  8853. thatReorderer.dom.fastLocate("grabHandle", item)[state?"addClass":"removeClass"](styles.hover);
  8854. };
  8855. /**
  8856. * Takes a $ object and adds 'movable' functionality to it
  8857. */
  8858. function initMovable(item) {
  8859. var styles = options.styles;
  8860. item.attr("aria-grabbed", "false");
  8861. item.mouseover(
  8862. function () {
  8863. thatReorderer.events.onHover.fire(item, true);
  8864. }
  8865. );
  8866. item.mouseout(
  8867. function () {
  8868. thatReorderer.events.onHover.fire(item, false);
  8869. }
  8870. );
  8871. var avatar;
  8872. thatReorderer.dom.fastLocate("grabHandle", item).draggable({
  8873. refreshPositions: false,
  8874. scroll: true,
  8875. helper: function () {
  8876. var dropWarningEl;
  8877. if (mouseDropWarning) {
  8878. dropWarningEl = mouseDropWarning[0];
  8879. }
  8880. avatar = $(options.avatarCreator(item[0], styles.avatar, dropWarningEl));
  8881. avatar.attr("id", createAvatarId(thatReorderer.container.id));
  8882. return avatar;
  8883. },
  8884. start: function (e, ui) {
  8885. var prevent = thatReorderer.events.onBeginMove.fire(item);
  8886. if (prevent === false) {
  8887. return false;
  8888. }
  8889. var handle = thatReorderer.dom.fastLocate("grabHandle", item)[0];
  8890. var handlePos = fluid.dom.computeAbsolutePosition(handle);
  8891. var handleWidth = handle.offsetWidth;
  8892. var handleHeight = handle.offsetHeight;
  8893. item.focus();
  8894. item.removeClass(options.styles.selected);
  8895. item.addClass(options.styles.mouseDrag);
  8896. item.attr("aria-grabbed", "true");
  8897. setDropEffects("move");
  8898. dropManager.startDrag(e, handlePos, handleWidth, handleHeight);
  8899. avatar.show();
  8900. },
  8901. stop: function (e, ui) {
  8902. item.removeClass(options.styles.mouseDrag);
  8903. item.addClass(options.styles.selected);
  8904. $(thatReorderer.activeItem).attr("aria-grabbed", "false");
  8905. var markerNode = fluid.unwrap(dropMarker);
  8906. if (markerNode.parentNode) {
  8907. markerNode.parentNode.removeChild(markerNode);
  8908. }
  8909. avatar.hide();
  8910. ui.helper = null;
  8911. setDropEffects("none");
  8912. dropManager.endDrag();
  8913. thatReorderer.requestMovement(dropManager.lastPosition(), item);
  8914. // refocus on the active item because moving places focus on the body
  8915. thatReorderer.activeItem.focus();
  8916. },
  8917. handle: thatReorderer.dom.fastLocate("grabHandle", item)
  8918. });
  8919. }
  8920. function changeSelectedToDefault(jItem, styles) {
  8921. jItem.removeClass(styles.selected);
  8922. jItem.removeClass(styles.dragging);
  8923. jItem.addClass(styles.defaultStyle);
  8924. jItem.attr("aria-selected", "false");
  8925. }
  8926. var selectItem = function (anItem) {
  8927. thatReorderer.events.onSelect.fire(anItem);
  8928. var styles = options.styles;
  8929. // Set the previous active item back to its default state.
  8930. if (thatReorderer.activeItem && thatReorderer.activeItem !== anItem) {
  8931. changeSelectedToDefault($(thatReorderer.activeItem), styles);
  8932. }
  8933. // Then select the new item.
  8934. thatReorderer.activeItem = anItem;
  8935. var jItem = $(anItem);
  8936. jItem.removeClass(styles.defaultStyle);
  8937. jItem.addClass(styles.selected);
  8938. jItem.attr("aria-selected", "true");
  8939. };
  8940. var initSelectables = function () {
  8941. var handleBlur = function (evt) {
  8942. changeSelectedToDefault($(this), options.styles);
  8943. return evt.stopPropagation();
  8944. };
  8945. var handleFocus = function (evt) {
  8946. selectItem(this);
  8947. return evt.stopPropagation();
  8948. };
  8949. var selectables = thatReorderer.dom.fastLocate("selectables");
  8950. for (var i = 0; i < selectables.length; ++ i) {
  8951. var selectable = $(selectables[i]);
  8952. if (!$.data(selectable[0], "fluid.reorderer.selectable-initialised")) {
  8953. selectable.addClass(styles.defaultStyle);
  8954. selectables.blur(handleBlur);
  8955. selectables.focus(handleFocus);
  8956. selectables.click(function (evt) {
  8957. var handle = fluid.unwrap(thatReorderer.dom.fastLocate("grabHandle", this));
  8958. if (fluid.dom.isContainer(handle, evt.target)) {
  8959. $(this).focus();
  8960. }
  8961. });
  8962. selectables.attr("role", options.containerRole.item);
  8963. selectables.attr("aria-selected", "false");
  8964. selectables.attr("aria-disabled", "false");
  8965. $.data(selectable[0], "fluid.reorderer.selectable-initialised", true);
  8966. }
  8967. }
  8968. if (!thatReorderer.selectableContext) {
  8969. thatReorderer.selectableContext = fluid.selectable(thatReorderer.container, {
  8970. selectableElements: selectables,
  8971. selectablesTabindex: thatReorderer.options.selectablesTabindex,
  8972. direction: null
  8973. });
  8974. }
  8975. };
  8976. var dropChangeListener = function (dropTarget) {
  8977. fluid.moveDom(dropMarker, dropTarget.element, dropTarget.position);
  8978. dropMarker.css("display", "");
  8979. if (mouseDropWarning) {
  8980. if (dropTarget.lockedelem) {
  8981. mouseDropWarning.show();
  8982. }
  8983. else {
  8984. mouseDropWarning.hide();
  8985. }
  8986. }
  8987. };
  8988. var initItems = function () {
  8989. var movables = thatReorderer.dom.fastLocate("movables");
  8990. var dropTargets = thatReorderer.dom.fastLocate("dropTargets");
  8991. initSelectables();
  8992. // Setup movables
  8993. for (var i = 0; i < movables.length; i++) {
  8994. var item = movables[i];
  8995. if (!$.data(item, "fluid.reorderer.movable-initialised")) {
  8996. initMovable($(item));
  8997. $.data(item, "fluid.reorderer.movable-initialised", true);
  8998. }
  8999. }
  9000. // In order to create valid html, the drop marker is the same type as the node being dragged.
  9001. // This creates a confusing UI in cases such as an ordered list.
  9002. // drop marker functionality should be made pluggable.
  9003. if (movables.length > 0 && !dropMarker) {
  9004. dropMarker = createDropMarker(movables[0].tagName);
  9005. }
  9006. dropManager.updateGeometry(thatReorderer.layoutHandler.getGeometricInfo());
  9007. dropManager.dropChangeFirer.addListener(dropChangeListener, "fluid.Reorderer");
  9008. // Setup dropTargets
  9009. dropTargets.attr("aria-dropeffect", "none");
  9010. };
  9011. // Final initialization of the Reorderer at the end of the construction process
  9012. if (thatReorderer.container) {
  9013. bindHandlersToContainer(thatReorderer.container,
  9014. thatReorderer.handleKeyDown,
  9015. thatReorderer.handleKeyUp);
  9016. addRolesToContainer(thatReorderer);
  9017. fluid.tabbable(thatReorderer.container);
  9018. initItems();
  9019. }
  9020. if (options.afterMoveCallbackUrl) {
  9021. thatReorderer.events.afterMove.addListener(function () {
  9022. var layoutHandler = thatReorderer.layoutHandler;
  9023. var model = layoutHandler.getModel? layoutHandler.getModel():
  9024. options.acquireModel(thatReorderer);
  9025. $.post(options.afterMoveCallbackUrl, JSON.stringify(model));
  9026. }, "postModel");
  9027. }
  9028. thatReorderer.events.onHover.addListener(hoverStyleHandler, "style");
  9029. thatReorderer.refresh = function () {
  9030. thatReorderer.dom.refresh("movables");
  9031. thatReorderer.dom.refresh("selectables");
  9032. thatReorderer.dom.refresh("grabHandle", thatReorderer.dom.fastLocate("movables"));
  9033. thatReorderer.dom.refresh("stylisticOffset", thatReorderer.dom.fastLocate("movables"));
  9034. thatReorderer.dom.refresh("dropTargets");
  9035. thatReorderer.events.onRefresh.fire();
  9036. initItems();
  9037. thatReorderer.selectableContext.selectables = thatReorderer.dom.fastLocate("selectables");
  9038. thatReorderer.selectableContext.selectablesUpdated(thatReorderer.activeItem);
  9039. };
  9040. thatReorderer.refresh();
  9041. return thatReorderer;
  9042. };
  9043. /**
  9044. * Constants for key codes in events.
  9045. */
  9046. fluid.reorderer.keys = {
  9047. TAB: 9,
  9048. ENTER: 13,
  9049. SHIFT: 16,
  9050. CTRL: 17,
  9051. ALT: 18,
  9052. META: 19,
  9053. SPACE: 32,
  9054. LEFT: 37,
  9055. UP: 38,
  9056. RIGHT: 39,
  9057. DOWN: 40,
  9058. i: 73,
  9059. j: 74,
  9060. k: 75,
  9061. m: 77
  9062. };
  9063. /**
  9064. * The default key sets for the Reorderer. Should be moved into the proper component defaults.
  9065. */
  9066. fluid.reorderer.defaultKeysets = [{
  9067. modifier : function (evt) {
  9068. return evt.ctrlKey;
  9069. },
  9070. up : fluid.reorderer.keys.UP,
  9071. down : fluid.reorderer.keys.DOWN,
  9072. right : fluid.reorderer.keys.RIGHT,
  9073. left : fluid.reorderer.keys.LEFT
  9074. },
  9075. {
  9076. modifier : function (evt) {
  9077. return evt.ctrlKey;
  9078. },
  9079. up : fluid.reorderer.keys.i,
  9080. down : fluid.reorderer.keys.m,
  9081. right : fluid.reorderer.keys.k,
  9082. left : fluid.reorderer.keys.j
  9083. }];
  9084. /**
  9085. * These roles are used to add ARIA roles to orderable items. This list can be extended as needed,
  9086. * but the values of the container and item roles must match ARIA-specified roles.
  9087. */
  9088. fluid.reorderer.roles = {
  9089. GRID: { container: "grid", item: "gridcell" },
  9090. LIST: { container: "list", item: "listitem" },
  9091. REGIONS: { container: "main", item: "article" }
  9092. };
  9093. // Simplified API for reordering lists and grids.
  9094. var simpleInit = function (container, layoutHandler, options) {
  9095. options = options || {};
  9096. options.layoutHandler = layoutHandler;
  9097. return fluid.reorderer(container, options);
  9098. };
  9099. fluid.reorderList = function (container, options) {
  9100. return simpleInit(container, "fluid.listLayoutHandler", options);
  9101. };
  9102. fluid.reorderGrid = function (container, options) {
  9103. return simpleInit(container, "fluid.gridLayoutHandler", options);
  9104. };
  9105. fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY = "shuffleProjectFrom";
  9106. fluid.reorderer.GEOMETRIC_STRATEGY = "projectFrom";
  9107. fluid.reorderer.LOGICAL_STRATEGY = "logicalFrom";
  9108. fluid.reorderer.WRAP_LOCKED_STRATEGY = "lockedWrapFrom";
  9109. fluid.reorderer.NO_STRATEGY = null;
  9110. fluid.reorderer.relativeInfoGetter = function (orientation, coStrategy, contraStrategy, dropManager, dom) {
  9111. return function (item, direction, forSelection) {
  9112. var dirorient = fluid.directionOrientation(direction);
  9113. var strategy = dirorient === orientation? coStrategy: contraStrategy;
  9114. return strategy !== null? dropManager[strategy](item, direction, forSelection) : null;
  9115. };
  9116. };
  9117. fluid.defaults("fluid.reorderer", {
  9118. styles: {
  9119. defaultStyle: "fl-reorderer-movable-default",
  9120. selected: "fl-reorderer-movable-selected",
  9121. dragging: "fl-reorderer-movable-dragging",
  9122. mouseDrag: "fl-reorderer-movable-dragging",
  9123. hover: "fl-reorderer-movable-hover",
  9124. dropMarker: "fl-reorderer-dropMarker",
  9125. avatar: "fl-reorderer-avatar"
  9126. },
  9127. selectors: {
  9128. dropWarning: ".flc-reorderer-dropWarning",
  9129. movables: ".flc-reorderer-movable",
  9130. grabHandle: "",
  9131. stylisticOffset: ""
  9132. },
  9133. avatarCreator: defaultAvatarCreator,
  9134. keysets: fluid.reorderer.defaultKeysets,
  9135. layoutHandler: {
  9136. type: "fluid.listLayoutHandler"
  9137. },
  9138. events: {
  9139. onShowKeyboardDropWarning: null,
  9140. onSelect: null,
  9141. onBeginMove: "preventable",
  9142. onMove: null,
  9143. afterMove: null,
  9144. onHover: null,
  9145. onRefresh: null
  9146. },
  9147. mergePolicy: {
  9148. keysets: "replace",
  9149. "selectors.selectables": "selectors.movables",
  9150. "selectors.dropTargets": "selectors.movables"
  9151. }
  9152. });
  9153. /*******************
  9154. * Layout Handlers *
  9155. *******************/
  9156. function geometricInfoGetter(orientation, sentinelize, dom) {
  9157. return function () {
  9158. return {
  9159. sentinelize: sentinelize,
  9160. extents: [{
  9161. orientation: orientation,
  9162. elements: dom.fastLocate("dropTargets")
  9163. }],
  9164. elementMapper: function (element) {
  9165. return $.inArray(element, dom.fastLocate("movables")) === -1? "locked": null;
  9166. }
  9167. };
  9168. };
  9169. }
  9170. fluid.defaults(true, "fluid.listLayoutHandler",
  9171. {orientation: fluid.orientation.VERTICAL,
  9172. containerRole: fluid.reorderer.roles.LIST,
  9173. selectablesTabindex: -1,
  9174. sentinelize: true
  9175. });
  9176. // Public layout handlers.
  9177. fluid.listLayoutHandler = function (container, options, dropManager, dom) {
  9178. var that = {};
  9179. that.getRelativePosition =
  9180. fluid.reorderer.relativeInfoGetter(options.orientation,
  9181. fluid.reorderer.LOGICAL_STRATEGY, null, dropManager, dom);
  9182. that.getGeometricInfo = geometricInfoGetter(options.orientation, options.sentinelize, dom);
  9183. return that;
  9184. }; // End ListLayoutHandler
  9185. fluid.defaults(true, "fluid.gridLayoutHandler",
  9186. {orientation: fluid.orientation.HORIZONTAL,
  9187. containerRole: fluid.reorderer.roles.GRID,
  9188. selectablesTabindex: -1,
  9189. sentinelize: false
  9190. });
  9191. /*
  9192. * Items in the Lightbox are stored in a list, but they are visually presented as a grid that
  9193. * changes dimensions when the window changes size. As a result, when the user presses the up or
  9194. * down arrow key, what lies above or below depends on the current window size.
  9195. *
  9196. * The GridLayoutHandler is responsible for handling changes to this virtual 'grid' of items
  9197. * in the window, and of informing the Lightbox of which items surround a given item.
  9198. */
  9199. fluid.gridLayoutHandler = function (container, options, dropManager, dom) {
  9200. var that = {};
  9201. that.getRelativePosition =
  9202. fluid.reorderer.relativeInfoGetter(options.orientation,
  9203. fluid.reorderer.LOGICAL_STRATEGY, fluid.reorderer.SHUFFLE_GEOMETRIC_STRATEGY,
  9204. dropManager, dom);
  9205. that.getGeometricInfo = geometricInfoGetter(options.orientation, options.sentinelize, dom);
  9206. return that;
  9207. }; // End of GridLayoutHandler
  9208. })(jQuery, fluid_1_1);
  9209. /*
  9210. Copyright 2008-2009 University of Cambridge
  9211. Copyright 2008-2009 University of Toronto
  9212. Copyright 2007-2009 University of California, Berkeley
  9213. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  9214. BSD license. You may not use this file except in compliance with one these
  9215. Licenses.
  9216. You may obtain a copy of the ECL 2.0 License and BSD License at
  9217. https://source.fluidproject.org/svn/LICENSE.txt
  9218. */
  9219. /*global jQuery*/
  9220. /*global fluid_1_1*/
  9221. fluid_1_1 = fluid_1_1 || {};
  9222. (function ($, fluid) {
  9223. var deriveLightboxCellBase = function (namebase, index) {
  9224. return namebase + "lightbox-cell:" + index + ":";
  9225. };
  9226. var addThumbnailActivateHandler = function (lightboxContainer) {
  9227. var enterKeyHandler = function (evt) {
  9228. if (evt.which === fluid.reorderer.keys.ENTER) {
  9229. var thumbnailAnchors = $("a", evt.target);
  9230. document.location = thumbnailAnchors.attr('href');
  9231. }
  9232. };
  9233. $(lightboxContainer).keypress(enterKeyHandler);
  9234. };
  9235. // Custom query method seeks all tags descended from a given root with a
  9236. // particular tag name, whose id matches a regex.
  9237. var seekNodesById = function (rootnode, tagname, idmatch) {
  9238. var inputs = rootnode.getElementsByTagName(tagname);
  9239. var togo = [];
  9240. for (var i = 0; i < inputs.length; i += 1) {
  9241. var input = inputs[i];
  9242. var id = input.id;
  9243. if (id && id.match(idmatch)) {
  9244. togo.push(input);
  9245. }
  9246. }
  9247. return togo;
  9248. };
  9249. var createItemFinder = function (parentNode, containerId) {
  9250. // This orderable finder knows that the lightbox thumbnails are 'div' elements
  9251. var lightboxCellNamePattern = "^" + deriveLightboxCellBase(containerId, "[0-9]+") + "$";
  9252. return function () {
  9253. return seekNodesById(parentNode, "div", lightboxCellNamePattern);
  9254. };
  9255. };
  9256. var findForm = function (element) {
  9257. while (element) {
  9258. if (element.nodeName.toLowerCase() === "form") {
  9259. return element;
  9260. }
  9261. element = element.parentNode;
  9262. }
  9263. };
  9264. /**
  9265. * Returns the default Lightbox order change callback. This callback is used by the Lightbox
  9266. * to send any changes in image order back to the server. It is implemented by nesting
  9267. * a form and set of hidden fields within the Lightbox container which contain the order value
  9268. * for each image displayed in the Lightbox. The default callback submits the form's default
  9269. * action via AJAX.
  9270. *
  9271. * @param {Element} lightboxContainer The DOM element containing the form that is POSTed back to the server upon order change
  9272. */
  9273. var defaultAfterMoveCallback = function (lightboxContainer) {
  9274. var reorderform = findForm(lightboxContainer);
  9275. return function () {
  9276. var inputs, i;
  9277. inputs = seekNodesById(
  9278. reorderform,
  9279. "input",
  9280. "^" + deriveLightboxCellBase(lightboxContainer.id, "[^:]*") + "reorder-index$");
  9281. for (i = 0; i < inputs.length; i += 1) {
  9282. inputs[i].value = i;
  9283. }
  9284. if (reorderform && reorderform.action) {
  9285. $.post(reorderform.action,
  9286. $(reorderform).serialize(),
  9287. function (type, data, evt) { /* No-op response */ });
  9288. }
  9289. };
  9290. };
  9291. fluid.defaults("fluid.reorderImages", {
  9292. layoutHandler: "fluid.gridLayoutHandler",
  9293. selectors: {
  9294. imageTitle: ".flc-reorderer-imageTitle"
  9295. }
  9296. });
  9297. // Public Lightbox API
  9298. /**
  9299. * Creates a new Lightbox instance from the specified parameters, providing full control over how
  9300. * the Lightbox is configured.
  9301. *
  9302. * @param {Object} container
  9303. * @param {Object} options
  9304. */
  9305. fluid.reorderImages = function (container, options) {
  9306. var that = fluid.initView("fluid.reorderImages", container, options);
  9307. var containerEl = fluid.unwrap(that.container);
  9308. if (!that.options.afterMoveCallback) {
  9309. that.options.afterMoveCallback = defaultAfterMoveCallback(containerEl);
  9310. }
  9311. if (!that.options.selectors.movables) {
  9312. that.options.selectors.movables = createItemFinder(containerEl, containerEl.id);
  9313. }
  9314. var reorderer = fluid.reorderer(container, that.options);
  9315. var movables = reorderer.locate("movables");
  9316. fluid.transform(movables, function (cell) {
  9317. fluid.reorderImages.addAriaRoles(that.options.selectors.imageTitle, cell);
  9318. });
  9319. // Remove the anchors from the taborder.
  9320. fluid.tabindex($("a", container), -1);
  9321. addThumbnailActivateHandler(container);
  9322. return reorderer;
  9323. };
  9324. fluid.reorderImages.addAriaRoles = function (imageTitle, cell) {
  9325. cell = $(cell);
  9326. cell.attr("role", "img");
  9327. var title = $(imageTitle, cell);
  9328. if (title[0] === cell[0] || title[0] === document) {
  9329. fluid.fail("Could not locate cell title using selector " + imageTitle + " in context " + fluid.dumpEl(cell));
  9330. }
  9331. var titleId = fluid.allocateSimpleId(title);
  9332. cell.attr("aria-labelledby", titleId);
  9333. var image = $("img", cell);
  9334. image.attr("role", "presentation");
  9335. image.attr("alt", "");
  9336. };
  9337. // This function now deprecated. Please use fluid.reorderImages() instead.
  9338. fluid.lightbox = fluid.reorderImages;
  9339. })(jQuery, fluid_1_1);
  9340. /*
  9341. Copyright 2008-2009 University of Cambridge
  9342. Copyright 2008-2009 University of Toronto
  9343. Copyright 2007-2009 University of California, Berkeley
  9344. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  9345. BSD license. You may not use this file except in compliance with one these
  9346. Licenses.
  9347. You may obtain a copy of the ECL 2.0 License and BSD License at
  9348. https://source.fluidproject.org/svn/LICENSE.txt
  9349. */
  9350. // Declare dependencies.
  9351. /*global jQuery*/
  9352. /*global fluid, fluid_1_1*/
  9353. fluid_1_1 = fluid_1_1 || {};
  9354. (function ($, fluid) {
  9355. fluid.moduleLayout = fluid.moduleLayout || {};
  9356. /**
  9357. * Calculate the location of the item and the column in which it resides.
  9358. * @return An object with column index and item index (within that column) properties.
  9359. * These indices are -1 if the item does not exist in the grid.
  9360. */
  9361. var findColumnAndItemIndices = function (item, layout) {
  9362. return fluid.find(layout.columns,
  9363. function (column, colIndex) {
  9364. var index = $.inArray(item, column.elements);
  9365. return index === -1? null : {columnIndex: colIndex, itemIndex: index};
  9366. }, {columnIndex: -1, itemIndex: -1});
  9367. };
  9368. var findColIndex = function (item, layout) {
  9369. return fluid.find(layout.columns,
  9370. function (column, colIndex) {
  9371. return item === column.container? colIndex : null;
  9372. }, -1);
  9373. };
  9374. /**
  9375. * Move an item within the layout object.
  9376. */
  9377. fluid.moduleLayout.updateLayout = function (item, target, position, layout) {
  9378. item = fluid.unwrap(item);
  9379. target = fluid.unwrap(target);
  9380. var itemIndices = findColumnAndItemIndices(item, layout);
  9381. layout.columns[itemIndices.columnIndex].elements.splice(itemIndices.itemIndex, 1);
  9382. var targetCol;
  9383. if (position === fluid.position.INSIDE) {
  9384. targetCol = layout.columns[findColIndex(target, layout)].elements;
  9385. targetCol.splice(targetCol.length, 0, item);
  9386. } else {
  9387. var relativeItemIndices = findColumnAndItemIndices(target, layout);
  9388. targetCol = layout.columns[relativeItemIndices.columnIndex].elements;
  9389. position = fluid.normalisePosition(position,
  9390. itemIndices.columnIndex === relativeItemIndices.columnIndex,
  9391. relativeItemIndices.itemIndex, itemIndices.itemIndex);
  9392. var relative = position === fluid.position.BEFORE? 0 : 1;
  9393. targetCol.splice(relativeItemIndices.itemIndex + relative, 0, item);
  9394. }
  9395. };
  9396. /**
  9397. * Builds a layout object from a set of columns and modules.
  9398. * @param {jQuery} container
  9399. * @param {jQuery} columns
  9400. * @param {jQuery} portlets
  9401. */
  9402. fluid.moduleLayout.layoutFromFlat = function (container, columns, portlets) {
  9403. var layout = {};
  9404. layout.container = container;
  9405. layout.columns = fluid.transform(columns,
  9406. function (column) {
  9407. return {
  9408. container: column,
  9409. elements: $.makeArray(portlets.filter(function () {
  9410. // is this a bug in filter? would have expected "this" to be 1st arg
  9411. return fluid.dom.isContainer(column, this);
  9412. }))
  9413. };
  9414. });
  9415. return layout;
  9416. };
  9417. /**
  9418. * Builds a layout object from a serialisable "layout" object consisting of id lists
  9419. */
  9420. fluid.moduleLayout.layoutFromIds = function (idLayout) {
  9421. return {
  9422. container: fluid.byId(idLayout.id),
  9423. columns: fluid.transform(idLayout.columns,
  9424. function (column) {
  9425. return {
  9426. container: fluid.byId(column.id),
  9427. elements: fluid.transform(column.children, fluid.byId)
  9428. };
  9429. })
  9430. };
  9431. };
  9432. /**
  9433. * Serializes the current layout into a structure of ids
  9434. */
  9435. fluid.moduleLayout.layoutToIds = function (idLayout) {
  9436. return {
  9437. id: fluid.getId(idLayout.container),
  9438. columns: fluid.transform(idLayout.columns,
  9439. function (column) {
  9440. return {
  9441. id: fluid.getId(column.container),
  9442. children: fluid.transform(column.elements, fluid.getId)
  9443. };
  9444. })
  9445. };
  9446. };
  9447. var defaultOnShowKeyboardDropWarning = function (item, dropWarning) {
  9448. if (dropWarning) {
  9449. var offset = $(item).offset();
  9450. dropWarning = $(dropWarning);
  9451. dropWarning.css("position", "absolute");
  9452. dropWarning.css("top", offset.top);
  9453. dropWarning.css("left", offset.left);
  9454. }
  9455. };
  9456. fluid.defaults(true, "fluid.moduleLayoutHandler",
  9457. {orientation: fluid.orientation.VERTICAL,
  9458. containerRole: fluid.reorderer.roles.REGIONS,
  9459. selectablesTabindex: 0,
  9460. sentinelize: true
  9461. });
  9462. /**
  9463. * Module Layout Handler for reordering content modules.
  9464. *
  9465. * General movement guidelines:
  9466. *
  9467. * - Arrowing sideways will always go to the top (moveable) module in the column
  9468. * - Moving sideways will always move to the top available drop target in the column
  9469. * - Wrapping is not necessary at this first pass, but is ok
  9470. */
  9471. fluid.moduleLayoutHandler = function (container, options, dropManager, dom) {
  9472. var that = {};
  9473. function computeLayout() {
  9474. var togo;
  9475. if (options.selectors.modules) {
  9476. togo = fluid.moduleLayout.layoutFromFlat(container, dom.locate("columns"), dom.locate("modules"));
  9477. }
  9478. if (!togo) {
  9479. var idLayout = fluid.model.getBeanValue(options, "moduleLayout.layout");
  9480. fluid.moduleLayout.layoutFromIds(idLayout);
  9481. }
  9482. return togo;
  9483. }
  9484. var layout = computeLayout();
  9485. that.layout = layout;
  9486. function isLocked(item) {
  9487. var lockedModules = options.selectors.lockedModules? dom.fastLocate("lockedModules") : [];
  9488. return $.inArray(item, lockedModules) !== -1;
  9489. }
  9490. that.getRelativePosition =
  9491. fluid.reorderer.relativeInfoGetter(options.orientation,
  9492. fluid.reorderer.WRAP_LOCKED_STRATEGY, fluid.reorderer.GEOMETRIC_STRATEGY,
  9493. dropManager, dom);
  9494. that.getGeometricInfo = function () {
  9495. var extents = [];
  9496. var togo = {extents: extents,
  9497. sentinelize: options.sentinelize};
  9498. togo.elementMapper = function (element) {
  9499. return isLocked(element)? "locked" : null;
  9500. };
  9501. for (var col = 0; col < layout.columns.length; col++) {
  9502. var column = layout.columns[col];
  9503. var thisEls = {
  9504. orientation: options.orientation,
  9505. elements: $.makeArray(column.elements),
  9506. parentElement: column.container
  9507. };
  9508. // fluid.log("Geometry col " + col + " elements " + fluid.dumpEl(thisEls.elements) + " isLocked [" +
  9509. // fluid.transform(thisEls.elements, togo.elementMapper).join(", ") + "]");
  9510. extents.push(thisEls);
  9511. }
  9512. return togo;
  9513. };
  9514. function computeModules(all) {
  9515. return function () {
  9516. var modules = fluid.accumulate(layout.columns, function (column, list) {
  9517. return list.concat(column.elements); // note that concat will not work on a jQuery
  9518. }, []);
  9519. if (!all) {
  9520. fluid.remove_if(modules, isLocked);
  9521. }
  9522. return modules;
  9523. };
  9524. }
  9525. that.returnedOptions = {
  9526. selectors: {
  9527. movables: computeModules(false),
  9528. dropTargets: computeModules(false),
  9529. selectables: computeModules(true)
  9530. },
  9531. listeners: {
  9532. onMove: function (item, requestedPosition) {
  9533. fluid.moduleLayout.updateLayout(item, requestedPosition.element, requestedPosition.position, layout);
  9534. },
  9535. onRefresh: function () {
  9536. layout = computeLayout();
  9537. that.layout = layout;
  9538. },
  9539. "onShowKeyboardDropWarning.setPosition": defaultOnShowKeyboardDropWarning
  9540. }
  9541. };
  9542. that.getModel = function () {
  9543. return fluid.moduleLayout.layoutToIds(layout);
  9544. };
  9545. return that;
  9546. };
  9547. })(jQuery, fluid_1_1);
  9548. /*
  9549. Copyright 2008-2009 University of Cambridge
  9550. Copyright 2008-2009 University of Toronto
  9551. Copyright 2007-2009 University of California, Berkeley
  9552. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  9553. BSD license. You may not use this file except in compliance with one these
  9554. Licenses.
  9555. You may obtain a copy of the ECL 2.0 License and BSD License at
  9556. https://source.fluidproject.org/svn/LICENSE.txt
  9557. */
  9558. /*global jQuery*/
  9559. /*global fluid_1_1*/
  9560. fluid_1_1 = fluid_1_1 || {};
  9561. (function ($, fluid) {
  9562. /**
  9563. * Simple way to create a layout reorderer.
  9564. * @param {selector} a selector for the layout container
  9565. * @param {Object} a map of selectors for columns and modules within the layout
  9566. * @param {Function} a function to be called when the order changes
  9567. * @param {Object} additional configuration options
  9568. */
  9569. fluid.reorderLayout = function (container, userOptions) {
  9570. var assembleOptions = {
  9571. layoutHandler: "fluid.moduleLayoutHandler",
  9572. selectors: {
  9573. columns: ".flc-reorderer-column",
  9574. modules: ".flc-reorderer-module"
  9575. }
  9576. };
  9577. var options = $.extend(true, assembleOptions, userOptions);
  9578. return fluid.reorderer(container, options);
  9579. };
  9580. })(jQuery, fluid_1_1);
  9581. /*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
  9582. Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
  9583. This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
  9584. */
  9585. var swfobject = function() {
  9586. var UNDEF = "undefined",
  9587. OBJECT = "object",
  9588. SHOCKWAVE_FLASH = "Shockwave Flash",
  9589. SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
  9590. FLASH_MIME_TYPE = "application/x-shockwave-flash",
  9591. EXPRESS_INSTALL_ID = "SWFObjectExprInst",
  9592. win = window,
  9593. doc = document,
  9594. nav = navigator,
  9595. domLoadFnArr = [],
  9596. regObjArr = [],
  9597. objIdArr = [],
  9598. listenersArr = [],
  9599. script,
  9600. timer = null,
  9601. storedAltContent = null,
  9602. storedAltContentId = null,
  9603. isDomLoaded = false,
  9604. isExpressInstallActive = false;
  9605. /* Centralized function for browser feature detection
  9606. - Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
  9607. - User agent string detection is only used when no alternative is possible
  9608. - Is executed directly for optimal performance
  9609. */
  9610. var ua = function() {
  9611. var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
  9612. playerVersion = [0,0,0],
  9613. d = null;
  9614. if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
  9615. d = nav.plugins[SHOCKWAVE_FLASH].description;
  9616. if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
  9617. d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
  9618. playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
  9619. playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
  9620. playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
  9621. }
  9622. }
  9623. else if (typeof win.ActiveXObject != UNDEF) {
  9624. var a = null, fp6Crash = false;
  9625. try {
  9626. a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
  9627. }
  9628. catch(e) {
  9629. try {
  9630. a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
  9631. playerVersion = [6,0,21];
  9632. a.AllowScriptAccess = "always"; // Introduced in fp6.0.47
  9633. }
  9634. catch(e) {
  9635. if (playerVersion[0] == 6) {
  9636. fp6Crash = true;
  9637. }
  9638. }
  9639. if (!fp6Crash) {
  9640. try {
  9641. a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
  9642. }
  9643. catch(e) {}
  9644. }
  9645. }
  9646. if (!fp6Crash && a) { // a will return null when ActiveX is disabled
  9647. try {
  9648. d = a.GetVariable("$version"); // Will crash fp6.0.21/23/29
  9649. if (d) {
  9650. d = d.split(" ")[1].split(",");
  9651. playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
  9652. }
  9653. }
  9654. catch(e) {}
  9655. }
  9656. }
  9657. var u = nav.userAgent.toLowerCase(),
  9658. p = nav.platform.toLowerCase(),
  9659. webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
  9660. ie = false,
  9661. windows = p ? /win/.test(p) : /win/.test(u),
  9662. mac = p ? /mac/.test(p) : /mac/.test(u);
  9663. /*@cc_on
  9664. ie = true;
  9665. @if (@_win32)
  9666. windows = true;
  9667. @elif (@_mac)
  9668. mac = true;
  9669. @end
  9670. @*/
  9671. return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
  9672. }();
  9673. /* Cross-browser onDomLoad
  9674. - Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
  9675. - Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
  9676. */
  9677. var onDomLoad = function() {
  9678. if (!ua.w3cdom) {
  9679. return;
  9680. }
  9681. addDomLoadEvent(main);
  9682. if (ua.ie && ua.win) {
  9683. try { // Avoid a possible Operation Aborted error
  9684. doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors
  9685. script = getElementById("__ie_ondomload");
  9686. if (script) {
  9687. addListener(script, "onreadystatechange", checkReadyState);
  9688. }
  9689. }
  9690. catch(e) {}
  9691. }
  9692. if (ua.webkit && typeof doc.readyState != UNDEF) {
  9693. timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
  9694. }
  9695. if (typeof doc.addEventListener != UNDEF) {
  9696. doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
  9697. }
  9698. addLoadEvent(callDomLoadFunctions);
  9699. }();
  9700. function checkReadyState() {
  9701. if (script.readyState == "complete") {
  9702. script.parentNode.removeChild(script);
  9703. callDomLoadFunctions();
  9704. }
  9705. }
  9706. function callDomLoadFunctions() {
  9707. if (isDomLoaded) {
  9708. return;
  9709. }
  9710. if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
  9711. var s = createElement("span");
  9712. try { // Avoid a possible Operation Aborted error
  9713. var t = doc.getElementsByTagName("body")[0].appendChild(s);
  9714. t.parentNode.removeChild(t);
  9715. }
  9716. catch (e) {
  9717. return;
  9718. }
  9719. }
  9720. isDomLoaded = true;
  9721. if (timer) {
  9722. clearInterval(timer);
  9723. timer = null;
  9724. }
  9725. var dl = domLoadFnArr.length;
  9726. for (var i = 0; i < dl; i++) {
  9727. domLoadFnArr[i]();
  9728. }
  9729. }
  9730. function addDomLoadEvent(fn) {
  9731. if (isDomLoaded) {
  9732. fn();
  9733. }
  9734. else {
  9735. domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
  9736. }
  9737. }
  9738. /* Cross-browser onload
  9739. - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
  9740. - Will fire an event as soon as a web page including all of its assets are loaded
  9741. */
  9742. function addLoadEvent(fn) {
  9743. if (typeof win.addEventListener != UNDEF) {
  9744. win.addEventListener("load", fn, false);
  9745. }
  9746. else if (typeof doc.addEventListener != UNDEF) {
  9747. doc.addEventListener("load", fn, false);
  9748. }
  9749. else if (typeof win.attachEvent != UNDEF) {
  9750. addListener(win, "onload", fn);
  9751. }
  9752. else if (typeof win.onload == "function") {
  9753. var fnOld = win.onload;
  9754. win.onload = function() {
  9755. fnOld();
  9756. fn();
  9757. };
  9758. }
  9759. else {
  9760. win.onload = fn;
  9761. }
  9762. }
  9763. /* Main function
  9764. - Will preferably execute onDomLoad, otherwise onload (as a fallback)
  9765. */
  9766. function main() { // Static publishing only
  9767. var rl = regObjArr.length;
  9768. for (var i = 0; i < rl; i++) { // For each registered object element
  9769. var id = regObjArr[i].id;
  9770. if (ua.pv[0] > 0) {
  9771. var obj = getElementById(id);
  9772. if (obj) {
  9773. regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
  9774. regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
  9775. if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
  9776. if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
  9777. fixParams(obj);
  9778. }
  9779. setVisibility(id, true);
  9780. }
  9781. else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
  9782. showExpressInstall(regObjArr[i]);
  9783. }
  9784. else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
  9785. displayAltContent(obj);
  9786. }
  9787. }
  9788. }
  9789. else { // If no fp is installed, we let the object element do its job (show alternative content)
  9790. setVisibility(id, true);
  9791. }
  9792. }
  9793. }
  9794. /* Fix nested param elements, which are ignored by older webkit engines
  9795. - This includes Safari up to and including version 1.2.2 on Mac OS 10.3
  9796. - Fall back to the proprietary embed element
  9797. */
  9798. function fixParams(obj) {
  9799. var nestedObj = obj.getElementsByTagName(OBJECT)[0];
  9800. if (nestedObj) {
  9801. var e = createElement("embed"), a = nestedObj.attributes;
  9802. if (a) {
  9803. var al = a.length;
  9804. for (var i = 0; i < al; i++) {
  9805. if (a[i].nodeName == "DATA") {
  9806. e.setAttribute("src", a[i].nodeValue);
  9807. }
  9808. else {
  9809. e.setAttribute(a[i].nodeName, a[i].nodeValue);
  9810. }
  9811. }
  9812. }
  9813. var c = nestedObj.childNodes;
  9814. if (c) {
  9815. var cl = c.length;
  9816. for (var j = 0; j < cl; j++) {
  9817. if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
  9818. e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
  9819. }
  9820. }
  9821. }
  9822. obj.parentNode.replaceChild(e, obj);
  9823. }
  9824. }
  9825. /* Show the Adobe Express Install dialog
  9826. - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
  9827. */
  9828. function showExpressInstall(regObj) {
  9829. isExpressInstallActive = true;
  9830. var obj = getElementById(regObj.id);
  9831. if (obj) {
  9832. if (regObj.altContentId) {
  9833. var ac = getElementById(regObj.altContentId);
  9834. if (ac) {
  9835. storedAltContent = ac;
  9836. storedAltContentId = regObj.altContentId;
  9837. }
  9838. }
  9839. else {
  9840. storedAltContent = abstractAltContent(obj);
  9841. }
  9842. if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
  9843. regObj.width = "310";
  9844. }
  9845. if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
  9846. regObj.height = "137";
  9847. }
  9848. doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
  9849. var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
  9850. dt = doc.title,
  9851. fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
  9852. replaceId = regObj.id;
  9853. // For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
  9854. // In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
  9855. if (ua.ie && ua.win && obj.readyState != 4) {
  9856. var newObj = createElement("div");
  9857. replaceId += "SWFObjectNew";
  9858. newObj.setAttribute("id", replaceId);
  9859. obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
  9860. obj.style.display = "none";
  9861. var fn = function() {
  9862. obj.parentNode.removeChild(obj);
  9863. };
  9864. addListener(win, "onload", fn);
  9865. }
  9866. createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
  9867. }
  9868. }
  9869. /* Functions to abstract and display alternative content
  9870. */
  9871. function displayAltContent(obj) {
  9872. if (ua.ie && ua.win && obj.readyState != 4) {
  9873. // For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
  9874. // In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
  9875. var el = createElement("div");
  9876. obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
  9877. el.parentNode.replaceChild(abstractAltContent(obj), el);
  9878. obj.style.display = "none";
  9879. var fn = function() {
  9880. obj.parentNode.removeChild(obj);
  9881. };
  9882. addListener(win, "onload", fn);
  9883. }
  9884. else {
  9885. obj.parentNode.replaceChild(abstractAltContent(obj), obj);
  9886. }
  9887. }
  9888. function abstractAltContent(obj) {
  9889. var ac = createElement("div");
  9890. if (ua.win && ua.ie) {
  9891. ac.innerHTML = obj.innerHTML;
  9892. }
  9893. else {
  9894. var nestedObj = obj.getElementsByTagName(OBJECT)[0];
  9895. if (nestedObj) {
  9896. var c = nestedObj.childNodes;
  9897. if (c) {
  9898. var cl = c.length;
  9899. for (var i = 0; i < cl; i++) {
  9900. if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
  9901. ac.appendChild(c[i].cloneNode(true));
  9902. }
  9903. }
  9904. }
  9905. }
  9906. }
  9907. return ac;
  9908. }
  9909. /* Cross-browser dynamic SWF creation
  9910. */
  9911. function createSWF(attObj, parObj, id) {
  9912. var r, el = getElementById(id);
  9913. if (el) {
  9914. if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
  9915. attObj.id = id;
  9916. }
  9917. if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
  9918. var att = "";
  9919. for (var i in attObj) {
  9920. if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
  9921. if (i.toLowerCase() == "data") {
  9922. parObj.movie = attObj[i];
  9923. }
  9924. else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
  9925. att += ' class="' + attObj[i] + '"';
  9926. }
  9927. else if (i.toLowerCase() != "classid") {
  9928. att += ' ' + i + '="' + attObj[i] + '"';
  9929. }
  9930. }
  9931. }
  9932. var par = "";
  9933. for (var j in parObj) {
  9934. if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
  9935. par += '<param name="' + j + '" value="' + parObj[j] + '" />';
  9936. }
  9937. }
  9938. el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
  9939. objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
  9940. r = getElementById(attObj.id);
  9941. }
  9942. else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
  9943. var e = createElement("embed");
  9944. e.setAttribute("type", FLASH_MIME_TYPE);
  9945. for (var k in attObj) {
  9946. if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
  9947. if (k.toLowerCase() == "data") {
  9948. e.setAttribute("src", attObj[k]);
  9949. }
  9950. else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
  9951. e.setAttribute("class", attObj[k]);
  9952. }
  9953. else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
  9954. e.setAttribute(k, attObj[k]);
  9955. }
  9956. }
  9957. }
  9958. for (var l in parObj) {
  9959. if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
  9960. if (l.toLowerCase() != "movie") { // Filter out IE specific param element
  9961. e.setAttribute(l, parObj[l]);
  9962. }
  9963. }
  9964. }
  9965. el.parentNode.replaceChild(e, el);
  9966. r = e;
  9967. }
  9968. else { // Well-behaving browsers
  9969. var o = createElement(OBJECT);
  9970. o.setAttribute("type", FLASH_MIME_TYPE);
  9971. for (var m in attObj) {
  9972. if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
  9973. if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
  9974. o.setAttribute("class", attObj[m]);
  9975. }
  9976. else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
  9977. o.setAttribute(m, attObj[m]);
  9978. }
  9979. }
  9980. }
  9981. for (var n in parObj) {
  9982. if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
  9983. createObjParam(o, n, parObj[n]);
  9984. }
  9985. }
  9986. el.parentNode.replaceChild(o, el);
  9987. r = o;
  9988. }
  9989. }
  9990. return r;
  9991. }
  9992. function createObjParam(el, pName, pValue) {
  9993. var p = createElement("param");
  9994. p.setAttribute("name", pName);
  9995. p.setAttribute("value", pValue);
  9996. el.appendChild(p);
  9997. }
  9998. /* Cross-browser SWF removal
  9999. - Especially needed to safely and completely remove a SWF in Internet Explorer
  10000. */
  10001. function removeSWF(id) {
  10002. var obj = getElementById(id);
  10003. if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
  10004. if (ua.ie && ua.win) {
  10005. if (obj.readyState == 4) {
  10006. removeObjectInIE(id);
  10007. }
  10008. else {
  10009. win.attachEvent("onload", function() {
  10010. removeObjectInIE(id);
  10011. });
  10012. }
  10013. }
  10014. else {
  10015. obj.parentNode.removeChild(obj);
  10016. }
  10017. }
  10018. }
  10019. function removeObjectInIE(id) {
  10020. var obj = getElementById(id);
  10021. if (obj) {
  10022. for (var i in obj) {
  10023. if (typeof obj[i] == "function") {
  10024. obj[i] = null;
  10025. }
  10026. }
  10027. obj.parentNode.removeChild(obj);
  10028. }
  10029. }
  10030. /* Functions to optimize JavaScript compression
  10031. */
  10032. function getElementById(id) {
  10033. var el = null;
  10034. try {
  10035. el = doc.getElementById(id);
  10036. }
  10037. catch (e) {}
  10038. return el;
  10039. }
  10040. function createElement(el) {
  10041. return doc.createElement(el);
  10042. }
  10043. /* Updated attachEvent function for Internet Explorer
  10044. - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
  10045. */
  10046. function addListener(target, eventType, fn) {
  10047. target.attachEvent(eventType, fn);
  10048. listenersArr[listenersArr.length] = [target, eventType, fn];
  10049. }
  10050. /* Flash Player and SWF content version matching
  10051. */
  10052. function hasPlayerVersion(rv) {
  10053. var pv = ua.pv, v = rv.split(".");
  10054. v[0] = parseInt(v[0], 10);
  10055. v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
  10056. v[2] = parseInt(v[2], 10) || 0;
  10057. return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
  10058. }
  10059. /* Cross-browser dynamic CSS creation
  10060. - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
  10061. */
  10062. function createCSS(sel, decl) {
  10063. if (ua.ie && ua.mac) {
  10064. return;
  10065. }
  10066. var h = doc.getElementsByTagName("head")[0], s = createElement("style");
  10067. s.setAttribute("type", "text/css");
  10068. s.setAttribute("media", "screen");
  10069. if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
  10070. s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
  10071. }
  10072. h.appendChild(s);
  10073. if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
  10074. var ls = doc.styleSheets[doc.styleSheets.length - 1];
  10075. if (typeof ls.addRule == OBJECT) {
  10076. ls.addRule(sel, decl);
  10077. }
  10078. }
  10079. }
  10080. function setVisibility(id, isVisible) {
  10081. var v = isVisible ? "visible" : "hidden";
  10082. if (isDomLoaded && getElementById(id)) {
  10083. getElementById(id).style.visibility = v;
  10084. }
  10085. else {
  10086. createCSS("#" + id, "visibility:" + v);
  10087. }
  10088. }
  10089. /* Filter to avoid XSS attacks
  10090. */
  10091. function urlEncodeIfNecessary(s) {
  10092. var regex = /[\\\"<>\.;]/;
  10093. var hasBadChars = regex.exec(s) != null;
  10094. return hasBadChars ? encodeURIComponent(s) : s;
  10095. }
  10096. /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
  10097. */
  10098. var cleanup = function() {
  10099. if (ua.ie && ua.win) {
  10100. window.attachEvent("onunload", function() {
  10101. // remove listeners to avoid memory leaks
  10102. var ll = listenersArr.length;
  10103. for (var i = 0; i < ll; i++) {
  10104. listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
  10105. }
  10106. // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
  10107. var il = objIdArr.length;
  10108. for (var j = 0; j < il; j++) {
  10109. removeSWF(objIdArr[j]);
  10110. }
  10111. // cleanup library's main closures to avoid memory leaks
  10112. for (var k in ua) {
  10113. ua[k] = null;
  10114. }
  10115. ua = null;
  10116. for (var l in swfobject) {
  10117. swfobject[l] = null;
  10118. }
  10119. swfobject = null;
  10120. });
  10121. }
  10122. }();
  10123. return {
  10124. /* Public API
  10125. - Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
  10126. */
  10127. registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
  10128. if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
  10129. return;
  10130. }
  10131. var regObj = {};
  10132. regObj.id = objectIdStr;
  10133. regObj.swfVersion = swfVersionStr;
  10134. regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
  10135. regObjArr[regObjArr.length] = regObj;
  10136. setVisibility(objectIdStr, false);
  10137. },
  10138. getObjectById: function(objectIdStr) {
  10139. var r = null;
  10140. if (ua.w3cdom) {
  10141. var o = getElementById(objectIdStr);
  10142. if (o) {
  10143. var n = o.getElementsByTagName(OBJECT)[0];
  10144. if (!n || (n && typeof o.SetVariable != UNDEF)) {
  10145. r = o;
  10146. }
  10147. else if (typeof n.SetVariable != UNDEF) {
  10148. r = n;
  10149. }
  10150. }
  10151. }
  10152. return r;
  10153. },
  10154. embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
  10155. if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
  10156. return;
  10157. }
  10158. widthStr += ""; // Auto-convert to string
  10159. heightStr += "";
  10160. if (hasPlayerVersion(swfVersionStr)) {
  10161. setVisibility(replaceElemIdStr, false);
  10162. var att = {};
  10163. if (attObj && typeof attObj === OBJECT) {
  10164. for (var i in attObj) {
  10165. if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
  10166. att[i] = attObj[i];
  10167. }
  10168. }
  10169. }
  10170. att.data = swfUrlStr;
  10171. att.width = widthStr;
  10172. att.height = heightStr;
  10173. var par = {};
  10174. if (parObj && typeof parObj === OBJECT) {
  10175. for (var j in parObj) {
  10176. if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
  10177. par[j] = parObj[j];
  10178. }
  10179. }
  10180. }
  10181. if (flashvarsObj && typeof flashvarsObj === OBJECT) {
  10182. for (var k in flashvarsObj) {
  10183. if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
  10184. if (typeof par.flashvars != UNDEF) {
  10185. par.flashvars += "&" + k + "=" + flashvarsObj[k];
  10186. }
  10187. else {
  10188. par.flashvars = k + "=" + flashvarsObj[k];
  10189. }
  10190. }
  10191. }
  10192. }
  10193. addDomLoadEvent(function() {
  10194. createSWF(att, par, replaceElemIdStr);
  10195. if (att.id == replaceElemIdStr) {
  10196. setVisibility(replaceElemIdStr, true);
  10197. }
  10198. });
  10199. }
  10200. else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
  10201. isExpressInstallActive = true; // deferred execution
  10202. setVisibility(replaceElemIdStr, false);
  10203. addDomLoadEvent(function() {
  10204. var regObj = {};
  10205. regObj.id = regObj.altContentId = replaceElemIdStr;
  10206. regObj.width = widthStr;
  10207. regObj.height = heightStr;
  10208. regObj.expressInstall = xiSwfUrlStr;
  10209. showExpressInstall(regObj);
  10210. });
  10211. }
  10212. },
  10213. getFlashPlayerVersion: function() {
  10214. return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
  10215. },
  10216. hasFlashPlayerVersion: hasPlayerVersion,
  10217. createSWF: function(attObj, parObj, replaceElemIdStr) {
  10218. if (ua.w3cdom) {
  10219. return createSWF(attObj, parObj, replaceElemIdStr);
  10220. }
  10221. else {
  10222. return undefined;
  10223. }
  10224. },
  10225. removeSWF: function(objElemIdStr) {
  10226. if (ua.w3cdom) {
  10227. removeSWF(objElemIdStr);
  10228. }
  10229. },
  10230. createCSS: function(sel, decl) {
  10231. if (ua.w3cdom) {
  10232. createCSS(sel, decl);
  10233. }
  10234. },
  10235. addDomLoadEvent: addDomLoadEvent,
  10236. addLoadEvent: addLoadEvent,
  10237. getQueryParamValue: function(param) {
  10238. var q = doc.location.search || doc.location.hash;
  10239. if (param == null) {
  10240. return urlEncodeIfNecessary(q);
  10241. }
  10242. if (q) {
  10243. var pairs = q.substring(1).split("&");
  10244. for (var i = 0; i < pairs.length; i++) {
  10245. if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
  10246. return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
  10247. }
  10248. }
  10249. }
  10250. return "";
  10251. },
  10252. // For internal usage only
  10253. expressInstallCallback: function() {
  10254. if (isExpressInstallActive && storedAltContent) {
  10255. var obj = getElementById(EXPRESS_INSTALL_ID);
  10256. if (obj) {
  10257. obj.parentNode.replaceChild(storedAltContent, obj);
  10258. if (storedAltContentId) {
  10259. setVisibility(storedAltContentId, true);
  10260. if (ua.ie && ua.win) {
  10261. storedAltContent.style.display = "block";
  10262. }
  10263. }
  10264. storedAltContent = null;
  10265. storedAltContentId = null;
  10266. isExpressInstallActive = false;
  10267. }
  10268. }
  10269. }
  10270. };
  10271. }();
  10272. /**
  10273. * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
  10274. *
  10275. * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/
  10276. *
  10277. * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz?n and Mammon Media and is released under the MIT License:
  10278. * http://www.opensource.org/licenses/mit-license.php
  10279. *
  10280. * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
  10281. * http://www.opensource.org/licenses/mit-license.php
  10282. *
  10283. */
  10284. /* ******************* */
  10285. /* Constructor & Init */
  10286. /* ******************* */
  10287. var SWFUpload;
  10288. if (SWFUpload == undefined) {
  10289. SWFUpload = function (settings) {
  10290. this.initSWFUpload(settings);
  10291. };
  10292. }
  10293. SWFUpload.prototype.initSWFUpload = function (settings) {
  10294. try {
  10295. this.customSettings = {}; // A container where developers can place their own settings associated with this instance.
  10296. this.settings = settings;
  10297. this.eventQueue = [];
  10298. this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
  10299. this.movieElement = null;
  10300. // Setup global control tracking
  10301. SWFUpload.instances[this.movieName] = this;
  10302. // Load the settings. Load the Flash movie.
  10303. this.initSettings();
  10304. this.loadFlash();
  10305. this.displayDebugInfo();
  10306. } catch (ex) {
  10307. delete SWFUpload.instances[this.movieName];
  10308. throw ex;
  10309. }
  10310. };
  10311. /* *************** */
  10312. /* Static Members */
  10313. /* *************** */
  10314. SWFUpload.instances = {};
  10315. SWFUpload.movieCount = 0;
  10316. SWFUpload.version = "2.2.0 2009-03-25";
  10317. SWFUpload.QUEUE_ERROR = {
  10318. QUEUE_LIMIT_EXCEEDED : -100,
  10319. FILE_EXCEEDS_SIZE_LIMIT : -110,
  10320. ZERO_BYTE_FILE : -120,
  10321. INVALID_FILETYPE : -130
  10322. };
  10323. SWFUpload.UPLOAD_ERROR = {
  10324. HTTP_ERROR : -200,
  10325. MISSING_UPLOAD_URL : -210,
  10326. IO_ERROR : -220,
  10327. SECURITY_ERROR : -230,
  10328. UPLOAD_LIMIT_EXCEEDED : -240,
  10329. UPLOAD_FAILED : -250,
  10330. SPECIFIED_FILE_ID_NOT_FOUND : -260,
  10331. FILE_VALIDATION_FAILED : -270,
  10332. FILE_CANCELLED : -280,
  10333. UPLOAD_STOPPED : -290
  10334. };
  10335. SWFUpload.FILE_STATUS = {
  10336. QUEUED : -1,
  10337. IN_PROGRESS : -2,
  10338. ERROR : -3,
  10339. COMPLETE : -4,
  10340. CANCELLED : -5
  10341. };
  10342. SWFUpload.BUTTON_ACTION = {
  10343. SELECT_FILE : -100,
  10344. SELECT_FILES : -110,
  10345. START_UPLOAD : -120
  10346. };
  10347. SWFUpload.CURSOR = {
  10348. ARROW : -1,
  10349. HAND : -2
  10350. };
  10351. SWFUpload.WINDOW_MODE = {
  10352. WINDOW : "window",
  10353. TRANSPARENT : "transparent",
  10354. OPAQUE : "opaque"
  10355. };
  10356. // Private: takes a URL, determines if it is relative and converts to an absolute URL
  10357. // using the current site. Only processes the URL if it can, otherwise returns the URL untouched
  10358. SWFUpload.completeURL = function(url) {
  10359. if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
  10360. return url;
  10361. }
  10362. var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
  10363. var indexSlash = window.location.pathname.lastIndexOf("/");
  10364. if (indexSlash <= 0) {
  10365. path = "/";
  10366. } else {
  10367. path = window.location.pathname.substr(0, indexSlash) + "/";
  10368. }
  10369. return /*currentURL +*/ path + url;
  10370. };
  10371. /* ******************** */
  10372. /* Instance Members */
  10373. /* ******************** */
  10374. // Private: initSettings ensures that all the
  10375. // settings are set, getting a default value if one was not assigned.
  10376. SWFUpload.prototype.initSettings = function () {
  10377. this.ensureDefault = function (settingName, defaultValue) {
  10378. this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
  10379. };
  10380. // Upload backend settings
  10381. this.ensureDefault("upload_url", "");
  10382. this.ensureDefault("preserve_relative_urls", false);
  10383. this.ensureDefault("file_post_name", "Filedata");
  10384. this.ensureDefault("post_params", {});
  10385. this.ensureDefault("use_query_string", false);
  10386. this.ensureDefault("requeue_on_error", false);
  10387. this.ensureDefault("http_success", []);
  10388. this.ensureDefault("assume_success_timeout", 0);
  10389. // File Settings
  10390. this.ensureDefault("file_types", "*.*");
  10391. this.ensureDefault("file_types_description", "All Files");
  10392. this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited"
  10393. this.ensureDefault("file_upload_limit", 0);
  10394. this.ensureDefault("file_queue_limit", 0);
  10395. // Flash Settings
  10396. this.ensureDefault("flash_url", "swfupload.swf");
  10397. this.ensureDefault("prevent_swf_caching", true);
  10398. // Button Settings
  10399. this.ensureDefault("button_image_url", "");
  10400. this.ensureDefault("button_width", 1);
  10401. this.ensureDefault("button_height", 1);
  10402. this.ensureDefault("button_text", "");
  10403. this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
  10404. this.ensureDefault("button_text_top_padding", 0);
  10405. this.ensureDefault("button_text_left_padding", 0);
  10406. this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
  10407. this.ensureDefault("button_disabled", false);
  10408. this.ensureDefault("button_placeholder_id", "");
  10409. this.ensureDefault("button_placeholder", null);
  10410. this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
  10411. this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
  10412. // Debug Settings
  10413. this.ensureDefault("debug", false);
  10414. this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API
  10415. // Event Handlers
  10416. this.settings.return_upload_start_handler = this.returnUploadStart;
  10417. this.ensureDefault("swfupload_loaded_handler", null);
  10418. this.ensureDefault("file_dialog_start_handler", null);
  10419. this.ensureDefault("file_queued_handler", null);
  10420. this.ensureDefault("file_queue_error_handler", null);
  10421. this.ensureDefault("file_dialog_complete_handler", null);
  10422. this.ensureDefault("upload_start_handler", null);
  10423. this.ensureDefault("upload_progress_handler", null);
  10424. this.ensureDefault("upload_error_handler", null);
  10425. this.ensureDefault("upload_success_handler", null);
  10426. this.ensureDefault("upload_complete_handler", null);
  10427. this.ensureDefault("debug_handler", this.debugMessage);
  10428. this.ensureDefault("custom_settings", {});
  10429. // Other settings
  10430. this.customSettings = this.settings.custom_settings;
  10431. // Update the flash url if needed
  10432. if (!!this.settings.prevent_swf_caching) {
  10433. this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
  10434. }
  10435. if (!this.settings.preserve_relative_urls) {
  10436. //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it
  10437. this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
  10438. this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
  10439. }
  10440. delete this.ensureDefault;
  10441. };
  10442. // Private: loadFlash replaces the button_placeholder element with the flash movie.
  10443. SWFUpload.prototype.loadFlash = function () {
  10444. var targetElement, tempParent;
  10445. // Make sure an element with the ID we are going to use doesn't already exist
  10446. if (document.getElementById(this.movieName) !== null) {
  10447. throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
  10448. }
  10449. // Get the element where we will be placing the flash movie
  10450. targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;
  10451. if (targetElement == undefined) {
  10452. throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
  10453. }
  10454. // Append the container and load the flash
  10455. tempParent = document.createElement("div");
  10456. tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
  10457. targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);
  10458. // Fix IE Flash/Form bug
  10459. if (window[this.movieName] == undefined) {
  10460. window[this.movieName] = this.getMovieElement();
  10461. }
  10462. };
  10463. // Private: getFlashHTML generates the object tag needed to embed the flash in to the document
  10464. SWFUpload.prototype.getFlashHTML = function () {
  10465. // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
  10466. return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
  10467. '<param name="wmode" value="', this.settings.button_window_mode, '" />',
  10468. '<param name="movie" value="', this.settings.flash_url, '" />',
  10469. '<param name="quality" value="high" />',
  10470. '<param name="menu" value="false" />',
  10471. '<param name="allowScriptAccess" value="always" />',
  10472. '<param name="flashvars" value="' + this.getFlashVars() + '" />',
  10473. '</object>'].join("");
  10474. };
  10475. // Private: getFlashVars builds the parameter string that will be passed
  10476. // to flash in the flashvars param.
  10477. SWFUpload.prototype.getFlashVars = function () {
  10478. // Build a string from the post param object
  10479. var paramString = this.buildParamString();
  10480. var httpSuccessString = this.settings.http_success.join(",");
  10481. // Build the parameter string
  10482. return ["movieName=", encodeURIComponent(this.movieName),
  10483. "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
  10484. "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
  10485. "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
  10486. "&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
  10487. "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
  10488. "&amp;params=", encodeURIComponent(paramString),
  10489. "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
  10490. "&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
  10491. "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
  10492. "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
  10493. "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
  10494. "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
  10495. "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
  10496. "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
  10497. "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
  10498. "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
  10499. "&amp;buttonText=", encodeURIComponent(this.settings.button_text),
  10500. "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
  10501. "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
  10502. "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
  10503. "&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
  10504. "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
  10505. "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
  10506. ].join("");
  10507. };
  10508. // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
  10509. // The element is cached after the first lookup
  10510. SWFUpload.prototype.getMovieElement = function () {
  10511. if (this.movieElement == undefined) {
  10512. this.movieElement = document.getElementById(this.movieName);
  10513. }
  10514. if (this.movieElement === null) {
  10515. throw "Could not find Flash element";
  10516. }
  10517. return this.movieElement;
  10518. };
  10519. // Private: buildParamString takes the name/value pairs in the post_params setting object
  10520. // and joins them up in to a string formatted "name=value&amp;name=value"
  10521. SWFUpload.prototype.buildParamString = function () {
  10522. var postParams = this.settings.post_params;
  10523. var paramStringPairs = [];
  10524. if (typeof(postParams) === "object") {
  10525. for (var name in postParams) {
  10526. if (postParams.hasOwnProperty(name)) {
  10527. paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
  10528. }
  10529. }
  10530. }
  10531. return paramStringPairs.join("&amp;");
  10532. };
  10533. // Public: Used to remove a SWFUpload instance from the page. This method strives to remove
  10534. // all references to the SWF, and other objects so memory is properly freed.
  10535. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
  10536. // Credits: Major improvements provided by steffen
  10537. SWFUpload.prototype.destroy = function () {
  10538. try {
  10539. // Make sure Flash is done before we try to remove it
  10540. this.cancelUpload(null, false);
  10541. // Remove the SWFUpload DOM nodes
  10542. var movieElement = null;
  10543. movieElement = this.getMovieElement();
  10544. if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  10545. // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
  10546. for (var i in movieElement) {
  10547. try {
  10548. if (typeof(movieElement[i]) === "function") {
  10549. movieElement[i] = null;
  10550. }
  10551. } catch (ex1) {}
  10552. }
  10553. // Remove the Movie Element from the page
  10554. try {
  10555. movieElement.parentNode.removeChild(movieElement);
  10556. } catch (ex) {}
  10557. }
  10558. // Remove IE form fix reference
  10559. window[this.movieName] = null;
  10560. // Destroy other references
  10561. SWFUpload.instances[this.movieName] = null;
  10562. delete SWFUpload.instances[this.movieName];
  10563. this.movieElement = null;
  10564. this.settings = null;
  10565. this.customSettings = null;
  10566. this.eventQueue = null;
  10567. this.movieName = null;
  10568. return true;
  10569. } catch (ex2) {
  10570. return false;
  10571. }
  10572. };
  10573. // Public: displayDebugInfo prints out settings and configuration
  10574. // information about this SWFUpload instance.
  10575. // This function (and any references to it) can be deleted when placing
  10576. // SWFUpload in production.
  10577. SWFUpload.prototype.displayDebugInfo = function () {
  10578. this.debug(
  10579. [
  10580. "---SWFUpload Instance Info---\n",
  10581. "Version: ", SWFUpload.version, "\n",
  10582. "Movie Name: ", this.movieName, "\n",
  10583. "Settings:\n",
  10584. "\t", "upload_url: ", this.settings.upload_url, "\n",
  10585. "\t", "flash_url: ", this.settings.flash_url, "\n",
  10586. "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n",
  10587. "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n",
  10588. "\t", "http_success: ", this.settings.http_success.join(", "), "\n",
  10589. "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n",
  10590. "\t", "file_post_name: ", this.settings.file_post_name, "\n",
  10591. "\t", "post_params: ", this.settings.post_params.toString(), "\n",
  10592. "\t", "file_types: ", this.settings.file_types, "\n",
  10593. "\t", "file_types_description: ", this.settings.file_types_description, "\n",
  10594. "\t", "file_size_limit: ", this.settings.file_size_limit, "\n",
  10595. "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n",
  10596. "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n",
  10597. "\t", "debug: ", this.settings.debug.toString(), "\n",
  10598. "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n",
  10599. "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n",
  10600. "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
  10601. "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n",
  10602. "\t", "button_width: ", this.settings.button_width.toString(), "\n",
  10603. "\t", "button_height: ", this.settings.button_height.toString(), "\n",
  10604. "\t", "button_text: ", this.settings.button_text.toString(), "\n",
  10605. "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n",
  10606. "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n",
  10607. "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
  10608. "\t", "button_action: ", this.settings.button_action.toString(), "\n",
  10609. "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n",
  10610. "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n",
  10611. "Event Handlers:\n",
  10612. "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
  10613. "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
  10614. "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
  10615. "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
  10616. "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
  10617. "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
  10618. "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
  10619. "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
  10620. "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
  10621. "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n"
  10622. ].join("")
  10623. );
  10624. };
  10625. /* Note: addSetting and getSetting are no longer used by SWFUpload but are included
  10626. the maintain v2 API compatibility
  10627. */
  10628. // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
  10629. SWFUpload.prototype.addSetting = function (name, value, default_value) {
  10630. if (value == undefined) {
  10631. return (this.settings[name] = default_value);
  10632. } else {
  10633. return (this.settings[name] = value);
  10634. }
  10635. };
  10636. // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
  10637. SWFUpload.prototype.getSetting = function (name) {
  10638. if (this.settings[name] != undefined) {
  10639. return this.settings[name];
  10640. }
  10641. return "";
  10642. };
  10643. // Private: callFlash handles function calls made to the Flash element.
  10644. // Calls are made with a setTimeout for some functions to work around
  10645. // bugs in the ExternalInterface library.
  10646. SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
  10647. argumentArray = argumentArray || [];
  10648. var movieElement = this.getMovieElement();
  10649. var returnValue, returnString;
  10650. // Flash's method if calling ExternalInterface methods (code adapted from MooTools).
  10651. try {
  10652. returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
  10653. returnValue = eval(returnString);
  10654. } catch (ex) {
  10655. throw "Call to " + functionName + " failed";
  10656. }
  10657. // Unescape file post param values
  10658. if (returnValue != undefined && typeof returnValue.post === "object") {
  10659. returnValue = this.unescapeFilePostParams(returnValue);
  10660. }
  10661. return returnValue;
  10662. };
  10663. /* *****************************
  10664. -- Flash control methods --
  10665. Your UI should use these
  10666. to operate SWFUpload
  10667. ***************************** */
  10668. // WARNING: this function does not work in Flash Player 10
  10669. // Public: selectFile causes a File Selection Dialog window to appear. This
  10670. // dialog only allows 1 file to be selected.
  10671. SWFUpload.prototype.selectFile = function () {
  10672. this.callFlash("SelectFile");
  10673. };
  10674. // WARNING: this function does not work in Flash Player 10
  10675. // Public: selectFiles causes a File Selection Dialog window to appear/ This
  10676. // dialog allows the user to select any number of files
  10677. // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
  10678. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around
  10679. // for this bug.
  10680. SWFUpload.prototype.selectFiles = function () {
  10681. this.callFlash("SelectFiles");
  10682. };
  10683. // Public: startUpload starts uploading the first file in the queue unless
  10684. // the optional parameter 'fileID' specifies the ID
  10685. SWFUpload.prototype.startUpload = function (fileID) {
  10686. this.callFlash("StartUpload", [fileID]);
  10687. };
  10688. // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index.
  10689. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
  10690. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
  10691. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
  10692. if (triggerErrorEvent !== false) {
  10693. triggerErrorEvent = true;
  10694. }
  10695. this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
  10696. };
  10697. // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
  10698. // If nothing is currently uploading then nothing happens.
  10699. SWFUpload.prototype.stopUpload = function () {
  10700. this.callFlash("StopUpload");
  10701. };
  10702. /* ************************
  10703. * Settings methods
  10704. * These methods change the SWFUpload settings.
  10705. * SWFUpload settings should not be changed directly on the settings object
  10706. * since many of the settings need to be passed to Flash in order to take
  10707. * effect.
  10708. * *********************** */
  10709. // Public: getStats gets the file statistics object.
  10710. SWFUpload.prototype.getStats = function () {
  10711. return this.callFlash("GetStats");
  10712. };
  10713. // Public: setStats changes the SWFUpload statistics. You shouldn't need to
  10714. // change the statistics but you can. Changing the statistics does not
  10715. // affect SWFUpload accept for the successful_uploads count which is used
  10716. // by the upload_limit setting to determine how many files the user may upload.
  10717. SWFUpload.prototype.setStats = function (statsObject) {
  10718. this.callFlash("SetStats", [statsObject]);
  10719. };
  10720. // Public: getFile retrieves a File object by ID or Index. If the file is
  10721. // not found then 'null' is returned.
  10722. SWFUpload.prototype.getFile = function (fileID) {
  10723. if (typeof(fileID) === "number") {
  10724. return this.callFlash("GetFileByIndex", [fileID]);
  10725. } else {
  10726. return this.callFlash("GetFile", [fileID]);
  10727. }
  10728. };
  10729. // Public: addFileParam sets a name/value pair that will be posted with the
  10730. // file specified by the Files ID. If the name already exists then the
  10731. // exiting value will be overwritten.
  10732. SWFUpload.prototype.addFileParam = function (fileID, name, value) {
  10733. return this.callFlash("AddFileParam", [fileID, name, value]);
  10734. };
  10735. // Public: removeFileParam removes a previously set (by addFileParam) name/value
  10736. // pair from the specified file.
  10737. SWFUpload.prototype.removeFileParam = function (fileID, name) {
  10738. this.callFlash("RemoveFileParam", [fileID, name]);
  10739. };
  10740. // Public: setUploadUrl changes the upload_url setting.
  10741. SWFUpload.prototype.setUploadURL = function (url) {
  10742. this.settings.upload_url = url.toString();
  10743. this.callFlash("SetUploadURL", [url]);
  10744. };
  10745. // Public: setPostParams changes the post_params setting
  10746. SWFUpload.prototype.setPostParams = function (paramsObject) {
  10747. this.settings.post_params = paramsObject;
  10748. this.callFlash("SetPostParams", [paramsObject]);
  10749. };
  10750. // Public: addPostParam adds post name/value pair. Each name can have only one value.
  10751. SWFUpload.prototype.addPostParam = function (name, value) {
  10752. this.settings.post_params[name] = value;
  10753. this.callFlash("SetPostParams", [this.settings.post_params]);
  10754. };
  10755. // Public: removePostParam deletes post name/value pair.
  10756. SWFUpload.prototype.removePostParam = function (name) {
  10757. delete this.settings.post_params[name];
  10758. this.callFlash("SetPostParams", [this.settings.post_params]);
  10759. };
  10760. // Public: setFileTypes changes the file_types setting and the file_types_description setting
  10761. SWFUpload.prototype.setFileTypes = function (types, description) {
  10762. this.settings.file_types = types;
  10763. this.settings.file_types_description = description;
  10764. this.callFlash("SetFileTypes", [types, description]);
  10765. };
  10766. // Public: setFileSizeLimit changes the file_size_limit setting
  10767. SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
  10768. this.settings.file_size_limit = fileSizeLimit;
  10769. this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
  10770. };
  10771. // Public: setFileUploadLimit changes the file_upload_limit setting
  10772. SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
  10773. this.settings.file_upload_limit = fileUploadLimit;
  10774. this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
  10775. };
  10776. // Public: setFileQueueLimit changes the file_queue_limit setting
  10777. SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
  10778. this.settings.file_queue_limit = fileQueueLimit;
  10779. this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
  10780. };
  10781. // Public: setFilePostName changes the file_post_name setting
  10782. SWFUpload.prototype.setFilePostName = function (filePostName) {
  10783. this.settings.file_post_name = filePostName;
  10784. this.callFlash("SetFilePostName", [filePostName]);
  10785. };
  10786. // Public: setUseQueryString changes the use_query_string setting
  10787. SWFUpload.prototype.setUseQueryString = function (useQueryString) {
  10788. this.settings.use_query_string = useQueryString;
  10789. this.callFlash("SetUseQueryString", [useQueryString]);
  10790. };
  10791. // Public: setRequeueOnError changes the requeue_on_error setting
  10792. SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
  10793. this.settings.requeue_on_error = requeueOnError;
  10794. this.callFlash("SetRequeueOnError", [requeueOnError]);
  10795. };
  10796. // Public: setHTTPSuccess changes the http_success setting
  10797. SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
  10798. if (typeof http_status_codes === "string") {
  10799. http_status_codes = http_status_codes.replace(" ", "").split(",");
  10800. }
  10801. this.settings.http_success = http_status_codes;
  10802. this.callFlash("SetHTTPSuccess", [http_status_codes]);
  10803. };
  10804. // Public: setHTTPSuccess changes the http_success setting
  10805. SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
  10806. this.settings.assume_success_timeout = timeout_seconds;
  10807. this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
  10808. };
  10809. // Public: setDebugEnabled changes the debug_enabled setting
  10810. SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
  10811. this.settings.debug_enabled = debugEnabled;
  10812. this.callFlash("SetDebugEnabled", [debugEnabled]);
  10813. };
  10814. // Public: setButtonImageURL loads a button image sprite
  10815. SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
  10816. if (buttonImageURL == undefined) {
  10817. buttonImageURL = "";
  10818. }
  10819. this.settings.button_image_url = buttonImageURL;
  10820. this.callFlash("SetButtonImageURL", [buttonImageURL]);
  10821. };
  10822. // Public: setButtonDimensions resizes the Flash Movie and button
  10823. SWFUpload.prototype.setButtonDimensions = function (width, height) {
  10824. this.settings.button_width = width;
  10825. this.settings.button_height = height;
  10826. var movie = this.getMovieElement();
  10827. if (movie != undefined) {
  10828. movie.style.width = width + "px";
  10829. movie.style.height = height + "px";
  10830. }
  10831. this.callFlash("SetButtonDimensions", [width, height]);
  10832. };
  10833. // Public: setButtonText Changes the text overlaid on the button
  10834. SWFUpload.prototype.setButtonText = function (html) {
  10835. this.settings.button_text = html;
  10836. this.callFlash("SetButtonText", [html]);
  10837. };
  10838. // Public: setButtonTextPadding changes the top and left padding of the text overlay
  10839. SWFUpload.prototype.setButtonTextPadding = function (left, top) {
  10840. this.settings.button_text_top_padding = top;
  10841. this.settings.button_text_left_padding = left;
  10842. this.callFlash("SetButtonTextPadding", [left, top]);
  10843. };
  10844. // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
  10845. SWFUpload.prototype.setButtonTextStyle = function (css) {
  10846. this.settings.button_text_style = css;
  10847. this.callFlash("SetButtonTextStyle", [css]);
  10848. };
  10849. // Public: setButtonDisabled disables/enables the button
  10850. SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
  10851. this.settings.button_disabled = isDisabled;
  10852. this.callFlash("SetButtonDisabled", [isDisabled]);
  10853. };
  10854. // Public: setButtonAction sets the action that occurs when the button is clicked
  10855. SWFUpload.prototype.setButtonAction = function (buttonAction) {
  10856. this.settings.button_action = buttonAction;
  10857. this.callFlash("SetButtonAction", [buttonAction]);
  10858. };
  10859. // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
  10860. SWFUpload.prototype.setButtonCursor = function (cursor) {
  10861. this.settings.button_cursor = cursor;
  10862. this.callFlash("SetButtonCursor", [cursor]);
  10863. };
  10864. /* *******************************
  10865. Flash Event Interfaces
  10866. These functions are used by Flash to trigger the various
  10867. events.
  10868. All these functions a Private.
  10869. Because the ExternalInterface library is buggy the event calls
  10870. are added to a queue and the queue then executed by a setTimeout.
  10871. This ensures that events are executed in a determinate order and that
  10872. the ExternalInterface bugs are avoided.
  10873. ******************************* */
  10874. SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
  10875. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  10876. if (argumentArray == undefined) {
  10877. argumentArray = [];
  10878. } else if (!(argumentArray instanceof Array)) {
  10879. argumentArray = [argumentArray];
  10880. }
  10881. var self = this;
  10882. if (typeof this.settings[handlerName] === "function") {
  10883. // Queue the event
  10884. this.eventQueue.push(function () {
  10885. this.settings[handlerName].apply(this, argumentArray);
  10886. });
  10887. // Execute the next queued event
  10888. setTimeout(function () {
  10889. self.executeNextEvent();
  10890. }, 0);
  10891. } else if (this.settings[handlerName] !== null) {
  10892. throw "Event handler " + handlerName + " is unknown or is not a function";
  10893. }
  10894. };
  10895. // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout
  10896. // we must queue them in order to garentee that they are executed in order.
  10897. SWFUpload.prototype.executeNextEvent = function () {
  10898. // Warning: Don't call this.debug inside here or you'll create an infinite loop
  10899. var f = this.eventQueue ? this.eventQueue.shift() : null;
  10900. if (typeof(f) === "function") {
  10901. f.apply(this);
  10902. }
  10903. };
  10904. // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
  10905. // properties that contain characters that are not valid for JavaScript identifiers. To work around this
  10906. // the Flash Component escapes the parameter names and we must unescape again before passing them along.
  10907. SWFUpload.prototype.unescapeFilePostParams = function (file) {
  10908. var reg = /[$]([0-9a-f]{4})/i;
  10909. var unescapedPost = {};
  10910. var uk;
  10911. if (file != undefined) {
  10912. for (var k in file.post) {
  10913. if (file.post.hasOwnProperty(k)) {
  10914. uk = k;
  10915. var match;
  10916. while ((match = reg.exec(uk)) !== null) {
  10917. uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
  10918. }
  10919. unescapedPost[uk] = file.post[k];
  10920. }
  10921. }
  10922. file.post = unescapedPost;
  10923. }
  10924. return file;
  10925. };
  10926. // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
  10927. SWFUpload.prototype.testExternalInterface = function () {
  10928. try {
  10929. return this.callFlash("TestExternalInterface");
  10930. } catch (ex) {
  10931. return false;
  10932. }
  10933. };
  10934. // Private: This event is called by Flash when it has finished loading. Don't modify this.
  10935. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
  10936. SWFUpload.prototype.flashReady = function () {
  10937. // Check that the movie element is loaded correctly with its ExternalInterface methods defined
  10938. var movieElement = this.getMovieElement();
  10939. if (!movieElement) {
  10940. this.debug("Flash called back ready but the flash movie can't be found.");
  10941. return;
  10942. }
  10943. this.cleanUp(movieElement);
  10944. this.queueEvent("swfupload_loaded_handler");
  10945. };
  10946. // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
  10947. // This function is called by Flash each time the ExternalInterface functions are created.
  10948. SWFUpload.prototype.cleanUp = function (movieElement) {
  10949. // Pro-actively unhook all the Flash functions
  10950. try {
  10951. if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
  10952. this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
  10953. for (var key in movieElement) {
  10954. try {
  10955. if (typeof(movieElement[key]) === "function") {
  10956. movieElement[key] = null;
  10957. }
  10958. } catch (ex) {
  10959. }
  10960. }
  10961. }
  10962. } catch (ex1) {
  10963. }
  10964. // Fix Flashes own cleanup code so if the SWFMovie was removed from the page
  10965. // it doesn't display errors.
  10966. window["__flash__removeCallback"] = function (instance, name) {
  10967. try {
  10968. if (instance) {
  10969. instance[name] = null;
  10970. }
  10971. } catch (flashEx) {
  10972. }
  10973. };
  10974. };
  10975. /* This is a chance to do something before the browse window opens */
  10976. SWFUpload.prototype.fileDialogStart = function () {
  10977. this.queueEvent("file_dialog_start_handler");
  10978. };
  10979. /* Called when a file is successfully added to the queue. */
  10980. SWFUpload.prototype.fileQueued = function (file) {
  10981. file = this.unescapeFilePostParams(file);
  10982. this.queueEvent("file_queued_handler", file);
  10983. };
  10984. /* Handle errors that occur when an attempt to queue a file fails. */
  10985. SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
  10986. file = this.unescapeFilePostParams(file);
  10987. this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
  10988. };
  10989. /* Called after the file dialog has closed and the selected files have been queued.
  10990. You could call startUpload here if you want the queued files to begin uploading immediately. */
  10991. SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
  10992. this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
  10993. };
  10994. SWFUpload.prototype.uploadStart = function (file) {
  10995. file = this.unescapeFilePostParams(file);
  10996. this.queueEvent("return_upload_start_handler", file);
  10997. };
  10998. SWFUpload.prototype.returnUploadStart = function (file) {
  10999. var returnValue;
  11000. if (typeof this.settings.upload_start_handler === "function") {
  11001. file = this.unescapeFilePostParams(file);
  11002. returnValue = this.settings.upload_start_handler.call(this, file);
  11003. } else if (this.settings.upload_start_handler != undefined) {
  11004. throw "upload_start_handler must be a function";
  11005. }
  11006. // Convert undefined to true so if nothing is returned from the upload_start_handler it is
  11007. // interpretted as 'true'.
  11008. if (returnValue === undefined) {
  11009. returnValue = true;
  11010. }
  11011. returnValue = !!returnValue;
  11012. this.callFlash("ReturnUploadStart", [returnValue]);
  11013. };
  11014. SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
  11015. file = this.unescapeFilePostParams(file);
  11016. this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
  11017. };
  11018. SWFUpload.prototype.uploadError = function (file, errorCode, message) {
  11019. file = this.unescapeFilePostParams(file);
  11020. this.queueEvent("upload_error_handler", [file, errorCode, message]);
  11021. };
  11022. SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
  11023. file = this.unescapeFilePostParams(file);
  11024. this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
  11025. };
  11026. SWFUpload.prototype.uploadComplete = function (file) {
  11027. file = this.unescapeFilePostParams(file);
  11028. this.queueEvent("upload_complete_handler", file);
  11029. };
  11030. /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
  11031. internal debug console. You can override this event and have messages written where you want. */
  11032. SWFUpload.prototype.debug = function (message) {
  11033. this.queueEvent("debug_handler", message);
  11034. };
  11035. /* **********************************
  11036. Debug Console
  11037. The debug console is a self contained, in page location
  11038. for debug message to be sent. The Debug Console adds
  11039. itself to the body if necessary.
  11040. The console is automatically scrolled as messages appear.
  11041. If you are using your own debug handler or when you deploy to production and
  11042. have debug disabled you can remove these functions to reduce the file size
  11043. and complexity.
  11044. ********************************** */
  11045. // Private: debugMessage is the default debug_handler. If you want to print debug messages
  11046. // call the debug() function. When overriding the function your own function should
  11047. // check to see if the debug setting is true before outputting debug information.
  11048. SWFUpload.prototype.debugMessage = function (message) {
  11049. if (this.settings.debug) {
  11050. var exceptionMessage, exceptionValues = [];
  11051. // Check for an exception object and print it nicely
  11052. if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
  11053. for (var key in message) {
  11054. if (message.hasOwnProperty(key)) {
  11055. exceptionValues.push(key + ": " + message[key]);
  11056. }
  11057. }
  11058. exceptionMessage = exceptionValues.join("\n") || "";
  11059. exceptionValues = exceptionMessage.split("\n");
  11060. exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
  11061. SWFUpload.Console.writeLine(exceptionMessage);
  11062. } else {
  11063. SWFUpload.Console.writeLine(message);
  11064. }
  11065. }
  11066. };
  11067. SWFUpload.Console = {};
  11068. SWFUpload.Console.writeLine = function (message) {
  11069. var console, documentForm;
  11070. try {
  11071. console = document.getElementById("SWFUpload_Console");
  11072. if (!console) {
  11073. documentForm = document.createElement("form");
  11074. document.getElementsByTagName("body")[0].appendChild(documentForm);
  11075. console = document.createElement("textarea");
  11076. console.id = "SWFUpload_Console";
  11077. console.style.fontFamily = "monospace";
  11078. console.setAttribute("wrap", "off");
  11079. console.wrap = "off";
  11080. console.style.overflow = "auto";
  11081. console.style.width = "700px";
  11082. console.style.height = "350px";
  11083. console.style.margin = "5px";
  11084. documentForm.appendChild(console);
  11085. }
  11086. console.value += message + "\n";
  11087. console.scrollTop = console.scrollHeight - console.clientHeight;
  11088. } catch (ex) {
  11089. alert("Exception: " + ex.name + " Message: " + ex.message);
  11090. }
  11091. };
  11092. /*
  11093. Copyright 2008-2009 University of Cambridge
  11094. Copyright 2008-2009 University of Toronto
  11095. Copyright 2007-2009 University of California, Berkeley
  11096. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  11097. BSD license. You may not use this file except in compliance with one these
  11098. Licenses.
  11099. You may obtain a copy of the ECL 2.0 License and BSD License at
  11100. https://source.fluidproject.org/svn/LICENSE.txt
  11101. */
  11102. /*global jQuery*/
  11103. /*global fluid_1_1*/
  11104. fluid_1_1 = fluid_1_1 || {};
  11105. (function ($, fluid) {
  11106. var animateDisplay = function (elm, animation, defaultAnimation) {
  11107. animation = (animation) ? animation : defaultAnimation;
  11108. elm.animate(animation.params, animation.duration, animation.callback);
  11109. };
  11110. var animateProgress = function (elm, width, speed) {
  11111. // de-queue any left over animations
  11112. elm.queue("fx", []);
  11113. elm.animate({
  11114. width: width,
  11115. queue: false
  11116. },
  11117. speed);
  11118. };
  11119. var showProgress = function (that, animation) {
  11120. if (animation === false) {
  11121. that.displayElement.show();
  11122. } else {
  11123. animateDisplay(that.displayElement, animation, that.options.showAnimation);
  11124. }
  11125. };
  11126. var hideProgress = function (that, delay, animation) {
  11127. delay = (delay === null || isNaN(delay)) ? that.options.delay : delay;
  11128. if (delay) {
  11129. // use a setTimeout to delay the hide for n millies, note use of recursion
  11130. var timeOut = setTimeout(function () {
  11131. hideProgress(that, 0, animation);
  11132. }, delay);
  11133. } else {
  11134. if (animation === false) {
  11135. that.displayElement.hide();
  11136. } else {
  11137. animateDisplay(that.displayElement, animation, that.options.hideAnimation);
  11138. }
  11139. }
  11140. };
  11141. var updateWidth = function (that, newWidth, dontAnimate) {
  11142. dontAnimate = dontAnimate || false;
  11143. var currWidth = that.indicator.width();
  11144. var direction = that.options.animate;
  11145. if ((newWidth > currWidth) && (direction === "both" || direction === "forward") && !dontAnimate) {
  11146. animateProgress(that.indicator, newWidth, that.options.speed);
  11147. } else if ((newWidth < currWidth) && (direction === "both" || direction === "backward") && !dontAnimate) {
  11148. animateProgress(that.indicator, newWidth, that.options.speed);
  11149. } else {
  11150. that.indicator.width(newWidth);
  11151. }
  11152. };
  11153. var percentToPixels = function (that, percent) {
  11154. // progress does not support percents over 100, also all numbers are rounded to integers
  11155. return Math.round((Math.min(percent, 100) * that.progressBar.width()) / 100);
  11156. };
  11157. var refreshRelativeWidth = function (that) {
  11158. var pixels = Math.max(percentToPixels(that, parseFloat(that.storedPercent)), that.options.minWidth);
  11159. updateWidth(that, pixels, true);
  11160. };
  11161. var initARIA = function (ariaElement) {
  11162. ariaElement.attr("role", "progressbar");
  11163. ariaElement.attr("aria-valuemin", "0");
  11164. ariaElement.attr("aria-valuemax", "100");
  11165. ariaElement.attr("aria-live", "assertive");
  11166. ariaElement.attr("aria-busy", "false");
  11167. ariaElement.attr("aria-valuenow", "0");
  11168. ariaElement.attr("aria-valuetext", "");
  11169. };
  11170. var updateARIA = function (that, percent) {
  11171. var busy = percent < 100 && percent > 0;
  11172. that.ariaElement.attr("aria-busy", busy);
  11173. that.ariaElement.attr("aria-valuenow", percent);
  11174. if (busy) {
  11175. var busyString = fluid.stringTemplate(that.options.ariaBusyText, {percentComplete : percent});
  11176. that.ariaElement.attr("aria-valuetext", busyString);
  11177. } else if (percent === 100) {
  11178. that.ariaElement.attr("aria-valuetext", that.options.ariaDoneText);
  11179. }
  11180. };
  11181. var updateText = function (label, value) {
  11182. label.html(value);
  11183. };
  11184. var repositionIndicator = function (that) {
  11185. that.indicator.css("top", that.progressBar.position().top)
  11186. .css("left", 0)
  11187. .height(that.progressBar.height());
  11188. refreshRelativeWidth(that);
  11189. };
  11190. var updateProgress = function (that, percent, labelText, animationForShow) {
  11191. // show progress before updating, jQuery will handle the case if the object is already displayed
  11192. showProgress(that, animationForShow);
  11193. // do not update if the value of percent is falsey
  11194. if (percent !== null) {
  11195. that.storedPercent = percent;
  11196. var pixels = Math.max(percentToPixels(that, parseFloat(percent)), that.options.minWidth);
  11197. updateWidth(that, pixels);
  11198. }
  11199. if (labelText !== null) {
  11200. updateText(that.label, labelText);
  11201. }
  11202. // update ARIA
  11203. if (that.ariaElement) {
  11204. updateARIA(that, percent);
  11205. }
  11206. };
  11207. var setupProgress = function (that) {
  11208. that.displayElement = that.locate("displayElement");
  11209. // hide file progress in case it is showing
  11210. if (that.options.initiallyHidden) {
  11211. that.displayElement.hide();
  11212. }
  11213. that.progressBar = that.locate("progressBar");
  11214. that.label = that.locate("label");
  11215. that.indicator = that.locate("indicator");
  11216. that.ariaElement = that.locate("ariaElement");
  11217. that.indicator.width(that.options.minWidth);
  11218. that.storedPercent = 0;
  11219. // initialize ARIA
  11220. if (that.ariaElement) {
  11221. initARIA(that.ariaElement);
  11222. }
  11223. };
  11224. /**
  11225. * Instantiates a new Progress component.
  11226. *
  11227. * @param {jQuery|Selector|Element} container the DOM element in which the Uploader lives
  11228. * @param {Object} options configuration options for the component.
  11229. */
  11230. fluid.progress = function (container, options) {
  11231. var that = fluid.initView("fluid.progress", container, options);
  11232. setupProgress(that);
  11233. /**
  11234. * Shows the progress bar if is currently hidden.
  11235. *
  11236. * @param {Object} animation a custom animation used when showing the progress bar
  11237. */
  11238. that.show = function (animation) {
  11239. showProgress(that, animation);
  11240. };
  11241. /**
  11242. * Hides the progress bar if it is visible.
  11243. *
  11244. * @param {Number} delay the amount of time to wait before hiding
  11245. * @param {Object} animation a custom animation used when hiding the progress bar
  11246. */
  11247. that.hide = function (delay, animation) {
  11248. hideProgress(that, delay, animation);
  11249. };
  11250. /**
  11251. * Updates the state of the progress bar.
  11252. * This will automatically show the progress bar if it is currently hidden.
  11253. * Percentage is specified as a decimal value, but will be automatically converted if needed.
  11254. *
  11255. *
  11256. * @param {Number|String} percentage the current percentage, specified as a "float-ish" value
  11257. * @param {String} labelValue the value to set for the label; this can be an HTML string
  11258. * @param {Object} animationForShow the animation to use when showing the progress bar if it is hidden
  11259. */
  11260. that.update = function (percentage, labelValue, animationForShow) {
  11261. updateProgress(that, percentage, labelValue, animationForShow);
  11262. };
  11263. that.refreshView = function () {
  11264. repositionIndicator(that);
  11265. };
  11266. return that;
  11267. };
  11268. fluid.defaults("fluid.progress", {
  11269. selectors: {
  11270. displayElement: ".flc-progress", // required, the element that gets displayed when progress is displayed, could be the indicator or bar or some larger outer wrapper as in an overlay effect
  11271. progressBar: ".flc-progress-bar", //required
  11272. indicator: ".flc-progress-indicator", //required
  11273. label: ".flc-progress-label", //optional
  11274. ariaElement: ".flc-progress-bar" // usually required, except in cases where there are more than one progressor for the same data such as a total and a sub-total
  11275. },
  11276. // progress display and hide animations, use the jQuery animation primatives, set to false to use no animation
  11277. // animations must be symetrical (if you hide with width, you'd better show with width) or you get odd effects
  11278. // see jQuery docs about animations to customize
  11279. showAnimation: {
  11280. params: {
  11281. opacity: "show"
  11282. },
  11283. duration: "slow",
  11284. callback: null
  11285. }, // equivalent of $().fadeIn("slow")
  11286. hideAnimation: {
  11287. params: {
  11288. opacity: "hide"
  11289. },
  11290. duration: "slow",
  11291. callback: null
  11292. }, // equivalent of $().fadeOut("slow")
  11293. minWidth: 5, // 0 length indicators can look broken if there is a long pause between updates
  11294. delay: 0, // the amount to delay the fade out of the progress
  11295. speed: 200, // default speed for animations, pretty fast
  11296. animate: "forward", // suppport "forward", "backward", and "both", any other value is no animation either way
  11297. initiallyHidden: true, // supports progress indicators which may always be present
  11298. updatePosition: false,
  11299. ariaBusyText: "Progress is %percentComplete percent complete",
  11300. ariaDoneText: "Progress is complete."
  11301. });
  11302. })(jQuery, fluid_1_1);
  11303. /*
  11304. Copyright 2008-2009 University of Cambridge
  11305. Copyright 2008-2009 University of Toronto
  11306. Copyright 2007-2009 University of California, Berkeley
  11307. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  11308. BSD license. You may not use this file except in compliance with one these
  11309. Licenses.
  11310. You may obtain a copy of the ECL 2.0 License and BSD License at
  11311. https://source.fluidproject.org/svn/LICENSE.txt
  11312. */
  11313. /*global jQuery*/
  11314. /*global fluid_1_1*/
  11315. fluid_1_1 = fluid_1_1 || {};
  11316. /***********************
  11317. * Demo Upload Manager *
  11318. ***********************/
  11319. (function ($, fluid) {
  11320. var updateProgress = function (file, events, demoState, isUploading) {
  11321. if (!isUploading) {
  11322. return;
  11323. }
  11324. var chunk = Math.min(demoState.chunkSize, file.size);
  11325. demoState.bytesUploaded = Math.min(demoState.bytesUploaded + chunk, file.size);
  11326. events.onFileProgress.fire(file, demoState.bytesUploaded, file.size);
  11327. };
  11328. var fireAfterFileComplete = function (that, file) {
  11329. // this is a horrible hack that needs to be addressed.
  11330. if (that.swfUploadSettings) {
  11331. that.swfUploadSettings.upload_complete_handler(file);
  11332. } else {
  11333. that.events.afterFileComplete.fire(file);
  11334. }
  11335. };
  11336. var finishAndContinueOrCleanup = function (that, file) {
  11337. that.queueManager.finishFile(file);
  11338. if (that.queueManager.shouldUploadNextFile()) {
  11339. startUploading(that);
  11340. } else {
  11341. that.queueManager.complete();
  11342. }
  11343. };
  11344. var finishUploading = function (that) {
  11345. if (!that.queue.isUploading) {
  11346. return;
  11347. }
  11348. var file = that.demoState.currentFile;
  11349. file.filestatus = fluid.uploader.fileStatusConstants.COMPLETE;
  11350. that.events.onFileSuccess.fire(file);
  11351. that.demoState.fileIdx++;
  11352. finishAndContinueOrCleanup(that, file);
  11353. };
  11354. var simulateUpload = function (that) {
  11355. if (!that.queue.isUploading) {
  11356. return;
  11357. }
  11358. var file = that.demoState.currentFile;
  11359. if (that.demoState.bytesUploaded < file.size) {
  11360. that.invokeAfterRandomDelay(function () {
  11361. updateProgress(file, that.events, that.demoState, that.queue.isUploading);
  11362. simulateUpload(that);
  11363. });
  11364. } else {
  11365. finishUploading(that);
  11366. }
  11367. };
  11368. var startUploading = function (that) {
  11369. // Reset our upload stats for each new file.
  11370. that.demoState.currentFile = that.queue.files[that.demoState.fileIdx];
  11371. that.demoState.chunksForCurrentFile = Math.ceil(that.demoState.currentFile / that.demoState.chunkSize);
  11372. that.demoState.bytesUploaded = 0;
  11373. that.queue.isUploading = true;
  11374. that.events.onFileStart.fire(that.demoState.currentFile);
  11375. that.demoState.currentFile.filestatus = fluid.uploader.fileStatusConstants.IN_PROGRESS;
  11376. simulateUpload(that);
  11377. };
  11378. var stopDemo = function (that) {
  11379. var file = that.demoState.currentFile;
  11380. file.filestatus = fluid.uploader.fileStatusConstants.CANCELLED;
  11381. that.queue.shouldStop = true;
  11382. // In SWFUpload's world, pausing is a combinination of an UPLOAD_STOPPED error and a complete.
  11383. that.events.onFileError.fire(file,
  11384. fluid.uploader.errorConstants.UPLOAD_STOPPED,
  11385. "The demo upload was paused by the user.");
  11386. finishAndContinueOrCleanup(that, file);
  11387. that.events.onUploadStop.fire();
  11388. };
  11389. var setupDemoUploadManager = function (that) {
  11390. if (that.options.simulateDelay === undefined || that.options.simulateDelay === null) {
  11391. that.options.simulateDelay = true;
  11392. }
  11393. // Initialize state for our upload simulation.
  11394. that.demoState = {
  11395. fileIdx: 0,
  11396. chunkSize: 200000
  11397. };
  11398. return that;
  11399. };
  11400. /**
  11401. * The Demo Upload Manager wraps a standard upload manager and simulates the upload process.
  11402. *
  11403. * @param {UploadManager} uploadManager the upload manager to wrap
  11404. */
  11405. fluid.demoUploadManager = function (uploadManager) {
  11406. var that = uploadManager;
  11407. that.start = function () {
  11408. that.queueManager.start();
  11409. startUploading(that);
  11410. };
  11411. /**
  11412. * Cancels a simulated upload.
  11413. * This method overrides the default behaviour in SWFUploadManager.
  11414. */
  11415. that.stop = function () {
  11416. stopDemo(that);
  11417. };
  11418. /**
  11419. * Invokes a function after a random delay by using setTimeout.
  11420. * If the simulateDelay option is false, the function is invoked immediately.
  11421. *
  11422. * @param {Object} fn the function to invoke
  11423. */
  11424. that.invokeAfterRandomDelay = function (fn) {
  11425. var delay;
  11426. if (that.options.simulateDelay) {
  11427. delay = Math.floor(Math.random() * 1000 + 100);
  11428. setTimeout(fn, delay);
  11429. } else {
  11430. fn();
  11431. }
  11432. };
  11433. setupDemoUploadManager(that);
  11434. return that;
  11435. };
  11436. })(jQuery, fluid_1_1);
  11437. /*
  11438. Copyright 2008-2009 University of Cambridge
  11439. Copyright 2008-2009 University of Toronto
  11440. Copyright 2007-2009 University of California, Berkeley
  11441. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  11442. BSD license. You may not use this file except in compliance with one these
  11443. Licenses.
  11444. You may obtain a copy of the ECL 2.0 License and BSD License at
  11445. https://source.fluidproject.org/svn/LICENSE.txt
  11446. */
  11447. /*global SWFUpload*/
  11448. /*global jQuery*/
  11449. /*global fluid_1_1*/
  11450. fluid_1_1 = fluid_1_1 || {};
  11451. (function ($, fluid) {
  11452. var filterFiles = function (files, filterFn) {
  11453. var filteredFiles = [];
  11454. for (var i = 0; i < files.length; i++) {
  11455. var file = files[i];
  11456. if (filterFn(file) === true) {
  11457. filteredFiles.push(file);
  11458. }
  11459. }
  11460. return filteredFiles;
  11461. };
  11462. var getUploadedFiles = function (that) {
  11463. return filterFiles(that.files, function (file) {
  11464. return (file.filestatus === fluid.uploader.fileStatusConstants.COMPLETE);
  11465. });
  11466. };
  11467. var getReadyFiles = function (that) {
  11468. return filterFiles(that.files, function (file) {
  11469. return (file.filestatus === fluid.uploader.fileStatusConstants.QUEUED || file.filestatus === fluid.uploader.fileStatusConstants.CANCELLED);
  11470. });
  11471. };
  11472. var getErroredFiles = function (that) {
  11473. return filterFiles(that.files, function (file) {
  11474. return (file.filestatus === fluid.uploader.fileStatusConstants.ERROR);
  11475. });
  11476. };
  11477. var removeFile = function (that, file) {
  11478. // Remove the file from the collection and tell the world about it.
  11479. var idx = $.inArray(file, that.files);
  11480. that.files.splice(idx, 1);
  11481. };
  11482. var clearCurrentBatch = function (that) {
  11483. that.currentBatch = {
  11484. fileIdx: -1,
  11485. files: [],
  11486. totalBytes: 0,
  11487. numFilesCompleted: 0,
  11488. numFilesErrored: 0,
  11489. bytesUploadedForFile: 0,
  11490. previousBytesUploadedForFile: 0,
  11491. totalBytesUploaded: 0
  11492. };
  11493. };
  11494. var updateCurrentBatch = function (that) {
  11495. var readyFiles = that.getReadyFiles();
  11496. that.currentBatch.files = readyFiles;
  11497. that.currentBatch.totalBytes = fluid.fileQueue.sizeOfFiles(readyFiles);
  11498. };
  11499. var setupCurrentBatch = function (that) {
  11500. clearCurrentBatch(that);
  11501. updateCurrentBatch(that);
  11502. };
  11503. fluid.fileQueue = function () {
  11504. var that = {};
  11505. that.files = [];
  11506. that.isUploading = false;
  11507. that.addFile = function (file) {
  11508. that.files.push(file);
  11509. };
  11510. that.removeFile = function (file) {
  11511. removeFile(that, file);
  11512. };
  11513. that.totalBytes = function () {
  11514. return fluid.fileQueue.sizeOfFiles(that.files);
  11515. };
  11516. that.getReadyFiles = function () {
  11517. return getReadyFiles(that);
  11518. };
  11519. that.getErroredFiles = function () {
  11520. return getErroredFiles(that);
  11521. };
  11522. that.sizeOfReadyFiles = function () {
  11523. return fluid.fileQueue.sizeOfFiles(that.getReadyFiles());
  11524. };
  11525. that.getUploadedFiles = function () {
  11526. return getUploadedFiles(that);
  11527. };
  11528. that.sizeOfUploadedFiles = function () {
  11529. return fluid.fileQueue.sizeOfFiles(that.getUploadedFiles());
  11530. };
  11531. that.setupCurrentBatch = function () {
  11532. setupCurrentBatch(that);
  11533. };
  11534. that.clearCurrentBatch = function () {
  11535. clearCurrentBatch(that);
  11536. };
  11537. that.updateCurrentBatch = function () {
  11538. updateCurrentBatch(that);
  11539. };
  11540. return that;
  11541. };
  11542. fluid.fileQueue.sizeOfFiles = function (files) {
  11543. var totalBytes = 0;
  11544. for (var i = 0; i < files.length; i++) {
  11545. var file = files[i];
  11546. totalBytes += file.size;
  11547. }
  11548. return totalBytes;
  11549. };
  11550. fluid.fileQueue.manager = function (queue, events) {
  11551. var that = {};
  11552. that.queue = queue;
  11553. that.events = events;
  11554. that.start = function () {
  11555. that.queue.setupCurrentBatch();
  11556. that.queue.isUploading = true;
  11557. that.queue.shouldStop = false;
  11558. that.events.onUploadStart.fire(that.queue.currentBatch.files);
  11559. };
  11560. that.startFile = function () {
  11561. that.queue.currentBatch.fileIdx++;
  11562. that.queue.currentBatch.bytesUploadedForFile = 0;
  11563. that.queue.currentBatch.previousBytesUploadedForFile = 0;
  11564. };
  11565. that.finishFile = function (file) {
  11566. var batch = that.queue.currentBatch;
  11567. batch.numFilesCompleted++;
  11568. that.events.afterFileComplete.fire(file);
  11569. };
  11570. that.shouldUploadNextFile = function () {
  11571. return !that.queue.shouldStop && that.queue.isUploading && that.queue.currentBatch.numFilesCompleted < that.queue.currentBatch.files.length;
  11572. };
  11573. that.complete = function () {
  11574. that.events.afterUploadComplete.fire(that.queue.currentBatch.files);
  11575. that.queue.clearCurrentBatch();
  11576. };
  11577. return that;
  11578. };
  11579. })(jQuery, fluid_1_1);
  11580. /*
  11581. Copyright 2008-2009 University of Cambridge
  11582. Copyright 2008-2009 University of Toronto
  11583. Copyright 2007-2009 University of California, Berkeley
  11584. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  11585. BSD license. You may not use this file except in compliance with one these
  11586. Licenses.
  11587. You may obtain a copy of the ECL 2.0 License and BSD License at
  11588. https://source.fluidproject.org/svn/LICENSE.txt
  11589. */
  11590. /*global jQuery*/
  11591. /*global fluid_1_1*/
  11592. fluid_1_1 = fluid_1_1 || {};
  11593. (function ($, fluid) {
  11594. var refreshView = function (that) {
  11595. var maxHeight = that.options.maxHeight;
  11596. var isOverMaxHeight = (that.scrollingElm.children().eq(0).height() > maxHeight);
  11597. var setHeight = (isOverMaxHeight) ? maxHeight : "";
  11598. that.scrollingElm.height(setHeight);
  11599. };
  11600. var scrollBottom = function (that) {
  11601. that.scrollingElm[0].scrollTop = that.scrollingElm[0].scrollHeight;
  11602. };
  11603. var scrollTo = function (that, element) {
  11604. if (!element || element.length < 1) {
  11605. return;
  11606. }
  11607. var padTop = 0;
  11608. var padBottom = 0;
  11609. var elmPosTop = element[0].offsetTop;
  11610. var elmHeight = element.height();
  11611. var containerScrollTop = that.scrollingElm[0].scrollTop;
  11612. var containerHeight = that.scrollingElm.height();
  11613. if (that.options.padScroll) {
  11614. // if the combined height of the elements is greater than the
  11615. // viewport then then scrollTo element would not be in view
  11616. var prevElmHeight = element.prev().height();
  11617. padTop = (prevElmHeight + elmHeight <= containerHeight) ? prevElmHeight : 0;
  11618. var nextElmHeight = element.next().height();
  11619. padBottom = (nextElmHeight + elmHeight <= containerHeight) ? nextElmHeight : 0;
  11620. }
  11621. // if the top of the row is ABOVE the view port move the row into position
  11622. if ((elmPosTop - padTop) < containerScrollTop) {
  11623. that.scrollingElm[0].scrollTop = elmPosTop - padTop;
  11624. }
  11625. // if the bottom of the row is BELOW the viewport then scroll it into position
  11626. if (((elmPosTop + elmHeight) + padBottom) > (containerScrollTop + containerHeight)) {
  11627. elmHeight = (elmHeight < containerHeight) ? elmHeight : containerHeight;
  11628. that.scrollingElm[0].scrollTop = (elmPosTop - containerHeight + elmHeight + padBottom);
  11629. }
  11630. };
  11631. var setupScroller = function (that) {
  11632. that.scrollingElm = that.container.parents(that.options.selectors.wrapper);
  11633. // We should render our own sensible default if the scrolling element is missing.
  11634. if (!that.scrollingElm.length) {
  11635. fluid.fail({
  11636. name: "Missing Scroller",
  11637. message: "The scroller wrapper element was not found."
  11638. });
  11639. }
  11640. // set the height of the scroller unless this is IE6
  11641. if (!$.browser.msie || $.browser.version > 6) {
  11642. that.scrollingElm.css("max-height", that.options.maxHeight);
  11643. }
  11644. };
  11645. /**
  11646. * Creates a new Scroller component.
  11647. *
  11648. * @param {Object} container the element containing the collection of things to make scrollable
  11649. * @param {Object} options configuration options for the component
  11650. */
  11651. fluid.scroller = function (container, options) {
  11652. var that = fluid.initView("fluid.scroller", container, options);
  11653. setupScroller(that);
  11654. /**
  11655. * Scrolls the specified element into view
  11656. *
  11657. * @param {jQuery} element the element to scroll into view
  11658. */
  11659. that.scrollTo = function (element) {
  11660. scrollTo(that, element);
  11661. };
  11662. /**
  11663. * Scrolls to the bottom of the view.
  11664. */
  11665. that.scrollBottom = function () {
  11666. scrollBottom(that);
  11667. };
  11668. /**
  11669. * Refreshes the scroller's appearance based on any changes to the document.
  11670. */
  11671. that.refreshView = function () {
  11672. if ($.browser.msie && $.browser.version < 7) {
  11673. refreshView(that);
  11674. }
  11675. };
  11676. that.refreshView();
  11677. return that;
  11678. };
  11679. fluid.defaults("fluid.scroller", {
  11680. selectors: {
  11681. wrapper: ".flc-scroller"
  11682. },
  11683. maxHeight: 180,
  11684. padScroll: true
  11685. });
  11686. })(jQuery, fluid_1_1);
  11687. /*
  11688. Copyright 2008-2009 University of Cambridge
  11689. Copyright 2008-2009 University of Toronto
  11690. Copyright 2007-2009 University of California, Berkeley
  11691. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  11692. BSD license. You may not use this file except in compliance with one these
  11693. Licenses.
  11694. You may obtain a copy of the ECL 2.0 License and BSD License at
  11695. https://source.fluidproject.org/svn/LICENSE.txt
  11696. */
  11697. /*global SWFUpload*/
  11698. /*global swfobject*/
  11699. /*global jQuery*/
  11700. /*global fluid_1_1*/
  11701. fluid_1_1 = fluid_1_1 || {};
  11702. (function ($, fluid) {
  11703. /*****************************
  11704. * SWFUpload Setup Decorator *
  11705. *****************************/
  11706. var unbindSelectFiles = function () {
  11707. // There's a bug in SWFUpload 2.2.0b3 that causes the entire browser to crash
  11708. // if selectFile() or selectFiles() is invoked. Remove them so no one will accidently crash their browser.
  11709. var emptyFunction = function () {};
  11710. SWFUpload.prototype.selectFile = emptyFunction;
  11711. SWFUpload.prototype.selectFiles = emptyFunction;
  11712. };
  11713. var prepareUpstreamOptions = function (that, uploader) {
  11714. that.returnedOptions = {
  11715. uploadManager: {
  11716. type: uploader.options.uploadManager.type || uploader.options.uploadManager
  11717. }
  11718. };
  11719. };
  11720. var createFlash9MovieContainer = function (that) {
  11721. var container = $("<div><span></span></div>");
  11722. container.addClass(that.options.styles.flash9Container);
  11723. $("body").append(container);
  11724. return container;
  11725. };
  11726. var setupForFlash9 = function (that) {
  11727. var flashContainer = createFlash9MovieContainer(that);
  11728. that.returnedOptions.uploadManager.options = {
  11729. flashURL: that.options.flash9URL || undefined,
  11730. flashButtonPeerId: fluid.allocateSimpleId(flashContainer.children().eq(0))
  11731. };
  11732. };
  11733. var createFlash10MovieContainer = function (that, uploaderContainer) {
  11734. // Wrap the whole uploader first.
  11735. uploaderContainer.wrap("<div class='" + that.options.styles.uploaderWrapperFlash10 + "'></div>");
  11736. // Then create a container and placeholder for the Flash movie as a sibling to the uploader.
  11737. var flashContainer = $("<div><span></span></div>");
  11738. flashContainer.addClass(that.options.styles.browseButtonOverlay);
  11739. uploaderContainer.after(flashContainer);
  11740. unbindSelectFiles();
  11741. return flashContainer;
  11742. };
  11743. var setupForFlash10 = function (that, uploader) {
  11744. var o = that.options,
  11745. flashContainer = createFlash10MovieContainer(that, uploader.container);
  11746. browseButton = uploader.locate("browseButton"),
  11747. h = o.flashButtonHeight || browseButton.outerHeight(),
  11748. w = o.flashButtonWidth || browseButton.outerWidth();
  11749. fluid.tabindex(browseButton, -1);
  11750. that.isTransparent = o.flashButtonAlwaysVisible ? false : (!$.browser.msie || o.transparentEvenInIE);
  11751. that.returnedOptions.uploadManager.options = {
  11752. flashURL: o.flash10URL || undefined,
  11753. flashButtonImageURL: that.isTransparent ? undefined : o.flashButtonImageURL,
  11754. flashButtonPeerId: fluid.allocateSimpleId(flashContainer.children().eq(0)),
  11755. flashButtonHeight: h,
  11756. flashButtonWidth: w,
  11757. flashButtonWindowMode: that.isTransparent ? SWFUpload.WINDOW_MODE.TRANSPARENT : SWFUpload.WINDOW_MODE.OPAQUE,
  11758. flashButtonCursorEffect: SWFUpload.CURSOR.HAND,
  11759. listeners: {
  11760. onUploadStart: function () {
  11761. uploader.uploadManager.swfUploader.setButtonDisabled(true);
  11762. },
  11763. afterUploadComplete: function () {
  11764. uploader.uploadManager.swfUploader.setButtonDisabled(false);
  11765. }
  11766. }
  11767. };
  11768. };
  11769. /**
  11770. * SWFUploadSetupDecorator is a decorator designed to setup the DOM correctly for SWFUpload and configure
  11771. * the Uploader component according to the version of Flash and browser currently running.
  11772. *
  11773. * @param {Uploader} uploader the Uploader component to decorate
  11774. * @param {options} options configuration options for the decorator
  11775. */
  11776. fluid.swfUploadSetupDecorator = function (uploader, options) {
  11777. var that = {};
  11778. fluid.mergeComponentOptions(that, "fluid.swfUploadSetupDecorator", options);
  11779. that.flashVersion = swfobject.getFlashPlayerVersion().major;
  11780. prepareUpstreamOptions(that, uploader);
  11781. if (that.flashVersion === 9) {
  11782. setupForFlash9(that, uploader);
  11783. } else {
  11784. setupForFlash10(that, uploader);
  11785. }
  11786. return that;
  11787. };
  11788. fluid.defaults("fluid.swfUploadSetupDecorator", {
  11789. // The flash9URL and flash10URLs are now deprecated in favour of the flashURL option in upload manager.
  11790. flashButtonAlwaysVisible: false,
  11791. transparentEvenInIE: true,
  11792. // Used only when the Flash movie is visible.
  11793. flashButtonImageURL: "../images/browse.png",
  11794. styles: {
  11795. browseButtonOverlay: "fl-uploader-browse-overlay",
  11796. flash9Container: "fl-uploader-flash9-container",
  11797. uploaderWrapperFlash10: "fl-uploader-flash10-wrapper"
  11798. }
  11799. });
  11800. /***********************
  11801. * SWF Upload Manager *
  11802. ***********************/
  11803. // Maps SWFUpload's setting names to our component's setting names.
  11804. var swfUploadOptionsMap = {
  11805. uploadURL: "upload_url",
  11806. flashURL: "flash_url",
  11807. postParams: "post_params",
  11808. fileSizeLimit: "file_size_limit",
  11809. fileTypes: "file_types",
  11810. fileTypesDescription: "file_types_description",
  11811. fileUploadLimit: "file_upload_limit",
  11812. fileQueueLimit: "file_queue_limit",
  11813. flashButtonPeerId: "button_placeholder_id",
  11814. flashButtonImageURL: "button_image_url",
  11815. flashButtonHeight: "button_height",
  11816. flashButtonWidth: "button_width",
  11817. flashButtonWindowMode: "button_window_mode",
  11818. flashButtonCursorEffect: "button_cursor",
  11819. debug: "debug"
  11820. };
  11821. // Maps SWFUpload's callback names to our component's callback names.
  11822. var swfUploadEventMap = {
  11823. afterReady: "swfupload_loaded_handler",
  11824. onFileDialog: "file_dialog_start_handler",
  11825. afterFileQueued: "file_queued_handler",
  11826. onQueueError: "file_queue_error_handler",
  11827. afterFileDialog: "file_dialog_complete_handler",
  11828. onFileStart: "upload_start_handler",
  11829. onFileProgress: "upload_progress_handler",
  11830. onFileError: "upload_error_handler",
  11831. onFileSuccess: "upload_success_handler"
  11832. };
  11833. var mapNames = function (nameMap, source, target) {
  11834. var result = target || {};
  11835. for (var key in source) {
  11836. var mappedKey = nameMap[key];
  11837. if (mappedKey) {
  11838. result[mappedKey] = source[key];
  11839. }
  11840. }
  11841. return result;
  11842. };
  11843. // For each event type, hand the fire function to SWFUpload so it can fire the event at the right time for us.
  11844. var mapEvents = function (that, nameMap, target) {
  11845. var result = target || {};
  11846. for (var eventType in that.events) {
  11847. var fireFn = that.events[eventType].fire;
  11848. var mappedName = nameMap[eventType];
  11849. if (mappedName) {
  11850. result[mappedName] = fireFn;
  11851. }
  11852. }
  11853. result.upload_complete_handler = function (file) {
  11854. that.queueManager.finishFile(file);
  11855. if (that.queueManager.shouldUploadNextFile()) {
  11856. that.swfUploader.startUpload();
  11857. } else {
  11858. if (that.queueManager.queue.shouldStop) {
  11859. that.swfUploader.stopUpload();
  11860. }
  11861. that.queueManager.complete();
  11862. }
  11863. };
  11864. return result;
  11865. };
  11866. // Invokes the OS browse files dialog, allowing either single or multiple select based on the options.
  11867. var browse = function (that) {
  11868. if (that.queue.isUploading) {
  11869. return;
  11870. }
  11871. if (that.options.fileQueueLimit === 1) {
  11872. that.swfUploader.selectFile();
  11873. } else {
  11874. that.swfUploader.selectFiles();
  11875. }
  11876. };
  11877. /* FLUID-822: while stopping the upload cycle while a file is in mid-upload should be possible
  11878. * in practice, it sets up a state where when the upload cycle is restarted SWFUpload will get stuck
  11879. * therefor we only stop the upload after a file has completed but before the next file begins.
  11880. */
  11881. var stopUpload = function (that) {
  11882. that.queue.shouldStop = true;
  11883. that.events.onUploadStop.fire();
  11884. };
  11885. var bindEvents = function (that) {
  11886. var fileStatusUpdater = function (file) {
  11887. fluid.find(that.queue.files, function (potentialMatch) {
  11888. if (potentialMatch.id === file.id) {
  11889. potentialMatch.filestatus = file.filestatus;
  11890. return true;
  11891. }
  11892. });
  11893. };
  11894. // Add a listener that will keep our file queue model in sync with SWFUpload.
  11895. that.events.afterFileQueued.addListener(function (file) {
  11896. that.queue.addFile(file);
  11897. });
  11898. that.events.onFileStart.addListener(function (file) {
  11899. that.queueManager.startFile();
  11900. fileStatusUpdater(file);
  11901. });
  11902. that.events.onFileProgress.addListener(function (file, currentBytes, totalBytes) {
  11903. var currentBatch = that.queue.currentBatch;
  11904. var byteIncrement = currentBytes - currentBatch.previousBytesUploadedForFile;
  11905. currentBatch.totalBytesUploaded += byteIncrement;
  11906. currentBatch.bytesUploadedForFile += byteIncrement;
  11907. currentBatch.previousBytesUploadedForFile = currentBytes;
  11908. fileStatusUpdater(file);
  11909. });
  11910. that.events.onFileError.addListener(function (file, error) {
  11911. if (error === fluid.uploader.errorConstants.UPLOAD_STOPPED) {
  11912. that.queue.isUploading = false;
  11913. } else if (that.queue.isUploading) {
  11914. that.queue.currentBatch.totalBytesUploaded += file.size;
  11915. that.queue.currentBatch.numFilesErrored++;
  11916. }
  11917. fileStatusUpdater(file);
  11918. });
  11919. that.events.onFileSuccess.addListener(function (file) {
  11920. if (that.queue.currentBatch.bytesUploadedForFile === 0) {
  11921. that.queue.currentBatch.totalBytesUploaded += file.size;
  11922. }
  11923. fileStatusUpdater(file);
  11924. });
  11925. that.events.afterUploadComplete.addListener(function () {
  11926. that.queue.isUploading = false;
  11927. });
  11928. };
  11929. var removeFile = function (that, file) {
  11930. that.queue.removeFile(file);
  11931. that.swfUploader.cancelUpload(file.id);
  11932. that.events.afterFileRemoved.fire(file);
  11933. };
  11934. // Instantiates a new SWFUploader instance and attaches it the upload manager.
  11935. var setupSwfUploadManager = function (that, events) {
  11936. that.events = events;
  11937. that.queue = fluid.fileQueue();
  11938. that.queueManager = fluid.fileQueue.manager(that.queue, that.events);
  11939. // Map the event and settings names to SWFUpload's expectations.
  11940. that.swfUploadSettings = mapNames(swfUploadOptionsMap, that.options);
  11941. mapEvents(that, swfUploadEventMap, that.swfUploadSettings);
  11942. // Setup the instance.
  11943. that.swfUploader = new SWFUpload(that.swfUploadSettings);
  11944. bindEvents(that);
  11945. };
  11946. /**
  11947. * Server Upload Manager is responsible for coordinating with the Flash-based SWFUploader library,
  11948. * providing a simple way to start, pause, and cancel the uploading process. It requires a working
  11949. * server to respond to the upload POST requests.
  11950. *
  11951. * @param {Object} eventBindings an object containing upload lifecycle callbacks
  11952. * @param {Object} options configuration options for the upload manager
  11953. */
  11954. fluid.swfUploadManager = function (events, options) {
  11955. var that = {};
  11956. // This needs to be refactored!
  11957. fluid.mergeComponentOptions(that, "fluid.swfUploadManager", options);
  11958. fluid.mergeListeners(events, that.options.listeners);
  11959. /**
  11960. * Opens the native OS browse file dialog.
  11961. */
  11962. that.browseForFiles = function () {
  11963. browse(that);
  11964. };
  11965. /**
  11966. * Removes the specified file from the upload queue.
  11967. *
  11968. * @param {File} file the file to remove
  11969. */
  11970. that.removeFile = function (file) {
  11971. removeFile(that, file);
  11972. };
  11973. /**
  11974. * Starts uploading all queued files to the server.
  11975. */
  11976. that.start = function () {
  11977. that.queueManager.start();
  11978. that.swfUploader.startUpload();
  11979. };
  11980. /**
  11981. * Cancels an in-progress upload.
  11982. */
  11983. that.stop = function () {
  11984. stopUpload(that);
  11985. };
  11986. setupSwfUploadManager(that, events);
  11987. return that;
  11988. };
  11989. fluid.defaults("fluid.swfUploadManager", {
  11990. uploadURL: "",
  11991. flashURL: "../../../lib/swfupload/flash/swfupload.swf",
  11992. flashButtonPeerId: "",
  11993. postParams: {},
  11994. fileSizeLimit: "20480",
  11995. fileTypes: "*",
  11996. fileTypesDescription: null,
  11997. fileUploadLimit: 0,
  11998. fileQueueLimit: 0,
  11999. debug: false
  12000. });
  12001. })(jQuery, fluid_1_1);
  12002. /*
  12003. Copyright 2007-2009 University of Toronto
  12004. Copyright 2007-2009 University of California, Berkeley
  12005. Copyright 2007-2009 University of Cambridge
  12006. Licensed under the Educational Community License (ECL), Version 2.0 or the New
  12007. BSD license. You may not use this file except in compliance with one these
  12008. Licenses.
  12009. You may obtain a copy of the ECL 2.0 License and BSD License at
  12010. https://source.fluidproject.org/svn/LICENSE.txt
  12011. */
  12012. /*global SWFUpload*/
  12013. /*global swfobject*/
  12014. /*global jQuery*/
  12015. /*global fluid_1_1*/
  12016. fluid_1_1 = fluid_1_1 || {};
  12017. /*******************
  12018. * File Queue View *
  12019. *******************/
  12020. (function ($, fluid) {
  12021. // Real data binding would be nice to replace these two pairs.
  12022. var rowForFile = function (that, file) {
  12023. return that.locate("fileQueue").find("#" + file.id);
  12024. };
  12025. var errorRowForFile = function (that, file) {
  12026. return $("#" + file.id + "_error", that.container);
  12027. };
  12028. var fileForRow = function (that, row) {
  12029. var files = that.uploadManager.queue.files;
  12030. for (var i = 0; i < files.length; i++) {
  12031. var file = files[i];
  12032. if (file.id.toString() === row.attr("id")) {
  12033. return file;
  12034. }
  12035. }
  12036. return null;
  12037. };
  12038. var progressorForFile = function (that, file) {
  12039. var progressId = file.id + "_progress";
  12040. return that.fileProgressors[progressId];
  12041. };
  12042. var startFileProgress = function (that, file) {
  12043. var fileRowElm = rowForFile(that, file);
  12044. that.scroller.scrollTo(fileRowElm);
  12045. // update the progressor and make sure that it's in position
  12046. var fileProgressor = progressorForFile(that, file);
  12047. fileProgressor.refreshView();
  12048. fileProgressor.show();
  12049. };
  12050. var updateFileProgress = function (that, file, fileBytesComplete, fileTotalBytes) {
  12051. var filePercent = fluid.uploader.derivePercent(fileBytesComplete, fileTotalBytes);
  12052. var filePercentStr = filePercent + "%";
  12053. progressorForFile(that, file).update(filePercent, filePercentStr);
  12054. };
  12055. var hideFileProgress = function (that, file) {
  12056. var fileRowElm = rowForFile(that, file);
  12057. progressorForFile(that, file).hide();
  12058. if (file.filestatus === fluid.uploader.fileStatusConstants.COMPLETE) {
  12059. that.locate("fileIconBtn", fileRowElm).removeClass(that.options.styles.dim);
  12060. }
  12061. };
  12062. var removeFileProgress = function (that, file) {
  12063. var fileProgressor = progressorForFile(that, file);
  12064. if (!fileProgressor) {
  12065. return;
  12066. }
  12067. var rowProgressor = fileProgressor.displayElement;
  12068. rowProgressor.remove();
  12069. };
  12070. var animateRowRemoval = function (that, row) {
  12071. row.fadeOut("fast", function () {
  12072. row.remove();
  12073. that.refreshView();
  12074. });
  12075. };
  12076. var removeFileErrorRow = function (that, file) {
  12077. if (file.filestatus === fluid.uploader.fileStatusConstants.ERROR) {
  12078. animateRowRemoval(that, errorRowForFile(that, file));
  12079. }
  12080. };
  12081. var removeFileAndRow = function (that, file, row) {
  12082. // Clean up the stuff associated with a file row.
  12083. removeFileProgress(that, file);
  12084. removeFileErrorRow(that, file);
  12085. // Remove the file itself.
  12086. that.uploadManager.removeFile(file);
  12087. animateRowRemoval(that, row);
  12088. };
  12089. var removeFileForRow = function (that, row) {
  12090. var file = fileForRow(that, row);
  12091. if (!file || file.filestatus === fluid.uploader.fileStatusConstants.COMPLETE) {
  12092. return;
  12093. }
  12094. removeFileAndRow(that, file, row);
  12095. };
  12096. var removeRowForFile = function (that, file) {
  12097. var row = rowForFile(that, file);
  12098. removeFileAndRow(that, file, row);
  12099. };
  12100. var bindHover = function (row, styles) {
  12101. var over = function () {
  12102. if (row.hasClass(styles.ready) && !row.hasClass(styles.uploading)) {
  12103. row.addClass(styles.hover);
  12104. }
  12105. };
  12106. var out = function () {
  12107. if (row.hasClass(styles.ready) && !row.hasClass(styles.uploading)) {
  12108. row.removeClass(styles.hover);
  12109. }
  12110. };
  12111. row.hover(over, out);
  12112. };
  12113. var bindDeleteKey = function (that, row) {
  12114. var deleteHandler = function () {
  12115. removeFileForRow(that, row);
  12116. };
  12117. fluid.activatable(row, null, {
  12118. additionalBindings: [{
  12119. key: $.ui.keyCode.DELETE,
  12120. activateHandler: deleteHandler
  12121. }]
  12122. });
  12123. };
  12124. var bindRowHandlers = function (that, row) {
  12125. if ($.browser.msie && $.browser.version < 7) {
  12126. bindHover(row, that.options.styles);
  12127. }
  12128. that.locate("fileIconBtn", row).click(function () {
  12129. removeFileForRow(that, row);
  12130. });
  12131. bindDeleteKey(that, row);
  12132. };
  12133. var renderRowFromTemplate = function (that, file) {
  12134. var row = that.rowTemplate.clone();
  12135. row.removeClass(that.options.styles.hiddenTemplate);
  12136. that.locate("fileName", row).text(file.name);
  12137. that.locate("fileSize", row).text(fluid.uploader.formatFileSize(file.size));
  12138. that.locate("fileIconBtn", row).addClass(that.options.styles.remove);
  12139. row.attr("id", file.id);
  12140. row.addClass(that.options.styles.ready);
  12141. bindRowHandlers(that, row);
  12142. return row;
  12143. };
  12144. var createProgressorFromTemplate = function (that, row) {
  12145. // create a new progress bar for the row and position it
  12146. var rowProgressor = that.rowProgressorTemplate.clone();
  12147. var rowId = row.attr("id");
  12148. var progressId = rowId + "_progress";
  12149. rowProgressor.attr("id", progressId);
  12150. rowProgressor.css("top", row.position().top);
  12151. rowProgressor.height(row.height()).width(5);
  12152. that.container.after(rowProgressor);
  12153. that.fileProgressors[progressId] = fluid.progress(that.uploadContainer, {
  12154. selectors: {
  12155. progressBar: "#" + rowId,
  12156. displayElement: "#" + progressId,
  12157. label: "#" + progressId + " .fl-uploader-file-progress-text",
  12158. indicator: "#" + progressId
  12159. }
  12160. });
  12161. };
  12162. var addFile = function (that, file) {
  12163. var row = renderRowFromTemplate(that, file);
  12164. /* FLUID-2720 - do not hide the row under IE8 */
  12165. if (!($.browser.msie && ($.browser.version >= 8))) {
  12166. row.hide();
  12167. }
  12168. that.container.append(row);
  12169. row.fadeIn("slow");
  12170. that.scroller.scrollBottom();
  12171. createProgressorFromTemplate(that, row);
  12172. that.refreshView();
  12173. };
  12174. var prepareForUpload = function (that) {
  12175. var rowButtons = that.locate("fileIconBtn", that.locate("fileRows"));
  12176. rowButtons.attr("disabled", "disabled");
  12177. rowButtons.addClass(that.options.styles.dim);
  12178. };
  12179. var refreshAfterUpload = function (that) {
  12180. var rowButtons = that.locate("fileIconBtn", that.locate("fileRows"));
  12181. rowButtons.removeAttr("disabled");
  12182. rowButtons.removeClass(that.options.styles.dim);
  12183. };
  12184. var changeRowState = function (that, row, newState) {
  12185. row.removeClass(that.options.styles.ready).removeClass(that.options.styles.error).addClass(newState);
  12186. };
  12187. var markRowAsComplete = function (that, file) {
  12188. // update styles and keyboard bindings for the file row
  12189. var row = rowForFile(that, file);
  12190. changeRowState(that, row, that.options.styles.uploaded);
  12191. row.attr("title", that.options.strings.status.success);
  12192. fluid.enabled(row, false);
  12193. // update the click event and the styling for the file delete button
  12194. var removeRowBtn = that.locate("fileIconBtn", row);
  12195. removeRowBtn.unbind("click");
  12196. removeRowBtn.removeClass(that.options.styles.remove);
  12197. removeRowBtn.attr("title", that.options.strings.status.success);
  12198. };
  12199. var renderErrorInfoRowFromTemplate = function (that, fileRow, error) {
  12200. // Render the row by cloning the template and binding its id to the file.
  12201. var errorRow = that.errorInfoRowTemplate.clone();
  12202. errorRow.attr("id", fileRow.attr("id") + "_error");
  12203. // Look up the error message and render it.
  12204. var errorType = fluid.keyForValue(fluid.uploader.errorConstants, error);
  12205. var errorMsg = that.options.strings.errors[errorType];
  12206. that.locate("errorText", errorRow).text(errorMsg);
  12207. fileRow.after(errorRow);
  12208. that.scroller.scrollTo(errorRow);
  12209. };
  12210. var showErrorForFile = function (that, file, error) {
  12211. hideFileProgress(that, file);
  12212. if (file.filestatus === fluid.uploader.fileStatusConstants.ERROR) {
  12213. var fileRowElm = rowForFile(that, file);
  12214. changeRowState(that, fileRowElm, that.options.styles.error);
  12215. renderErrorInfoRowFromTemplate(that, fileRowElm, error);
  12216. }
  12217. };
  12218. var bindModelEvents = function (that) {
  12219. that.returnedOptions = {
  12220. listeners: {
  12221. afterFileQueued: that.addFile,
  12222. onUploadStart: that.prepareForUpload,
  12223. onFileStart: that.showFileProgress,
  12224. onFileProgress: that.updateFileProgress,
  12225. onFileSuccess: that.markFileComplete,
  12226. onFileError: that.showErrorForFile,
  12227. afterFileComplete: that.hideFileProgress,
  12228. afterUploadComplete: that.refreshAfterUpload
  12229. }
  12230. };
  12231. };
  12232. var addKeyboardNavigation = function (that) {
  12233. fluid.tabbable(that.container);
  12234. that.selectableContext = fluid.selectable(that.container, {
  12235. selectableSelector: that.options.selectors.fileRows,
  12236. onSelect: function (itemToSelect) {
  12237. $(itemToSelect).addClass(that.options.styles.selected);
  12238. },
  12239. onUnselect: function (selectedItem) {
  12240. $(selectedItem).removeClass(that.options.styles.selected);
  12241. }
  12242. });
  12243. };
  12244. var prepareTemplateElements = function (that) {
  12245. // Grab our template elements out of the DOM.
  12246. that.rowTemplate = that.locate("rowTemplate").remove();
  12247. that.errorInfoRowTemplate = that.locate("errorInfoRowTemplate").remove();
  12248. that.errorInfoRowTemplate.removeClass(that.options.styles.hiddenTemplate);
  12249. that.rowProgressorTemplate = that.locate("rowProgressorTemplate", that.uploadContainer).remove();
  12250. };
  12251. var setupFileQueue = function (that, uploadManager) {
  12252. that.uploadManager = uploadManager;
  12253. that.scroller = fluid.scroller(that.container);
  12254. prepareTemplateElements(that);
  12255. addKeyboardNavigation(that);
  12256. bindModelEvents(that);
  12257. };
  12258. /**
  12259. * Creates a new File Queue view.
  12260. *
  12261. * @param {jQuery|selector} container the file queue's container DOM element
  12262. * @param {UploadManager} uploadManager an upload manager model instance
  12263. * @param {Object} options configuration options for the view
  12264. */
  12265. fluid.fileQueueView = function (container, parentContainer, uploadManager, options) {
  12266. var that = fluid.initView("fluid.fileQueueView", container, options);
  12267. that.uploadContainer = parentContainer;
  12268. that.fileProgressors = {};
  12269. that.addFile = function (file) {
  12270. addFile(that, file);
  12271. };
  12272. that.removeFile = function (file) {
  12273. removeRowForFile(that, file);
  12274. };
  12275. that.prepareForUpload = function () {
  12276. prepareForUpload(that);
  12277. };
  12278. that.refreshAfterUpload = function () {
  12279. refreshAfterUpload(that);
  12280. };
  12281. that.showFileProgress = function (file) {
  12282. startFileProgress(that, file);
  12283. };
  12284. that.updateFileProgress = function (file, fileBytesComplete, fileTotalBytes) {
  12285. updateFileProgress(that, file, fileBytesComplete, fileTotalBytes);
  12286. };
  12287. that.markFileComplete = function (file) {
  12288. progressorForFile(that, file).update(100, "100%");
  12289. markRowAsComplete(that, file);
  12290. };
  12291. that.showErrorForFile = function (file, error) {
  12292. showErrorForFile(that, file, error);
  12293. };
  12294. that.hideFileProgress = function (file) {
  12295. hideFileProgress(that, file);
  12296. };
  12297. that.refreshView = function () {
  12298. that.scroller.refreshView();
  12299. that.selectableContext.refresh();
  12300. };
  12301. setupFileQueue(that, uploadManager);
  12302. return that;
  12303. };
  12304. fluid.defaults("fluid.fileQueueView", {
  12305. selectors: {
  12306. fileRows: ".flc-uploader-file",
  12307. fileName: ".flc-uploader-file-name",
  12308. fileSize: ".flc-uploader-file-size",
  12309. fileIconBtn: ".flc-uploader-file-action",
  12310. errorText: ".flc-uploader-file-error",
  12311. rowTemplate: ".flc-uploader-file-tmplt",
  12312. errorInfoRowTemplate: ".flc-uploader-file-error-tmplt",
  12313. rowProgressorTemplate: ".flc-uploader-file-progressor-tmplt"
  12314. },
  12315. styles: {
  12316. hover: "fl-uploader-file-hover",
  12317. selected: "fl-uploader-file-focus",
  12318. ready: "fl-uploader-file-state-ready",
  12319. uploading: "fl-uploader-file-state-uploading",
  12320. uploaded: "fl-uploader-file-state-uploaded",
  12321. error: "fl-uploader-file-state-error",
  12322. remove: "fl-uploader-file-action-remove",
  12323. dim: "fl-uploader-dim",
  12324. hiddenTemplate: "fl-uploader-hidden-templates"
  12325. },
  12326. strings: {
  12327. progress: {
  12328. toUploadLabel: "To upload: %fileCount %fileLabel (%totalBytes)",
  12329. singleFile: "file",
  12330. pluralFiles: "files"
  12331. },
  12332. status: {
  12333. success: "File Uploaded",
  12334. error: "File Upload Error"
  12335. },
  12336. errors: {
  12337. HTTP_ERROR: "File upload error: a network error occured or the file was rejected (reason unknown).",
  12338. IO_ERROR: "File upload error: a network error occured.",
  12339. UPLOAD_LIMIT_EXCEEDED: "File upload error: you have uploaded as many files as you are allowed during this session",
  12340. UPLOAD_FAILED: "File upload error: the upload failed for an unknown reason.",
  12341. QUEUE_LIMIT_EXCEEDED: "You have as many files in the queue as can be added at one time. Removing files from the queue may allow you to add different files.",
  12342. FILE_EXCEEDS_SIZE_LIMIT: "One or more of the files that you attempted to add to the queue exceeded the limit of %fileSizeLimit.",
  12343. ZERO_BYTE_FILE: "One or more of the files that you attempted to add contained no data.",
  12344. INVALID_FILETYPE: "One or more files were not added to the queue because they were of the wrong type."
  12345. }
  12346. }
  12347. });
  12348. })(jQuery, fluid_1_1);
  12349. /************
  12350. * Uploader *
  12351. ************/
  12352. (function ($, fluid) {
  12353. var fileOrFiles = function (that, numFiles) {
  12354. return (numFiles === 1) ? that.options.strings.progress.singleFile :
  12355. that.options.strings.progress.pluralFiles;
  12356. };
  12357. var enableElement = function (that, elm) {
  12358. elm.removeAttr("disabled");
  12359. elm.removeClass(that.options.styles.dim);
  12360. };
  12361. var disableElement = function (that, elm) {
  12362. elm.attr("disabled", "disabled");
  12363. elm.addClass(that.options.styles.dim);
  12364. };
  12365. var showElement = function (that, elm) {
  12366. elm.removeClass(that.options.styles.hidden);
  12367. };
  12368. var hideElement = function (that, elm) {
  12369. elm.addClass(that.options.styles.hidden);
  12370. };
  12371. var setTotalProgressStyle = function (that, didError) {
  12372. didError = didError || false;
  12373. var indicator = that.totalProgress.indicator;
  12374. indicator.toggleClass(that.options.styles.totalProgress, !didError);
  12375. indicator.toggleClass(that.options.styles.totalProgressError, didError);
  12376. };
  12377. var setStateEmpty = function (that) {
  12378. disableElement(that, that.locate("uploadButton"));
  12379. // If the queue is totally empty, treat it specially.
  12380. if (that.uploadManager.queue.files.length === 0) {
  12381. that.locate("browseButton").text(that.options.strings.buttons.browse);
  12382. showElement(that, that.locate("instructions"));
  12383. }
  12384. };
  12385. var setStateDone = function (that) {
  12386. disableElement(that, that.locate("uploadButton"));
  12387. enableElement(that, that.locate("browseButton"));
  12388. hideElement(that, that.locate("pauseButton"));
  12389. showElement(that, that.locate("uploadButton"));
  12390. };
  12391. var setStateLoaded = function (that) {
  12392. that.locate("browseButton").text(that.options.strings.buttons.addMore);
  12393. hideElement(that, that.locate("pauseButton"));
  12394. showElement(that, that.locate("uploadButton"));
  12395. enableElement(that, that.locate("uploadButton"));
  12396. enableElement(that, that.locate("browseButton"));
  12397. hideElement(that, that.locate("instructions"));
  12398. that.totalProgress.hide();
  12399. };
  12400. var setStateUploading = function (that) {
  12401. that.totalProgress.hide(false, false);
  12402. setTotalProgressStyle(that);
  12403. hideElement(that, that.locate("uploadButton"));
  12404. disableElement(that, that.locate("browseButton"));
  12405. enableElement(that, that.locate("pauseButton"));
  12406. showElement(that, that.locate("pauseButton"));
  12407. that.locate(that.options.focusWithEvent.afterUploadStart).focus();
  12408. };
  12409. var renderUploadTotalMessage = function (that) {
  12410. // Render template for the total file status message.
  12411. var numReadyFiles = that.uploadManager.queue.getReadyFiles().length;
  12412. var bytesReadyFiles = that.uploadManager.queue.sizeOfReadyFiles();
  12413. var fileLabelStr = fileOrFiles(that, numReadyFiles);
  12414. var totalStateStr = fluid.stringTemplate(that.options.strings.progress.toUploadLabel, {
  12415. fileCount: numReadyFiles,
  12416. fileLabel: fileLabelStr,
  12417. totalBytes: fluid.uploader.formatFileSize(bytesReadyFiles)
  12418. });
  12419. that.locate("totalFileStatusText").html(totalStateStr);
  12420. };
  12421. var updateTotalProgress = function (that) {
  12422. var batch = that.uploadManager.queue.currentBatch;
  12423. var totalPercent = fluid.uploader.derivePercent(batch.totalBytesUploaded, batch.totalBytes);
  12424. var numFilesInBatch = batch.files.length;
  12425. var fileLabelStr = fileOrFiles(that, numFilesInBatch);
  12426. var totalProgressStr = fluid.stringTemplate(that.options.strings.progress.totalProgressLabel, {
  12427. curFileN: batch.fileIdx + 1,
  12428. totalFilesN: numFilesInBatch,
  12429. fileLabel: fileLabelStr,
  12430. currBytes: fluid.uploader.formatFileSize(batch.totalBytesUploaded),
  12431. totalBytes: fluid.uploader.formatFileSize(batch.totalBytes)
  12432. });
  12433. that.totalProgress.update(totalPercent, totalProgressStr);
  12434. };
  12435. var updateTotalAtCompletion = function (that) {
  12436. var numErroredFiles = that.uploadManager.queue.getErroredFiles().length;
  12437. var numTotalFiles = that.uploadManager.queue.files.length;
  12438. var fileLabelStr = fileOrFiles(that, numTotalFiles);
  12439. var errorStr = "";
  12440. // if there are errors then change the total progress bar
  12441. // and set up the errorStr so that we can use it in the totalProgressStr
  12442. if (numErroredFiles > 0) {
  12443. var errorLabelString = (numErroredFiles === 1) ? that.options.strings.progress.singleError :
  12444. that.options.strings.progress.pluralErrors;
  12445. setTotalProgressStyle(that, true);
  12446. errorStr = fluid.stringTemplate(that.options.strings.progress.numberOfErrors, {
  12447. errorsN: numErroredFiles,
  12448. errorLabel: errorLabelString
  12449. });
  12450. }
  12451. var totalProgressStr = fluid.stringTemplate(that.options.strings.progress.completedLabel, {
  12452. curFileN: that.uploadManager.queue.getUploadedFiles().length,
  12453. totalFilesN: numTotalFiles,
  12454. errorString: errorStr,
  12455. fileLabel: fileLabelStr,
  12456. totalCurrBytes: fluid.uploader.formatFileSize(that.uploadManager.queue.sizeOfUploadedFiles())
  12457. });
  12458. that.totalProgress.update(100, totalProgressStr);
  12459. };
  12460. var bindDOMEvents = function (that) {
  12461. that.locate("browseButton").click(function (evnt) {
  12462. that.uploadManager.browseForFiles();
  12463. evnt.preventDefault();
  12464. });
  12465. that.locate("uploadButton").click(function () {
  12466. that.uploadManager.start();
  12467. });
  12468. that.locate("pauseButton").click(function () {
  12469. that.uploadManager.stop();
  12470. });
  12471. };
  12472. var updateStateAfterFileDialog = function (that) {
  12473. if (that.uploadManager.queue.getReadyFiles().length > 0) {
  12474. setStateLoaded(that);
  12475. renderUploadTotalMessage(that);
  12476. that.locate(that.options.focusWithEvent.afterFileDialog).focus();
  12477. }
  12478. };
  12479. var updateStateAfterFileRemoval = function (that) {
  12480. if (that.uploadManager.queue.getReadyFiles().length === 0) {
  12481. setStateEmpty(that);
  12482. }
  12483. renderUploadTotalMessage(that);
  12484. };
  12485. var updateStateAfterPause = function (that) {
  12486. // do nothing, moved to afterUploadComplete
  12487. };
  12488. var updateStateAfterCompletion = function (that) {
  12489. var userPaused = that.uploadManager.queue.shouldStop;
  12490. if (that.uploadManager.queue.getReadyFiles().length === 0) {
  12491. setStateDone(that);
  12492. } else {
  12493. setStateLoaded(that);
  12494. }
  12495. updateTotalAtCompletion(that);
  12496. };
  12497. var bindModelEvents = function (that) {
  12498. that.events.afterFileDialog.addListener(function () {
  12499. updateStateAfterFileDialog(that);
  12500. });
  12501. that.events.afterFileRemoved.addListener(function () {
  12502. updateStateAfterFileRemoval(that);
  12503. });
  12504. that.events.onUploadStart.addListener(function () {
  12505. setStateUploading(that);
  12506. });
  12507. that.events.onUploadStop.addListener(function () {
  12508. that.locate(that.options.focusWithEvent.afterUploadStop).focus();
  12509. });
  12510. that.events.onFileProgress.addListener(function () {
  12511. updateTotalProgress(that);
  12512. });
  12513. that.events.onFileSuccess.addListener(function () {
  12514. updateTotalProgress(that);
  12515. });
  12516. that.events.onFileError.addListener(function (file, error, message) {
  12517. if (error === fluid.uploader.errorConstants.UPLOAD_STOPPED) {
  12518. updateStateAfterPause(that);
  12519. }
  12520. });
  12521. that.events.afterUploadComplete.addListener(function () {
  12522. updateStateAfterCompletion(that);
  12523. });
  12524. };
  12525. var initUploadManager = function (that) {
  12526. var manager = fluid.initSubcomponent(that,
  12527. "uploadManager",
  12528. [that.events, fluid.COMPONENT_OPTIONS]);
  12529. return that.options.demo ? fluid.demoUploadManager(manager) : manager;
  12530. };
  12531. var setupUploader = function (that) {
  12532. // Instantiate the upload manager, file queue view, and total file progress bar,
  12533. // passing them smaller chunks of the overall options for the uploader.
  12534. that.decorators = fluid.initSubcomponents(that, "decorators", [that, fluid.COMPONENT_OPTIONS]);
  12535. that.uploadManager = initUploadManager(that);
  12536. that.fileQueueView = fluid.initSubcomponent(that,
  12537. "fileQueueView",
  12538. [that.locate("fileQueue"),
  12539. that.container,
  12540. that.uploadManager,
  12541. fluid.COMPONENT_OPTIONS]);
  12542. that.totalProgress = fluid.initSubcomponent(that,
  12543. "totalProgressBar",
  12544. [that.container, fluid.COMPONENT_OPTIONS]);
  12545. // Upload button should not be enabled until there are files to upload
  12546. disableElement(that, that.locate("uploadButton"));
  12547. bindDOMEvents(that);
  12548. bindModelEvents(that);
  12549. };
  12550. /**
  12551. * Instantiates a new Uploader component.
  12552. *
  12553. * @param {Object} container the DOM element in which the Uploader lives
  12554. * @param {Object} options configuration options for the component.
  12555. */
  12556. fluid.uploader = function (container, options) {
  12557. var that = fluid.initView("fluid.uploader", container, options);
  12558. setupUploader(that);
  12559. return that;
  12560. };
  12561. /**
  12562. * Instantiates a new Uploader component in the progressive enhancement style.
  12563. * This mode requires another DOM element to be present, the element that is to be enhanced.
  12564. * This method checks to see if the correct version of Flash is present, and will only
  12565. * create the Uploader component if so.
  12566. *
  12567. * @param {Object} container the DOM element in which the Uploader component lives
  12568. * @param {Object} enhanceable the DOM element to show if the system requirements aren't met
  12569. * @param {Object} options configuration options for the component
  12570. */
  12571. fluid.progressiveEnhanceableUploader = function (container, enhanceable, options) {
  12572. enhanceable = fluid.container(enhanceable);
  12573. container = fluid.container(container);
  12574. if (swfobject.getFlashPlayerVersion().major < 9) {
  12575. // Degrade gracefully.
  12576. enhanceable.show();
  12577. } else {
  12578. // Instantiate the component.
  12579. container.show();
  12580. return fluid.uploader(container, options);
  12581. }
  12582. };
  12583. /**
  12584. * Pretty prints a file's size, converting from bytes to kilobytes or megabytes.
  12585. *
  12586. * @param {Number} bytes the files size, specified as in number bytes.
  12587. */
  12588. fluid.uploader.formatFileSize = function (bytes) {
  12589. if (typeof bytes === "number") {
  12590. if (bytes === 0) {
  12591. return "0.0 KB";
  12592. } else if (bytes > 0) {
  12593. if (bytes < 1048576) {
  12594. return (Math.ceil(bytes / 1024 * 10) / 10).toFixed(1) + " KB";
  12595. }
  12596. else {
  12597. return (Math.ceil(bytes / 1048576 * 10) / 10).toFixed(1) + " MB";
  12598. }
  12599. }
  12600. }
  12601. return "";
  12602. };
  12603. fluid.uploader.derivePercent = function (num, total) {
  12604. return Math.round((num * 100) / total);
  12605. };
  12606. fluid.defaults("fluid.uploader", {
  12607. demo: false,
  12608. decorators: [{
  12609. type: "fluid.swfUploadSetupDecorator"
  12610. }, {
  12611. type: "fluid.manuallyDegrade",
  12612. options: {
  12613. selectors: {
  12614. enhanceable: ".fl-uploader.fl-progEnhance-basic"
  12615. }
  12616. }
  12617. }],
  12618. uploadManager: {
  12619. type: "fluid.swfUploadManager"
  12620. },
  12621. fileQueueView: {
  12622. type: "fluid.fileQueueView"
  12623. },
  12624. totalProgressBar: {
  12625. type: "fluid.progress",
  12626. options: {
  12627. selectors: {
  12628. progressBar: ".flc-uploader-queue-footer",
  12629. displayElement: ".flc-uploader-total-progress",
  12630. label: ".flc-uploader-total-progress-text",
  12631. indicator: ".flc-uploader-total-progress",
  12632. ariaElement: ".flc-uploader-total-progress"
  12633. }
  12634. }
  12635. },
  12636. selectors: {
  12637. fileQueue: ".flc-uploader-queue",
  12638. browseButton: ".flc-uploader-button-browse",
  12639. uploadButton: ".flc-uploader-button-upload",
  12640. pauseButton: ".flc-uploader-button-pause",
  12641. totalFileStatusText: ".flc-uploader-total-progress-text",
  12642. instructions: ".flc-uploader-browse-instructions"
  12643. },
  12644. // Event listeners must already be implemented to use these options.
  12645. // At the moment, the following events are supported:
  12646. // afterFileDialog, afterUploadStart, and afterUploadStop.
  12647. focusWithEvent: {
  12648. afterFileDialog: "uploadButton",
  12649. afterUploadStart: "pauseButton",
  12650. afterUploadStop: "uploadButton"
  12651. },
  12652. styles: {
  12653. disabled: "fl-uploader-disabled",
  12654. hidden: "fl-uploader-hidden",
  12655. dim: "fl-uploader-dim",
  12656. totalProgress: "fl-uploader-total-progress-okay",
  12657. totalProgressError: "fl-uploader-total-progress-errored"
  12658. },
  12659. events: {
  12660. afterReady: null,
  12661. onFileDialog: null,
  12662. afterFileQueued: null,
  12663. afterFileRemoved: null,
  12664. onQueueError: null,
  12665. afterFileDialog: null,
  12666. onUploadStart: null,
  12667. onUploadStop: null,
  12668. onFileStart: null,
  12669. onFileProgress: null,
  12670. onFileError: null,
  12671. onFileSuccess: null,
  12672. afterFileComplete: null,
  12673. afterUploadComplete: null
  12674. },
  12675. strings: {
  12676. progress: {
  12677. toUploadLabel: "To upload: %fileCount %fileLabel (%totalBytes)",
  12678. totalProgressLabel: "Uploading: %curFileN of %totalFilesN %fileLabel (%currBytes of %totalBytes)",
  12679. completedLabel: "Uploaded: %curFileN of %totalFilesN %fileLabel (%totalCurrBytes)%errorString",
  12680. numberOfErrors: ", %errorsN %errorLabel",
  12681. singleFile: "file",
  12682. pluralFiles: "files",
  12683. singleError: "error",
  12684. pluralErrors: "errors"
  12685. },
  12686. buttons: {
  12687. browse: "Browse Files",
  12688. addMore: "Add More",
  12689. stopUpload: "Stop Upload",
  12690. cancelRemaning: "Cancel remaining Uploads",
  12691. resumeUpload: "Resume Upload"
  12692. }
  12693. }
  12694. });
  12695. fluid.uploader.errorConstants = {
  12696. HTTP_ERROR: -200,
  12697. MISSING_UPLOAD_URL: -210,
  12698. IO_ERROR: -220,
  12699. SECURITY_ERROR: -230,
  12700. UPLOAD_LIMIT_EXCEEDED: -240,
  12701. UPLOAD_FAILED: -250,
  12702. SPECIFIED_FILE_ID_NOT_FOUND: -260,
  12703. FILE_VALIDATION_FAILED: -270,
  12704. FILE_CANCELLED: -280,
  12705. UPLOAD_STOPPED: -290
  12706. };
  12707. fluid.uploader.fileStatusConstants = {
  12708. QUEUED: -1,
  12709. IN_PROGRESS: -2,
  12710. ERROR: -3,
  12711. COMPLETE: -4,
  12712. CANCELLED: -5
  12713. };
  12714. /*******************
  12715. * ManuallyDegrade *
  12716. *******************/
  12717. var renderLink = function (renderLocation, text, classes, appendBeside) {
  12718. var link = $("<a href='#'>" + text + "</a>");
  12719. link.addClass(classes);
  12720. if (renderLocation === "before") {
  12721. appendBeside.before(link);
  12722. } else {
  12723. appendBeside.after(link);
  12724. }
  12725. return link;
  12726. };
  12727. var toggleVisibility = function (toShow, toHide) {
  12728. // For FLUID-2789: hide() doesn't work in Opera, so this check
  12729. // uses a style to hide if the browser is Opera
  12730. if (window.opera) {
  12731. toShow.show().removeClass("hideUploaderForOpera");
  12732. toHide.show().addClass("hideUploaderForOpera");
  12733. } else {
  12734. toShow.show();
  12735. toHide.hide();
  12736. }
  12737. };
  12738. var defaultControlRenderer = function (that) {
  12739. var degradeLink = renderLink(that.options.defaultRenderLocation,
  12740. that.options.strings.degradeLinkText,
  12741. that.options.styles.degradeLinkClass,
  12742. that.enhancedContainer);
  12743. degradeLink.addClass("flc-manuallyDegrade-degrade");
  12744. var enhanceLink = renderLink(that.options.defaultRenderLocation,
  12745. that.options.strings.enhanceLinkText,
  12746. that.options.styles.enhanceLinkClass,
  12747. that.degradedContainer);
  12748. enhanceLink.addClass("flc-manuallyDegrade-enhance");
  12749. };
  12750. var fetchControls = function (that) {
  12751. that.degradeControl = that.locate("degradeControl");
  12752. that.enhanceControl = that.locate("enhanceControl");
  12753. };
  12754. var setupManuallyDegrade = function (that) {
  12755. // If we don't have anything to degrade to, stop right here.
  12756. if (!that.degradedContainer.length) {
  12757. return;
  12758. }
  12759. // Render the controls if they're not already there.
  12760. fetchControls(that);
  12761. if (!that.degradeControl.length && !that.enhanceControl.length) {
  12762. that.options.controlRenderer(that);
  12763. fetchControls(that);
  12764. }
  12765. // Bind click handlers to them.
  12766. that.degradeControl.click(that.degrade);
  12767. that.enhanceControl.click(that.enhance);
  12768. // Hide the enhance link to start.
  12769. that.enhanceControl.hide();
  12770. };
  12771. var determineContainer = function (options) {
  12772. var defaults = fluid.defaults("fluid.manuallyDegrade");
  12773. return (options && options.container) ? options.container : defaults.container;
  12774. };
  12775. fluid.manuallyDegrade = function (component, options) {
  12776. var container = determineContainer(options);
  12777. var that = fluid.initView("fluid.manuallyDegrade", container, options);
  12778. var isDegraded = false;
  12779. that.enhancedContainer = component.container;
  12780. that.degradedContainer = that.locate("enhanceable");