privates.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. /**
  2. * A global unique id count.
  3. *
  4. * @static
  5. * @private
  6. * @property _uniqueId
  7. * @type Integer
  8. **/
  9. var _uniqueId = 0;
  10. /**
  11. * The plugin prefix for cookies.
  12. *
  13. * @final
  14. * @private
  15. * @property _cookiePrefix
  16. * @type String
  17. **/
  18. var _cookiePrefix = "jQu3ry_5teps_St@te_";
  19. /**
  20. * Suffix for the unique tab id.
  21. *
  22. * @final
  23. * @private
  24. * @property _tabSuffix
  25. * @type String
  26. * @since 0.9.7
  27. **/
  28. var _tabSuffix = "-t-";
  29. /**
  30. * Suffix for the unique tabpanel id.
  31. *
  32. * @final
  33. * @private
  34. * @property _tabpanelSuffix
  35. * @type String
  36. * @since 0.9.7
  37. **/
  38. var _tabpanelSuffix = "-p-";
  39. /**
  40. * Suffix for the unique title id.
  41. *
  42. * @final
  43. * @private
  44. * @property _titleSuffix
  45. * @type String
  46. * @since 0.9.7
  47. **/
  48. var _titleSuffix = "-h-";
  49. /**
  50. * An error message for an "index out of range" error.
  51. *
  52. * @final
  53. * @private
  54. * @property _indexOutOfRangeErrorMessage
  55. * @type String
  56. **/
  57. var _indexOutOfRangeErrorMessage = "Index out of range.";
  58. /**
  59. * An error message for an "missing corresponding element" error.
  60. *
  61. * @final
  62. * @private
  63. * @property _missingCorrespondingElementErrorMessage
  64. * @type String
  65. **/
  66. var _missingCorrespondingElementErrorMessage = "One or more corresponding step {0} are missing.";
  67. /**
  68. * Adds a step to the cache.
  69. *
  70. * @static
  71. * @private
  72. * @method addStepToCache
  73. * @param wizard {Object} A jQuery wizard object
  74. * @param step {Object} The step object to add
  75. **/
  76. function addStepToCache(wizard, step)
  77. {
  78. getSteps(wizard).push(step);
  79. }
  80. function analyzeData(wizard, options, state)
  81. {
  82. var stepTitles = wizard.children(options.headerTag),
  83. stepContents = wizard.children(options.bodyTag);
  84. // Validate content
  85. if (stepTitles.length > stepContents.length)
  86. {
  87. throwError(_missingCorrespondingElementErrorMessage, "contents");
  88. }
  89. else if (stepTitles.length < stepContents.length)
  90. {
  91. throwError(_missingCorrespondingElementErrorMessage, "titles");
  92. }
  93. var startIndex = options.startIndex;
  94. state.stepCount = stepTitles.length;
  95. // Tries to load the saved state (step position)
  96. if (options.saveState && $.cookie)
  97. {
  98. var savedState = $.cookie(_cookiePrefix + getUniqueId(wizard));
  99. // Sets the saved position to the start index if not undefined or out of range
  100. var savedIndex = parseInt(savedState, 0);
  101. if (!isNaN(savedIndex) && savedIndex < state.stepCount)
  102. {
  103. startIndex = savedIndex;
  104. }
  105. }
  106. state.currentIndex = startIndex;
  107. stepTitles.each(function (index)
  108. {
  109. var item = $(this), // item == header
  110. content = stepContents.eq(index),
  111. modeData = content.data("mode"),
  112. mode = (modeData == null) ? contentMode.html : getValidEnumValue(contentMode,
  113. (/^\s*$/.test(modeData) || isNaN(modeData)) ? modeData : parseInt(modeData, 0)),
  114. contentUrl = (mode === contentMode.html || content.data("url") === undefined) ?
  115. "" : content.data("url"),
  116. contentLoaded = (mode !== contentMode.html && content.data("loaded") === "1"),
  117. step = $.extend({}, stepModel, {
  118. title: item.html(),
  119. content: (mode === contentMode.html) ? content.html() : "",
  120. contentUrl: contentUrl,
  121. contentMode: mode,
  122. contentLoaded: contentLoaded
  123. });
  124. addStepToCache(wizard, step);
  125. });
  126. }
  127. /**
  128. * Triggers the onCanceled event.
  129. *
  130. * @static
  131. * @private
  132. * @method cancel
  133. * @param wizard {Object} The jQuery wizard object
  134. **/
  135. function cancel(wizard)
  136. {
  137. wizard.triggerHandler("canceled");
  138. }
  139. function decreaseCurrentIndexBy(state, decreaseBy)
  140. {
  141. return state.currentIndex - decreaseBy;
  142. }
  143. /**
  144. * Removes the control functionality completely and transforms the current state to the initial HTML structure.
  145. *
  146. * @static
  147. * @private
  148. * @method destroy
  149. * @param wizard {Object} A jQuery wizard object
  150. **/
  151. function destroy(wizard, options)
  152. {
  153. var eventNamespace = getEventNamespace(wizard);
  154. // Remove virtual data objects from the wizard
  155. wizard.unbind(eventNamespace).removeData("uid").removeData("options")
  156. .removeData("state").removeData("steps").removeData("eventNamespace")
  157. .find(".actions a").unbind(eventNamespace);
  158. // Remove attributes and CSS classes from the wizard
  159. wizard.removeClass(options.clearFixCssClass + " vertical");
  160. var contents = wizard.find(".content > *");
  161. // Remove virtual data objects from panels and their titles
  162. contents.removeData("loaded").removeData("mode").removeData("url");
  163. // Remove attributes, CSS classes and reset inline styles on all panels and their titles
  164. contents.removeAttr("id").removeAttr("role").removeAttr("tabindex")
  165. .removeAttr("class").removeAttr("style")._removeAria("labelledby")
  166. ._removeAria("hidden");
  167. // Empty panels if the mode is set to 'async' or 'iframe'
  168. wizard.find(".content > [data-mode='async'],.content > [data-mode='iframe']").empty();
  169. var wizardSubstitute = $("<{0} class=\"{1}\"></{0}>".format(wizard.get(0).tagName, wizard.attr("class")));
  170. var wizardId = wizard._id();
  171. if (wizardId != null && wizardId !== "")
  172. {
  173. wizardSubstitute._id(wizardId);
  174. }
  175. wizardSubstitute.html(wizard.find(".content").html());
  176. wizard.after(wizardSubstitute);
  177. wizard.remove();
  178. return wizardSubstitute;
  179. }
  180. /**
  181. * Triggers the onFinishing and onFinished event.
  182. *
  183. * @static
  184. * @private
  185. * @method finishStep
  186. * @param wizard {Object} The jQuery wizard object
  187. * @param state {Object} The state container of the current wizard
  188. **/
  189. function finishStep(wizard, state)
  190. {
  191. var currentStep = wizard.find(".steps li").eq(state.currentIndex);
  192. if (wizard.triggerHandler("finishing", [state.currentIndex]))
  193. {
  194. currentStep.addClass("done").removeClass("error");
  195. wizard.triggerHandler("finished", [state.currentIndex]);
  196. }
  197. else
  198. {
  199. currentStep.addClass("error");
  200. }
  201. }
  202. /**
  203. * Gets or creates if not exist an unique event namespace for the given wizard instance.
  204. *
  205. * @static
  206. * @private
  207. * @method getEventNamespace
  208. * @param wizard {Object} A jQuery wizard object
  209. * @return {String} Returns the unique event namespace for the given wizard
  210. */
  211. function getEventNamespace(wizard)
  212. {
  213. var eventNamespace = wizard.data("eventNamespace");
  214. if (eventNamespace == null)
  215. {
  216. eventNamespace = "." + getUniqueId(wizard);
  217. wizard.data("eventNamespace", eventNamespace);
  218. }
  219. return eventNamespace;
  220. }
  221. function getStepAnchor(wizard, index)
  222. {
  223. var uniqueId = getUniqueId(wizard);
  224. return wizard.find("#" + uniqueId + _tabSuffix + index);
  225. }
  226. function getStepPanel(wizard, index)
  227. {
  228. var uniqueId = getUniqueId(wizard);
  229. return wizard.find("#" + uniqueId + _tabpanelSuffix + index);
  230. }
  231. function getStepTitle(wizard, index)
  232. {
  233. var uniqueId = getUniqueId(wizard);
  234. return wizard.find("#" + uniqueId + _titleSuffix + index);
  235. }
  236. function getOptions(wizard)
  237. {
  238. return wizard.data("options");
  239. }
  240. function getState(wizard)
  241. {
  242. return wizard.data("state");
  243. }
  244. function getSteps(wizard)
  245. {
  246. return wizard.data("steps");
  247. }
  248. /**
  249. * Gets a specific step object by index.
  250. *
  251. * @static
  252. * @private
  253. * @method getStep
  254. * @param index {Integer} An integer that belongs to the position of a step
  255. * @return {Object} A specific step object
  256. **/
  257. function getStep(wizard, index)
  258. {
  259. var steps = getSteps(wizard);
  260. if (index < 0 || index >= steps.length)
  261. {
  262. throwError(_indexOutOfRangeErrorMessage);
  263. }
  264. return steps[index];
  265. }
  266. /**
  267. * Gets or creates if not exist an unique id from the given wizard instance.
  268. *
  269. * @static
  270. * @private
  271. * @method getUniqueId
  272. * @param wizard {Object} A jQuery wizard object
  273. * @return {String} Returns the unique id for the given wizard
  274. */
  275. function getUniqueId(wizard)
  276. {
  277. var uniqueId = wizard.data("uid");
  278. if (uniqueId == null)
  279. {
  280. uniqueId = wizard._id();
  281. if (uniqueId == null)
  282. {
  283. uniqueId = "steps-uid-".concat(_uniqueId);
  284. wizard._id(uniqueId);
  285. }
  286. _uniqueId++;
  287. wizard.data("uid", uniqueId);
  288. }
  289. return uniqueId;
  290. }
  291. /**
  292. * Gets a valid enum value by checking a specific enum key or value.
  293. *
  294. * @static
  295. * @private
  296. * @method getValidEnumValue
  297. * @param enumType {Object} Type of enum
  298. * @param keyOrValue {Object} Key as `String` or value as `Integer` to check for
  299. */
  300. function getValidEnumValue(enumType, keyOrValue)
  301. {
  302. validateArgument("enumType", enumType);
  303. validateArgument("keyOrValue", keyOrValue);
  304. // Is key
  305. if (typeof keyOrValue === "string")
  306. {
  307. var value = enumType[keyOrValue];
  308. if (value === undefined)
  309. {
  310. throwError("The enum key '{0}' does not exist.", keyOrValue);
  311. }
  312. return value;
  313. }
  314. // Is value
  315. else if (typeof keyOrValue === "number")
  316. {
  317. for (var key in enumType)
  318. {
  319. if (enumType[key] === keyOrValue)
  320. {
  321. return keyOrValue;
  322. }
  323. }
  324. throwError("Invalid enum value '{0}'.", keyOrValue);
  325. }
  326. // Type is not supported
  327. else
  328. {
  329. throwError("Invalid key or value type.");
  330. }
  331. }
  332. /**
  333. * Routes to the next step.
  334. *
  335. * @static
  336. * @private
  337. * @method goToNextStep
  338. * @param wizard {Object} The jQuery wizard object
  339. * @param options {Object} Settings of the current wizard
  340. * @param state {Object} The state container of the current wizard
  341. * @return {Boolean} Indicates whether the action executed
  342. **/
  343. function goToNextStep(wizard, options, state)
  344. {
  345. return paginationClick(wizard, options, state, increaseCurrentIndexBy(state, 1));
  346. }
  347. /**
  348. * Routes to the previous step.
  349. *
  350. * @static
  351. * @private
  352. * @method goToPreviousStep
  353. * @param wizard {Object} The jQuery wizard object
  354. * @param options {Object} Settings of the current wizard
  355. * @param state {Object} The state container of the current wizard
  356. * @return {Boolean} Indicates whether the action executed
  357. **/
  358. function goToPreviousStep(wizard, options, state)
  359. {
  360. return paginationClick(wizard, options, state, decreaseCurrentIndexBy(state, 1));
  361. }
  362. /**
  363. * Routes to a specific step by a given index.
  364. *
  365. * @static
  366. * @private
  367. * @method goToStep
  368. * @param wizard {Object} The jQuery wizard object
  369. * @param options {Object} Settings of the current wizard
  370. * @param state {Object} The state container of the current wizard
  371. * @param index {Integer} The position (zero-based) to route to
  372. * @return {Boolean} Indicates whether the action succeeded or failed
  373. **/
  374. function goToStep(wizard, options, state, index)
  375. {
  376. if (index < 0 || index >= state.stepCount)
  377. {
  378. throwError(_indexOutOfRangeErrorMessage);
  379. }
  380. if (options.forceMoveForward && index < state.currentIndex)
  381. {
  382. return;
  383. }
  384. var oldIndex = state.currentIndex;
  385. if (wizard.triggerHandler("stepChanging", [state.currentIndex, index]))
  386. {
  387. // Save new state
  388. state.currentIndex = index;
  389. saveCurrentStateToCookie(wizard, options, state);
  390. // Change visualisation
  391. refreshStepNavigation(wizard, options, state, oldIndex);
  392. refreshPagination(wizard, options, state);
  393. loadAsyncContent(wizard, options, state);
  394. startTransitionEffect(wizard, options, state, index, oldIndex, function()
  395. {
  396. wizard.triggerHandler("stepChanged", [index, oldIndex]);
  397. });
  398. }
  399. else
  400. {
  401. wizard.find(".steps li").eq(oldIndex).addClass("error");
  402. }
  403. return true;
  404. }
  405. function increaseCurrentIndexBy(state, increaseBy)
  406. {
  407. return state.currentIndex + increaseBy;
  408. }
  409. /**
  410. * Initializes the component.
  411. *
  412. * @static
  413. * @private
  414. * @method initialize
  415. * @param options {Object} The component settings
  416. **/
  417. function initialize(options)
  418. {
  419. /*jshint -W040 */
  420. var opts = $.extend(true, {}, defaults, options);
  421. return this.each(function ()
  422. {
  423. var wizard = $(this);
  424. var state = {
  425. currentIndex: opts.startIndex,
  426. currentStep: null,
  427. stepCount: 0,
  428. transitionElement: null
  429. };
  430. // Create data container
  431. wizard.data("options", opts);
  432. wizard.data("state", state);
  433. wizard.data("steps", []);
  434. analyzeData(wizard, opts, state);
  435. render(wizard, opts, state);
  436. registerEvents(wizard, opts);
  437. // Trigger focus
  438. if (opts.autoFocus && _uniqueId === 0)
  439. {
  440. getStepAnchor(wizard, opts.startIndex).focus();
  441. }
  442. wizard.triggerHandler("init", [opts.startIndex]);
  443. });
  444. }
  445. /**
  446. * Inserts a new step to a specific position.
  447. *
  448. * @static
  449. * @private
  450. * @method insertStep
  451. * @param wizard {Object} The jQuery wizard object
  452. * @param options {Object} Settings of the current wizard
  453. * @param state {Object} The state container of the current wizard
  454. * @param index {Integer} The position (zero-based) to add
  455. * @param step {Object} The step object to add
  456. * @example
  457. * $("#wizard").steps().insert(0, {
  458. * title: "Title",
  459. * content: "", // optional
  460. * contentMode: "async", // optional
  461. * contentUrl: "/Content/Step/1" // optional
  462. * });
  463. * @chainable
  464. **/
  465. function insertStep(wizard, options, state, index, step)
  466. {
  467. if (index < 0 || index > state.stepCount)
  468. {
  469. throwError(_indexOutOfRangeErrorMessage);
  470. }
  471. // TODO: Validate step object
  472. // Change data
  473. step = $.extend({}, stepModel, step);
  474. insertStepToCache(wizard, index, step);
  475. if (state.currentIndex !== state.stepCount && state.currentIndex >= index)
  476. {
  477. state.currentIndex++;
  478. saveCurrentStateToCookie(wizard, options, state);
  479. }
  480. state.stepCount++;
  481. var contentContainer = wizard.find(".content"),
  482. header = $("<{0}>{1}</{0}>".format(options.headerTag, step.title)),
  483. body = $("<{0}></{0}>".format(options.bodyTag));
  484. if (step.contentMode == null || step.contentMode === contentMode.html)
  485. {
  486. body.html(step.content);
  487. }
  488. if (index === 0)
  489. {
  490. contentContainer.prepend(body).prepend(header);
  491. }
  492. else
  493. {
  494. getStepPanel(wizard, (index - 1)).after(body).after(header);
  495. }
  496. renderBody(wizard, state, body, index);
  497. renderTitle(wizard, options, state, header, index);
  498. refreshSteps(wizard, options, state, index);
  499. if (index === state.currentIndex)
  500. {
  501. refreshStepNavigation(wizard, options, state);
  502. }
  503. refreshPagination(wizard, options, state);
  504. return wizard;
  505. }
  506. /**
  507. * Inserts a step object to the cache at a specific position.
  508. *
  509. * @static
  510. * @private
  511. * @method insertStepToCache
  512. * @param wizard {Object} A jQuery wizard object
  513. * @param index {Integer} The position (zero-based) to add
  514. * @param step {Object} The step object to add
  515. **/
  516. function insertStepToCache(wizard, index, step)
  517. {
  518. getSteps(wizard).splice(index, 0, step);
  519. }
  520. /**
  521. * Handles the keyup DOM event for pagination.
  522. *
  523. * @static
  524. * @private
  525. * @event keyup
  526. * @param event {Object} An event object
  527. */
  528. function keyUpHandler(event)
  529. {
  530. var wizard = $(this),
  531. options = getOptions(wizard),
  532. state = getState(wizard);
  533. if (options.suppressPaginationOnFocus && wizard.find(":focus").is(":input"))
  534. {
  535. event.preventDefault();
  536. return false;
  537. }
  538. var keyCodes = { left: 37, right: 39 };
  539. if (event.keyCode === keyCodes.left)
  540. {
  541. event.preventDefault();
  542. goToPreviousStep(wizard, options, state);
  543. }
  544. else if (event.keyCode === keyCodes.right)
  545. {
  546. event.preventDefault();
  547. goToNextStep(wizard, options, state);
  548. }
  549. }
  550. /**
  551. * Loads and includes async content.
  552. *
  553. * @static
  554. * @private
  555. * @method loadAsyncContent
  556. * @param wizard {Object} A jQuery wizard object
  557. * @param options {Object} Settings of the current wizard
  558. * @param state {Object} The state container of the current wizard
  559. */
  560. function loadAsyncContent(wizard, options, state)
  561. {
  562. if (state.stepCount > 0)
  563. {
  564. var currentIndex = state.currentIndex,
  565. currentStep = getStep(wizard, currentIndex);
  566. if (!options.enableContentCache || !currentStep.contentLoaded)
  567. {
  568. switch (getValidEnumValue(contentMode, currentStep.contentMode))
  569. {
  570. case contentMode.iframe:
  571. wizard.find(".content > .body").eq(state.currentIndex).empty()
  572. .html("<iframe src=\"" + currentStep.contentUrl + "\" frameborder=\"0\" scrolling=\"no\" />")
  573. .data("loaded", "1");
  574. break;
  575. case contentMode.async:
  576. var currentStepContent = getStepPanel(wizard, currentIndex)._aria("busy", "true")
  577. .empty().append(renderTemplate(options.loadingTemplate, { text: options.labels.loading }));
  578. $.ajax({ url: currentStep.contentUrl, cache: false }).done(function (data)
  579. {
  580. currentStepContent.empty().html(data)._aria("busy", "false").data("loaded", "1");
  581. wizard.triggerHandler("contentLoaded", [currentIndex]);
  582. });
  583. break;
  584. }
  585. }
  586. }
  587. }
  588. /**
  589. * Fires the action next or previous click event.
  590. *
  591. * @static
  592. * @private
  593. * @method paginationClick
  594. * @param wizard {Object} The jQuery wizard object
  595. * @param options {Object} Settings of the current wizard
  596. * @param state {Object} The state container of the current wizard
  597. * @param index {Integer} The position (zero-based) to route to
  598. * @return {Boolean} Indicates whether the event fired successfully or not
  599. **/
  600. function paginationClick(wizard, options, state, index)
  601. {
  602. var oldIndex = state.currentIndex;
  603. if (index >= 0 && index < state.stepCount && !(options.forceMoveForward && index < state.currentIndex))
  604. {
  605. var anchor = getStepAnchor(wizard, index),
  606. parent = anchor.parent(),
  607. isDisabled = parent.hasClass("disabled");
  608. // Enable the step to make the anchor clickable!
  609. parent._enableAria();
  610. anchor.click();
  611. // An error occured
  612. if (oldIndex === state.currentIndex && isDisabled)
  613. {
  614. // Disable the step again if current index has not changed; prevents click action.
  615. parent._enableAria(false);
  616. return false;
  617. }
  618. return true;
  619. }
  620. return false;
  621. }
  622. /**
  623. * Fires when a pagination click happens.
  624. *
  625. * @static
  626. * @private
  627. * @event click
  628. * @param event {Object} An event object
  629. */
  630. function paginationClickHandler(event)
  631. {
  632. event.preventDefault();
  633. var anchor = $(this),
  634. wizard = anchor.parent().parent().parent().parent(),
  635. options = getOptions(wizard),
  636. state = getState(wizard),
  637. href = anchor.attr("href");
  638. switch (href.substring(href.lastIndexOf("#") + 1))
  639. {
  640. case "cancel":
  641. cancel(wizard);
  642. break;
  643. case "finish":
  644. finishStep(wizard, state);
  645. break;
  646. case "next":
  647. goToNextStep(wizard, options, state);
  648. break;
  649. case "previous":
  650. goToPreviousStep(wizard, options, state);
  651. break;
  652. }
  653. }
  654. /**
  655. * Refreshs the visualization state for the entire pagination.
  656. *
  657. * @static
  658. * @private
  659. * @method refreshPagination
  660. * @param wizard {Object} A jQuery wizard object
  661. * @param options {Object} Settings of the current wizard
  662. * @param state {Object} The state container of the current wizard
  663. */
  664. function refreshPagination(wizard, options, state)
  665. {
  666. if (options.enablePagination)
  667. {
  668. var finish = wizard.find(".actions a[href$='#finish']").parent(),
  669. next = wizard.find(".actions a[href$='#next']").parent();
  670. if (!options.forceMoveForward)
  671. {
  672. var previous = wizard.find(".actions a[href$='#previous']").parent();
  673. previous._enableAria(state.currentIndex > 0);
  674. }
  675. if (options.enableFinishButton && options.showFinishButtonAlways)
  676. {
  677. finish._enableAria(state.stepCount > 0);
  678. next._enableAria(state.stepCount > 1 && state.stepCount > (state.currentIndex + 1));
  679. }
  680. else
  681. {
  682. finish._showAria(options.enableFinishButton && state.stepCount === (state.currentIndex + 1));
  683. next._showAria(state.stepCount === 0 || state.stepCount > (state.currentIndex + 1)).
  684. _enableAria(state.stepCount > (state.currentIndex + 1) || !options.enableFinishButton);
  685. }
  686. }
  687. }
  688. /**
  689. * Refreshs the visualization state for the step navigation (tabs).
  690. *
  691. * @static
  692. * @private
  693. * @method refreshStepNavigation
  694. * @param wizard {Object} A jQuery wizard object
  695. * @param options {Object} Settings of the current wizard
  696. * @param state {Object} The state container of the current wizard
  697. * @param [oldIndex] {Integer} The index of the prior step
  698. */
  699. function refreshStepNavigation(wizard, options, state, oldIndex)
  700. {
  701. var currentOrNewStepAnchor = getStepAnchor(wizard, state.currentIndex),
  702. currentInfo = $("<span class=\"current-info audible\">" + options.labels.current + " </span>"),
  703. stepTitles = wizard.find(".content > .title");
  704. if (oldIndex != null)
  705. {
  706. var oldStepAnchor = getStepAnchor(wizard, oldIndex);
  707. oldStepAnchor.parent().addClass("done").removeClass("error")._selectAria(false);
  708. stepTitles.eq(oldIndex).removeClass("current").next(".body").removeClass("current");
  709. currentInfo = oldStepAnchor.find(".current-info");
  710. currentOrNewStepAnchor.focus();
  711. }
  712. currentOrNewStepAnchor.prepend(currentInfo).parent()._selectAria().removeClass("done")._enableAria();
  713. stepTitles.eq(state.currentIndex).addClass("current").next(".body").addClass("current");
  714. }
  715. /**
  716. * Refreshes step buttons and their related titles beyond a certain position.
  717. *
  718. * @static
  719. * @private
  720. * @method refreshSteps
  721. * @param wizard {Object} A jQuery wizard object
  722. * @param options {Object} Settings of the current wizard
  723. * @param state {Object} The state container of the current wizard
  724. * @param index {Integer} The start point for refreshing ids
  725. */
  726. function refreshSteps(wizard, options, state, index)
  727. {
  728. var uniqueId = getUniqueId(wizard);
  729. for (var i = index; i < state.stepCount; i++)
  730. {
  731. var uniqueStepId = uniqueId + _tabSuffix + i,
  732. uniqueBodyId = uniqueId + _tabpanelSuffix + i,
  733. uniqueHeaderId = uniqueId + _titleSuffix + i,
  734. title = wizard.find(".title").eq(i)._id(uniqueHeaderId);
  735. wizard.find(".steps a").eq(i)._id(uniqueStepId)
  736. ._aria("controls", uniqueBodyId).attr("href", "#" + uniqueHeaderId)
  737. .html(renderTemplate(options.titleTemplate, { index: i + 1, title: title.html() }));
  738. wizard.find(".body").eq(i)._id(uniqueBodyId)
  739. ._aria("labelledby", uniqueHeaderId);
  740. }
  741. }
  742. function registerEvents(wizard, options)
  743. {
  744. var eventNamespace = getEventNamespace(wizard);
  745. wizard.bind("canceled" + eventNamespace, options.onCanceled);
  746. wizard.bind("contentLoaded" + eventNamespace, options.onContentLoaded);
  747. wizard.bind("finishing" + eventNamespace, options.onFinishing);
  748. wizard.bind("finished" + eventNamespace, options.onFinished);
  749. wizard.bind("init" + eventNamespace, options.onInit);
  750. wizard.bind("stepChanging" + eventNamespace, options.onStepChanging);
  751. wizard.bind("stepChanged" + eventNamespace, options.onStepChanged);
  752. if (options.enableKeyNavigation)
  753. {
  754. wizard.bind("keyup" + eventNamespace, keyUpHandler);
  755. }
  756. wizard.find(".actions a").bind("click" + eventNamespace, paginationClickHandler);
  757. }
  758. /**
  759. * Removes a specific step by an given index.
  760. *
  761. * @static
  762. * @private
  763. * @method removeStep
  764. * @param wizard {Object} A jQuery wizard object
  765. * @param options {Object} Settings of the current wizard
  766. * @param state {Object} The state container of the current wizard
  767. * @param index {Integer} The position (zero-based) of the step to remove
  768. * @return Indecates whether the item is removed.
  769. **/
  770. function removeStep(wizard, options, state, index)
  771. {
  772. // Index out of range and try deleting current item will return false.
  773. if (index < 0 || index >= state.stepCount || state.currentIndex === index)
  774. {
  775. return false;
  776. }
  777. // Change data
  778. removeStepFromCache(wizard, index);
  779. if (state.currentIndex > index)
  780. {
  781. state.currentIndex--;
  782. saveCurrentStateToCookie(wizard, options, state);
  783. }
  784. state.stepCount--;
  785. getStepTitle(wizard, index).remove();
  786. getStepPanel(wizard, index).remove();
  787. getStepAnchor(wizard, index).parent().remove();
  788. // Set the "first" class to the new first step button
  789. if (index === 0)
  790. {
  791. wizard.find(".steps li").first().addClass("first");
  792. }
  793. // Set the "last" class to the new last step button
  794. if (index === state.stepCount)
  795. {
  796. wizard.find(".steps li").eq(index).addClass("last");
  797. }
  798. refreshSteps(wizard, options, state, index);
  799. refreshPagination(wizard, options, state);
  800. return true;
  801. }
  802. function removeStepFromCache(wizard, index)
  803. {
  804. getSteps(wizard).splice(index, 1);
  805. }
  806. /**
  807. * Transforms the base html structure to a more sensible html structure.
  808. *
  809. * @static
  810. * @private
  811. * @method render
  812. * @param wizard {Object} A jQuery wizard object
  813. * @param options {Object} Settings of the current wizard
  814. * @param state {Object} The state container of the current wizard
  815. **/
  816. function render(wizard, options, state)
  817. {
  818. // Create a content wrapper and copy HTML from the intial wizard structure
  819. var wrapperTemplate = "<{0} class=\"{1}\">{2}</{0}>",
  820. orientation = getValidEnumValue(stepsOrientation, options.stepsOrientation),
  821. verticalCssClass = (orientation === stepsOrientation.vertical) ? " vertical" : "",
  822. contentWrapper = $(wrapperTemplate.format(options.contentContainerTag, "content " + options.clearFixCssClass, wizard.html())),
  823. stepsWrapper = $(wrapperTemplate.format(options.stepsContainerTag, "steps " + options.clearFixCssClass, "<ul role=\"tablist\"></ul>")),
  824. stepTitles = contentWrapper.children(options.headerTag),
  825. stepContents = contentWrapper.children(options.bodyTag);
  826. // Transform the wizard wrapper and remove the inner HTML
  827. wizard.attr("role", "application").empty().append(stepsWrapper).append(contentWrapper)
  828. .addClass(options.cssClass + " " + options.clearFixCssClass + verticalCssClass);
  829. // Add WIA-ARIA support
  830. stepContents.each(function (index)
  831. {
  832. renderBody(wizard, state, $(this), index);
  833. });
  834. stepTitles.each(function (index)
  835. {
  836. renderTitle(wizard, options, state, $(this), index);
  837. });
  838. refreshStepNavigation(wizard, options, state);
  839. renderPagination(wizard, options, state);
  840. }
  841. /**
  842. * Transforms the body to a proper tabpanel.
  843. *
  844. * @static
  845. * @private
  846. * @method renderBody
  847. * @param wizard {Object} A jQuery wizard object
  848. * @param body {Object} A jQuery body object
  849. * @param index {Integer} The position of the body
  850. */
  851. function renderBody(wizard, state, body, index)
  852. {
  853. var uniqueId = getUniqueId(wizard),
  854. uniqueBodyId = uniqueId + _tabpanelSuffix + index,
  855. uniqueHeaderId = uniqueId + _titleSuffix + index;
  856. body._id(uniqueBodyId).attr("role", "tabpanel")._aria("labelledby", uniqueHeaderId)
  857. .addClass("body")._showAria(state.currentIndex === index);
  858. }
  859. /**
  860. * Renders a pagination if enabled.
  861. *
  862. * @static
  863. * @private
  864. * @method renderPagination
  865. * @param wizard {Object} A jQuery wizard object
  866. * @param options {Object} Settings of the current wizard
  867. * @param state {Object} The state container of the current wizard
  868. */
  869. function renderPagination(wizard, options, state)
  870. {
  871. if (options.enablePagination)
  872. {
  873. var pagination = "<{0} class=\"actions {1}\"><ul role=\"menu\" aria-label=\"{2}\">{3}</ul></{0}>",
  874. buttonTemplate = "<li><a href=\"#{0}\" role=\"menuitem\">{1}</a></li>",
  875. buttons = "";
  876. if (!options.forceMoveForward)
  877. {
  878. buttons += buttonTemplate.format("previous", options.labels.previous);
  879. }
  880. buttons += buttonTemplate.format("next", options.labels.next);
  881. if (options.enableFinishButton)
  882. {
  883. buttons += buttonTemplate.format("finish", options.labels.finish);
  884. }
  885. if (options.enableCancelButton)
  886. {
  887. buttons += buttonTemplate.format("cancel", options.labels.cancel);
  888. }
  889. wizard.append(pagination.format(options.actionContainerTag, options.clearFixCssClass,
  890. options.labels.pagination, buttons));
  891. refreshPagination(wizard, options, state);
  892. loadAsyncContent(wizard, options, state);
  893. }
  894. }
  895. /**
  896. * Renders a template and replaces all placeholder.
  897. *
  898. * @static
  899. * @private
  900. * @method renderTemplate
  901. * @param template {String} A template
  902. * @param substitutes {Object} A list of substitute
  903. * @return {String} The rendered template
  904. */
  905. function renderTemplate(template, substitutes)
  906. {
  907. var matches = template.match(/#([a-z]*)#/gi);
  908. for (var i = 0; i < matches.length; i++)
  909. {
  910. var match = matches[i],
  911. key = match.substring(1, match.length - 1);
  912. if (substitutes[key] === undefined)
  913. {
  914. throwError("The key '{0}' does not exist in the substitute collection!", key);
  915. }
  916. template = template.replace(match, substitutes[key]);
  917. }
  918. return template;
  919. }
  920. /**
  921. * Transforms the title to a step item button.
  922. *
  923. * @static
  924. * @private
  925. * @method renderTitle
  926. * @param wizard {Object} A jQuery wizard object
  927. * @param options {Object} Settings of the current wizard
  928. * @param state {Object} The state container of the current wizard
  929. * @param header {Object} A jQuery header object
  930. * @param index {Integer} The position of the header
  931. */
  932. function renderTitle(wizard, options, state, header, index)
  933. {
  934. var uniqueId = getUniqueId(wizard),
  935. uniqueStepId = uniqueId + _tabSuffix + index,
  936. uniqueBodyId = uniqueId + _tabpanelSuffix + index,
  937. uniqueHeaderId = uniqueId + _titleSuffix + index,
  938. stepCollection = wizard.find(".steps > ul"),
  939. title = renderTemplate(options.titleTemplate, {
  940. index: index + 1,
  941. title: header.html()
  942. }),
  943. stepItem = $("<li role=\"tab\"><a id=\"" + uniqueStepId + "\" href=\"#" + uniqueHeaderId +
  944. "\" aria-controls=\"" + uniqueBodyId + "\">" + title + "</a></li>");
  945. stepItem._enableAria(options.enableAllSteps || state.currentIndex > index);
  946. if (state.currentIndex > index)
  947. {
  948. stepItem.addClass("done");
  949. }
  950. header._id(uniqueHeaderId).attr("tabindex", "-1").addClass("title");
  951. if (index === 0)
  952. {
  953. stepCollection.prepend(stepItem);
  954. }
  955. else
  956. {
  957. stepCollection.find("li").eq(index - 1).after(stepItem);
  958. }
  959. // Set the "first" class to the new first step button
  960. if (index === 0)
  961. {
  962. stepCollection.find("li").removeClass("first").eq(index).addClass("first");
  963. }
  964. // Set the "last" class to the new last step button
  965. if (index === (state.stepCount - 1))
  966. {
  967. stepCollection.find("li").removeClass("last").eq(index).addClass("last");
  968. }
  969. // Register click event
  970. stepItem.children("a").bind("click" + getEventNamespace(wizard), stepClickHandler);
  971. }
  972. /**
  973. * Saves the current state to a cookie.
  974. *
  975. * @static
  976. * @private
  977. * @method saveCurrentStateToCookie
  978. * @param wizard {Object} A jQuery wizard object
  979. * @param options {Object} Settings of the current wizard
  980. * @param state {Object} The state container of the current wizard
  981. */
  982. function saveCurrentStateToCookie(wizard, options, state)
  983. {
  984. if (options.saveState && $.cookie)
  985. {
  986. $.cookie(_cookiePrefix + getUniqueId(wizard), state.currentIndex);
  987. }
  988. }
  989. function startTransitionEffect(wizard, options, state, index, oldIndex, doneCallback)
  990. {
  991. var stepContents = wizard.find(".content > .body"),
  992. effect = getValidEnumValue(transitionEffect, options.transitionEffect),
  993. effectSpeed = options.transitionEffectSpeed,
  994. newStep = stepContents.eq(index),
  995. currentStep = stepContents.eq(oldIndex);
  996. switch (effect)
  997. {
  998. case transitionEffect.fade:
  999. case transitionEffect.slide:
  1000. var hide = (effect === transitionEffect.fade) ? "fadeOut" : "slideUp",
  1001. show = (effect === transitionEffect.fade) ? "fadeIn" : "slideDown";
  1002. state.transitionElement = newStep;
  1003. currentStep[hide](effectSpeed, function ()
  1004. {
  1005. var wizard = $(this)._showAria(false).parent().parent(),
  1006. state = getState(wizard);
  1007. if (state.transitionElement)
  1008. {
  1009. state.transitionElement[show](effectSpeed, function ()
  1010. {
  1011. $(this)._showAria();
  1012. }).promise().done(doneCallback);
  1013. state.transitionElement = null;
  1014. }
  1015. });
  1016. break;
  1017. case transitionEffect.slideLeft:
  1018. var outerWidth = currentStep.outerWidth(true),
  1019. posFadeOut = (index > oldIndex) ? -(outerWidth) : outerWidth,
  1020. posFadeIn = (index > oldIndex) ? outerWidth : -(outerWidth);
  1021. $.when(currentStep.animate({ left: posFadeOut }, effectSpeed,
  1022. function () { $(this)._showAria(false); }),
  1023. newStep.css("left", posFadeIn + "px")._showAria()
  1024. .animate({ left: 0 }, effectSpeed)).done(doneCallback);
  1025. break;
  1026. default:
  1027. $.when(currentStep._showAria(false), newStep._showAria())
  1028. .done(doneCallback);
  1029. break;
  1030. }
  1031. }
  1032. /**
  1033. * Fires when a step click happens.
  1034. *
  1035. * @static
  1036. * @private
  1037. * @event click
  1038. * @param event {Object} An event object
  1039. */
  1040. function stepClickHandler(event)
  1041. {
  1042. event.preventDefault();
  1043. var anchor = $(this),
  1044. wizard = anchor.parent().parent().parent().parent(),
  1045. options = getOptions(wizard),
  1046. state = getState(wizard),
  1047. oldIndex = state.currentIndex;
  1048. if (anchor.parent().is(":not(.disabled):not(.current)"))
  1049. {
  1050. var href = anchor.attr("href"),
  1051. position = parseInt(href.substring(href.lastIndexOf("-") + 1), 0);
  1052. goToStep(wizard, options, state, position);
  1053. }
  1054. // If nothing has changed
  1055. if (oldIndex === state.currentIndex)
  1056. {
  1057. getStepAnchor(wizard, oldIndex).focus();
  1058. return false;
  1059. }
  1060. }
  1061. function throwError(message)
  1062. {
  1063. if (arguments.length > 1)
  1064. {
  1065. message = message.format(Array.prototype.slice.call(arguments, 1));
  1066. }
  1067. throw new Error(message);
  1068. }
  1069. /**
  1070. * Checks an argument for null or undefined and throws an error if one check applies.
  1071. *
  1072. * @static
  1073. * @private
  1074. * @method validateArgument
  1075. * @param argumentName {String} The name of the given argument
  1076. * @param argumentValue {Object} The argument itself
  1077. */
  1078. function validateArgument(argumentName, argumentValue)
  1079. {
  1080. if (argumentValue == null)
  1081. {
  1082. throwError("The argument '{0}' is null or undefined.", argumentName);
  1083. }
  1084. }