Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

1725 righe
50 KiB

  1. /*!
  2. * Monday Webforms for CoreMedia v1.9.3, (c) 2018 Monday Consulting GmbH
  3. *
  4. * @see https://monday-webforms.com/
  5. */
  6. /*global define, window, document, jQuery, exports, require */
  7. ;(function(factory) {
  8. "use strict";
  9. if (typeof define === 'function' && define.amd) {
  10. // AMD. Register as an anonymous module.
  11. define(['jquery'], factory);
  12. } else if (typeof exports === 'object' && typeof require === 'function') {
  13. // Node/CommonJS
  14. factory(require('jquery'));
  15. } else {
  16. // Browser globals
  17. factory(jQuery);
  18. }
  19. }(function($) {
  20. "use strict";
  21. // polyfill for customevent for IE10
  22. (function() {
  23. function CustomEvent(event, params) {
  24. params = params || {bubbles: false, cancelable: false, detail: undefined};
  25. var evt = document.createEvent('CustomEvent');
  26. evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  27. return evt;
  28. }
  29. CustomEvent.prototype = window.Event.prototype;
  30. window.CustomEvent = CustomEvent;
  31. })();
  32. var EVENTS = {
  33. AJAX_FINISHED: "mwf-ajax-finished",
  34. AJAX_ERROR: "mwf-ajax-error",
  35. FILL_DROPDOWN: "mwf-fill-dropdown",
  36. FILL_SELECTION: "mwf-fill-selection",
  37. FILL_HIDDEN: "mwf-fill-hidden",
  38. SUGGESTION_SELECTED: "mwf-suggestion-selected",
  39. VALUE_CHANGED: "mwf-value-changed"
  40. },
  41. globalSettings = {};
  42. function triggerEvent(el, eventName, options) {
  43. var event;
  44. if (window.CustomEvent) {
  45. event = new CustomEvent(eventName, options);
  46. } else {
  47. event = document.createEvent('CustomEvent');
  48. event.initCustomEvent(eventName, true, true, options);
  49. }
  50. el.dispatchEvent(event);
  51. }
  52. function globalSettingsWithVariant(variant) {
  53. return variant === undefined ?
  54. globalSettings.def : $.extend(true, {}, globalSettings.def, globalSettings[variant]);
  55. }
  56. /**
  57. * Monday Webforms jQuery-Plugin
  58. * @constructor
  59. */
  60. function Webforms(elem, settings) {
  61. var
  62. plugin = this,
  63. $elem = $(elem),
  64. operators = {},
  65. formdata = {},
  66. filenames = {},
  67. uiState = {
  68. visible: {},
  69. hidden: {},
  70. writable: {},
  71. readonly: {},
  72. optional: {},
  73. mandatory: {},
  74. disabled: {},
  75. enabled: {}
  76. },
  77. stateMapping = {
  78. visible: 'hidden',
  79. hidden: 'visible',
  80. writable: 'readonly',
  81. readonly: 'writable',
  82. optional: 'mandatory',
  83. mandatory: 'optional',
  84. disabled: 'enabled',
  85. enabled: 'disabled'
  86. },
  87. $form = $elem.is('form') ? $elem : $elem.find("form"),
  88. formId = $form.dataWithDefault('mwf-id', $form.data('mwf-form')),
  89. targetUrl = $form.dataWithDefault('mwf-target', settings.url),
  90. statisticsUrl = settings.statisticsUrl;
  91. if (settings.formdata !== undefined) {
  92. formdata = settings.formdata;
  93. }
  94. if (!statisticsUrl || 0 === statisticsUrl.length) {
  95. statisticsUrl = null;
  96. }
  97. plugin.settings = settings;
  98. /* internal utility functions
  99. ----------------------------------------------------------------------------------------------------------- */
  100. function updateUI(fields, conditionId, cond) {
  101. var s, i, inverseState, isTrue, isFalse, state, input,
  102. conditionalFieldsState = {
  103. 'visible': [], 'hidden': [],
  104. 'writable': [], 'readonly': [],
  105. 'optional': [], 'mandatory': [],
  106. 'enabled': [], 'disabled': []
  107. };
  108. // clear UI state of this condition
  109. for (s in uiState) {
  110. if (uiState.hasOwnProperty(s)) {
  111. delete uiState[s][conditionId];
  112. }
  113. }
  114. for (i = 0; i < fields.length; i++) {
  115. input = fields[i].input;
  116. state = fields[i].state;
  117. if (cond) {
  118. conditionalFieldsState[state].push(input);
  119. }
  120. uiState[state][conditionId] = conditionalFieldsState[state];
  121. inverseState = stateMapping[state];
  122. isTrue = containsState(state, input);
  123. isFalse = containsState(inverseState, input);
  124. if (isTrue) {
  125. plugin.settings.operations[state]($form, fields[i]);
  126. if (plugin.settings.onConditionTrue !== undefined) {
  127. plugin.settings.onConditionTrue($form, fields[i], state);
  128. }
  129. } else if (isFalse || !isTrue) {
  130. plugin.settings.operations[inverseState]($form, fields[i]);
  131. if (plugin.settings.onConditionFalse !== undefined) {
  132. plugin.settings.onConditionFalse($form, fields[i], inverseState);
  133. }
  134. }
  135. }
  136. }
  137. function containsState(type, input) {
  138. var state = uiState[type], cond;
  139. for (cond in state) {
  140. if (state.hasOwnProperty(cond) && $.inArray(input, state[cond]) > -1) {
  141. return true;
  142. }
  143. }
  144. return false;
  145. }
  146. function valueChanged($elem) {
  147. if (!$elem.is(':file')) {
  148. formdata = serializeForm($form);
  149. $form.trigger("mwf-valuechange", $elem);
  150. }
  151. }
  152. function startsWith(formValue, value) {
  153. if (formValue == null || value == null) {
  154. return false;
  155. }
  156. return formValue.match(new RegExp("^" + value)) == value;
  157. }
  158. function serializeForm($form) {
  159. var o = {}, a = $form.serializeArray(), form = $form.get(0);
  160. $.each(a, function() {
  161. var input = form.querySelector('[name="' + this.name + '"]'),
  162. value = this.value || '',
  163. type = input.getAttribute('type'),
  164. key;
  165. if (type === 'radio' || type === 'checkbox' || input.nodeName.toLowerCase() === 'select') {
  166. if (!o.hasOwnProperty(this.name)) {
  167. o[this.name] = [];
  168. }
  169. if (startsWith(value, '{')) {
  170. try {
  171. key = JSON.parse(value).k;
  172. } catch (ex) {
  173. // do nothing
  174. }
  175. } else if (value === 'EMPTY_VALUE') {
  176. value = '';
  177. }
  178. o[this.name].push((key !== undefined) ? key : value);
  179. } else if (type === 'hidden') {
  180. if (startsWith(value, '{')) {
  181. try {
  182. key = JSON.parse(value).v;
  183. } catch (ex) {
  184. // do nothing
  185. }
  186. }
  187. o[this.name] = (key !== undefined) ? key : value;
  188. } else {
  189. o[this.name] = value;
  190. }
  191. });
  192. $.each(form.querySelectorAll('input[type="checkbox"]:not(:checked),input[type="radio"]:not(:checked)'), function() {
  193. var name = this.getAttribute('name');
  194. if (!o.hasOwnProperty(name)) {
  195. o[name] = '';
  196. }
  197. });
  198. return o;
  199. }
  200. function valueLabel(name, v) {
  201. var l = [];
  202. $.each($form.find('[name="' + name + '"]'), function() {
  203. var $input = $(this);
  204. if ($input.is(':radio') || $input.is(':checkbox')) {
  205. if ($.inArray($input.attr('data-mwf-value'), v) !== -1) {
  206. l.push($input.attr('data-mwf-label'));
  207. }
  208. } else if ($input.is('select')) {
  209. $.each($input.find('option'), function() {
  210. var $option = $(this);
  211. if ($.inArray($option.attr('data-mwf-value'), v) !== -1) {
  212. l.push($option.attr('data-mwf-label'));
  213. }
  214. });
  215. } else if ($input.is(':file')) {
  216. $.merge(l, filenames[name]);
  217. } else {
  218. l.push(v);
  219. }
  220. });
  221. return l;
  222. }
  223. /* API functions
  224. ----------------------------------------------------------------------------------------------------------- */
  225. function maxSelected(array, max) {
  226. var m = Number(max), l = (array !== null) ? array.length : 0;
  227. return (l < m);
  228. }
  229. function minSelected(array, min) {
  230. var m = Number(min), l = (array !== null) ? array.length : 0;
  231. return (l > m);
  232. }
  233. function isSelected(array, s) {
  234. return array != null && $.inArray(s, array) > -1;
  235. }
  236. function parseAge(format, str) {
  237. if (str == null) {
  238. return null;
  239. }
  240. var date = parseDate(format, str), today = new Date();
  241. return Math.floor((today - date) / (365.25 * 24 * 60 * 60 * 1000));
  242. }
  243. function parseDate(format, date) {
  244. if (date == null) {
  245. return null;
  246. }
  247. return $.format.date(date, format);
  248. }
  249. function isEmptyList(array) {
  250. var i, s;
  251. if (array != null) {
  252. for (i = 0; i < array.length; i++) {
  253. s = String(array[i]);
  254. if (s !== null && s !== '' && s !== 'EMPTY_VALUE') {
  255. return false;
  256. }
  257. }
  258. }
  259. return true;
  260. }
  261. function ajaxFillSelection($elem, attr) {
  262. var data = $.extend(formdata, attr.data);
  263. if ((attr.createEntry === undefined)) {
  264. attr.createEntry = (attr.type === 'checkbox') ? plugin.settings.createCheckBox : plugin.settings.createRadio;
  265. }
  266. if ((attr.onFillSelection === undefined)) {
  267. attr.onFillSelection = plugin.settings.onFillSelection;
  268. }
  269. $.ajax({
  270. url: attr.url,
  271. type: 'POST',
  272. data: data,
  273. traditional: true,
  274. cache: false,
  275. xhrFields: { withCredentials: true } // gfi added
  276. })
  277. .done(function(json) {
  278. var pre = attr.preselected.split(','), i, entry;
  279. $elem.find('[data-mwf-mutable]').remove();
  280. for (i in json) {
  281. if (json.hasOwnProperty(i)) {
  282. entry = json[i];
  283. $elem.append(attr.createEntry($form, attr.name, entry, $.inArray(entry.k, pre) !== -1));
  284. }
  285. }
  286. attr.onFillSelection($form, $elem);
  287. triggerEvent(document, EVENTS.FILL_SELECTION, {detail: {$form: $form, $elem: $elem}});
  288. })
  289. .fail(function(jqXHR, textStatus, errorThrown) {
  290. plugin.settings.onAjaxError(jqXHR, textStatus, errorThrown);
  291. });
  292. }
  293. function ajaxFillHidden($elem, attr) {
  294. var data = $.extend(formdata, attr.data);
  295. $.ajax({
  296. url: attr.url,
  297. type: 'POST',
  298. data: data,
  299. traditional: true,
  300. cache: false,
  301. xhrFields: { withCredentials: true } // gfi added
  302. })
  303. .done(function(json) {
  304. $elem.val(JSON.stringify(json));
  305. $elem.attr('data-mwf-value', json.v);
  306. $elem.trigger('change');
  307. triggerEvent(document, EVENTS.FILL_HIDDEN, {detail: {$form: $form, $elem: $elem}});
  308. })
  309. .fail(function(jqXHR, textStatus, errorThrown) {
  310. plugin.settings.onAjaxError(jqXHR, textStatus, errorThrown);
  311. });
  312. }
  313. function ajaxFillDropdown($elem, attr) {
  314. var data = $.extend(formdata, attr.data);
  315. if ((attr.createOption === undefined)) {
  316. attr.createOption = plugin.settings.createOption;
  317. }
  318. if ((attr.onFillDropdown === undefined)) {
  319. attr.onFillDropdown = plugin.settings.onFillDropdown;
  320. }
  321. $.ajax({
  322. url: attr.url,
  323. type: 'POST',
  324. data: data,
  325. traditional: true,
  326. cache: false,
  327. xhrFields: { withCredentials: true } // gfi added
  328. })
  329. .done(function(json) {
  330. var $option, i, entry, pre = attr.preselected.split(',');
  331. $elem.find('[data-mwf-mutable]').remove();
  332. for (i in json) {
  333. if (json.hasOwnProperty(i)) {
  334. entry = json[i];
  335. $option = attr.createOption($form, entry, $.inArray(entry.k, pre) !== -1);
  336. $elem.append($option);
  337. }
  338. }
  339. attr.onFillDropdown($form, $elem);
  340. triggerEvent(document, EVENTS.FILL_DROPDOWN, {detail: {$form: $form, $elem: $elem}});
  341. })
  342. .fail(function(jqXHR, textStatus, errorThrown) {
  343. plugin.settings.onAjaxError(jqXHR, textStatus, errorThrown);
  344. });
  345. }
  346. function ajaxAutocomplete($elem, attr) {
  347. var chars = 1;
  348. if (attr.params.chars !== undefined) {
  349. chars = attr.params.chars;
  350. }
  351. var onSelect = function(selection) {
  352. triggerEvent(document, EVENTS.SUGGESTION_SELECTED, {
  353. detail: {
  354. $form: $form,
  355. $elem: $elem,
  356. id: formId,
  357. selection: selection,
  358. params: attr.params
  359. }
  360. });
  361. if ($.isFunction(attr.onSelect)) {
  362. attr.onSelect(arguments);
  363. }
  364. };
  365. $elem.autocomplete({
  366. paramName: 'query',
  367. params: attr.data,
  368. serviceUrl: attr.url,
  369. maxHeight: 150,
  370. noCache: true,
  371. minChars: chars,
  372. type: 'POST',
  373. onSelect: onSelect,
  374. autoSelectFirst: true,
  375. sendFormData: true,
  376. transformResult: function(response) {
  377. response = JSON.parse(response);
  378. return {
  379. suggestions: $.map(response, function(entry, key) {
  380. return {value: entry.v, data: entry.k};
  381. })
  382. };
  383. }
  384. });
  385. }
  386. function ajaxSubmit(opt) {
  387. var $buttons = $form.find(':button').filter(':not(:disabled)'),
  388. data = {_parentUrl: window.location.href};
  389. if (plugin.settings.appendUrlVars) {
  390. $.extend(data, $.getUrlVars(window.location.search));
  391. delete data.view;
  392. }
  393. $.extend(data, $.getUrlVars(opt.query), opt.data, $form.serializeObject());
  394. if (opt.onSubmit !== undefined) {
  395. if (!opt.onSubmit($form, opt.url, opt.query)) {
  396. return;
  397. }
  398. }
  399. $buttons.prop('disabled', true);
  400. $.ajax({
  401. url: opt.url,
  402. type: 'POST',
  403. data: data,
  404. traditional: true,
  405. cache: false,
  406. xhrFields: { withCredentials: true } // gfi added
  407. })
  408. .done(function(data, textStatus, jqXHR) {
  409. if (jqXHR && jqXHR.getResponseHeader("webforms_redirect")) {
  410. if (opt.onRedirect !== undefined) {
  411. opt.onRedirect($form, data, textStatus, jqXHR);
  412. }
  413. var timeout = (jqXHR.getResponseHeader('webforms_redirect_delay') || 0) * 1000;
  414. setTimeout(function() {
  415. location.assign(jqXHR.getResponseHeader('webforms_redirect'));
  416. }, timeout);
  417. if (!timeout) {
  418. return;
  419. }
  420. }
  421. $elem = $elem.replaceWithPush(data);
  422. $form = $elem.is('form') ? $elem : $elem.find("form");
  423. if (opt.onSuccess !== undefined) {
  424. opt.onSuccess($form, data, textStatus, jqXHR);
  425. }
  426. triggerEvent(document, EVENTS.AJAX_FINISHED, {detail: {$dest: $elem}});
  427. })
  428. .fail(function(jqXHR, textStatus, errorThrown) {
  429. if (opt.onError !== undefined) {
  430. opt.onError($form, jqXHR, textStatus, errorThrown);
  431. }
  432. $buttons.prop('disabled', false);
  433. triggerEvent(document, EVENTS.AJAX_ERROR, {
  434. detail: {
  435. $dest: $elem,
  436. jqXHR: jqXHR,
  437. textStatus: textStatus,
  438. errorThrown: errorThrown
  439. }
  440. })
  441. });
  442. }
  443. function createCondition(conditionId, conjunction, conditions, fields) {
  444. var checkCondition = function() {
  445. var all = true, any = false, condTrue, i, formValue, cond;
  446. for (i = 0; i < conditions.length; i++) {
  447. cond = conditions[i];
  448. if (!cond) {
  449. continue;
  450. }
  451. formValue = formdata[cond[1]];
  452. if (formValue === undefined) {
  453. formValue = cond[4];
  454. }
  455. condTrue = operators[cond[2]](formValue, cond[3]);
  456. if (condTrue) {
  457. any = true;
  458. } else {
  459. all = false;
  460. }
  461. if (!conjunction && any) {
  462. break;
  463. }
  464. }
  465. updateUI(fields, conditionId, (all || (!conjunction && any)));
  466. };
  467. // register event listener
  468. $form.on('mwf-valuechange', function(e, input) {
  469. var cond, i;
  470. for (i = 0; i < conditions.length; i++) {
  471. cond = conditions[i];
  472. if (!cond) {
  473. continue;
  474. }
  475. if ($(input).attr("name") === conditions[i][1]) {
  476. checkCondition();
  477. }
  478. }
  479. });
  480. // check conditions initially
  481. checkCondition();
  482. if (plugin.settings.onConditionCreated !== undefined) {
  483. plugin.settings.onConditionCreated($form, conditionId, conjunction, conditions, fields);
  484. }
  485. }
  486. function createCalculatedValue(calcValueId, js, fields, formVariables, updateValue) {
  487. updateValue = (updateValue === undefined) ? plugin.settings.updateCalculatedValue : updateValue;
  488. var name,
  489. id = calcValueId,
  490. vars = formVariables,
  491. fct,
  492. calculate = function() {
  493. var state = $.extend({}, fields, formdata, vars),
  494. result = fct(state),
  495. $field = $form.find('[data-mwf-id="' + id + '"]');
  496. updateValue($form, id, result);
  497. $field.val(result).trigger('change');
  498. };
  499. try {
  500. eval('fct = function(s) {' + js + '}');
  501. } catch (ex) {
  502. $.logError(ex.message);
  503. }
  504. // register event listener
  505. $form.on('mwf-valuechange', function(e, input) {
  506. for (name in fields) {
  507. if (fields.hasOwnProperty(name) && $(input).attr('name') === name) {
  508. calculate();
  509. break;
  510. }
  511. }
  512. });
  513. }
  514. function recursiveEach(obj, callback, maxDeep) {
  515. var history = [], deep = -1, _recursiveEach;
  516. if (maxDeep === undefined) {
  517. maxDeep = Number.MAX_VALUE;
  518. }
  519. _recursiveEach = function(obj, callback) {
  520. var p, o, i, names = Object.getOwnPropertyNames(obj || {});
  521. deep++;
  522. for (i = 0; i < names.length; i++) {
  523. p = names[i];
  524. o = obj[p];
  525. if (typeof o === "object") {
  526. if (deep < maxDeep && $.inArray(o, history) === -1) {
  527. history.push(o);
  528. _recursiveEach(o, callback);
  529. }
  530. } else {
  531. if (callback.call(obj, obj, p, o) === false) {
  532. break;
  533. }
  534. }
  535. }
  536. deep--;
  537. };
  538. _recursiveEach(obj, callback);
  539. }
  540. /* condition operators
  541. ----------------------------------------------------------------------------------------------------------- */
  542. operators.contains = function(formValue, value) {
  543. if (formValue == null || value == null) {
  544. return false;
  545. }
  546. return formValue.indexOf(value) !== -1;
  547. };
  548. operators.containsnot = function(formValue, value) {
  549. if (formValue == null || value == null) {
  550. return false;
  551. }
  552. return formValue.indexOf(value) === -1;
  553. };
  554. operators.startswith = function(formValue, value) {
  555. return startsWith(formValue, value);
  556. };
  557. operators.endswith = function(formValue, value) {
  558. if (formValue == null || value == null) {
  559. return false;
  560. }
  561. return formValue.match(new RegExp(value + "$")) == value;
  562. };
  563. operators.equal = function(formValue, value) {
  564. if (formValue == null || value == null) {
  565. return formValue === value;
  566. }
  567. var f1 = parseFloat(formValue.replace(',', '.')),
  568. f2 = parseFloat(value.replace(',', '.'));
  569. return (!isNaN(f1) && !isNaN(f2) && f1 === f2) || (formValue === value);
  570. };
  571. operators.notequal = function(formValue, value) {
  572. if (formValue == null || value == null) {
  573. return formValue !== value;
  574. }
  575. var f1 = parseFloat(formValue.replace(',', '.')),
  576. f2 = parseFloat(value.replace(',', '.'));
  577. return (!isNaN(f1) && !isNaN(f2) && f1 !== f2) || (formValue !== value);
  578. };
  579. operators.empty = function(formValue, value) {
  580. return formValue == null || formValue === '';
  581. };
  582. operators.notempty = function(formValue, value) {
  583. return formValue != null && formValue !== '';
  584. };
  585. operators.emptylist = function(formValue, value) {
  586. return isEmptyList(formValue);
  587. };
  588. operators.notemptylist = function(formValue, value) {
  589. return !isEmptyList(formValue);
  590. };
  591. operators.selected = function(formValue, value) {
  592. if (formValue == null || value == null) {
  593. return false;
  594. }
  595. return $.inArray(value, formValue) !== -1;
  596. };
  597. operators.notselected = function(formValue, value) {
  598. if (formValue == null || value == null) {
  599. return false;
  600. }
  601. return $.inArray(value, formValue) === -1;
  602. };
  603. operators.minselected = function(formValue, value) {
  604. var l = (formValue == null) ? 0 : formValue.length;
  605. return l > Number(value);
  606. };
  607. operators.maxselected = function(formValue, value) {
  608. var l = (formValue == null) ? 0 : formValue.length;
  609. return l < Number(value);
  610. };
  611. operators.lessthan = function(formValue, value) {
  612. if (formValue == null || value == null) {
  613. return false;
  614. }
  615. var f1 = parseFloat(formValue.replace(',', '.')),
  616. f2 = parseFloat(value.replace(',', '.'));
  617. return (!isNaN(f1) && !isNaN(f2) && f1 < f2);
  618. };
  619. operators.greaterthan = function(formValue, value) {
  620. if (formValue == null || value == null) {
  621. return false;
  622. }
  623. var f1 = parseFloat(formValue.replace(',', '.')),
  624. f2 = parseFloat(value.replace(',', '.'));
  625. return (!isNaN(f1) && !isNaN(f2) && f1 > f2);
  626. };
  627. /* public methods
  628. ----------------------------------------------------------------------------------------------------------- */
  629. plugin.formSubmit = function(opt) {
  630. ajaxSubmit({
  631. url: targetUrl,
  632. id: formId,
  633. query: (opt.query !== undefined) ? opt.query : '',
  634. onSubmit: (opt.submit !== undefined) ? opt.submit : plugin.settings.onSubmit,
  635. onSuccess: (opt.success !== undefined) ? opt.success : plugin.settings.onSuccess,
  636. onError: (opt.error !== undefined) ? opt.error : plugin.settings.onAjaxError,
  637. onRedirect: (opt.redirect !== undefined) ? opt.redirect : plugin.settings.onRedirect
  638. });
  639. };
  640. plugin.gotoPage = function(opt) {
  641. ajaxSubmit({
  642. url: targetUrl,
  643. id: formId,
  644. query: opt.query.concat('&_target', opt.page, '=', opt.page),
  645. onSubmit: (opt.submit !== undefined) ? opt.submit : plugin.settings.onSubmit,
  646. onSuccess: (opt.success !== undefined) ? opt.success : plugin.settings.onSuccess,
  647. onError: (opt.error !== undefined) ? opt.error : plugin.settings.onAjaxError,
  648. onRedirect: (opt.redirect !== undefined) ? opt.redirect : plugin.settings.onRedirect
  649. });
  650. };
  651. plugin.init = function() {
  652. recursiveEach(settings, function(obj, property, value) {
  653. if (typeof value === 'string' && value.trim().substring(0, 8) === 'function') {
  654. try {
  655. eval('obj[property] =' + value);
  656. } catch (ex) {
  657. $.logError(ex.message);
  658. }
  659. }
  660. }, 1);
  661. $form.on('change', function(event) {
  662. valueChanged($(event.target));
  663. if (statisticsUrl !== null) {
  664. $.ajax({
  665. url: statisticsUrl,
  666. xhrFields: { withCredentials: true } // gfi added
  667. });
  668. statisticsUrl = null;
  669. }
  670. });
  671. if (targetUrl === undefined) {
  672. $.logError('No target URL specified.')
  673. }
  674. $.each($form.find('[data-mwf-submit]'), function() {
  675. var attr = $(this).data('mwf-submit'),
  676. query = (attr.query !== undefined) ? attr.query : '',
  677. onSuccess = (attr.success !== undefined) ? attr.success : plugin.settings.onSuccess,
  678. onRedirect = (attr.redirect !== undefined) ? attr.redirect : plugin.settings.onRedirect,
  679. onError = (attr.error !== undefined) ? attr.error : plugin.settings.onAjaxError,
  680. onSubmit = (attr.submit !== undefined) ? attr.submit : plugin.settings.onSubmit;
  681. switch (attr.type) {
  682. case 'next':
  683. case 'back':
  684. case 'goto':
  685. query = query.concat('&_target', attr.page, '=', attr.page);
  686. break;
  687. case 'cancel':
  688. case 'exit':
  689. case 'finish':
  690. query = query.concat('&_', attr.type, '=1');
  691. break;
  692. }
  693. $(this).on('click', function() {
  694. ajaxSubmit({
  695. url: targetUrl,
  696. id: formId,
  697. query: query,
  698. onSubmit: onSubmit,
  699. onSuccess: onSuccess,
  700. onError: onError,
  701. onRedirect: onRedirect
  702. });
  703. });
  704. });
  705. $.each($form.find('[data-mwf-bind]'), function() {
  706. var name = $(this).data('mwf-bind'),
  707. $elem = $(this);
  708. $form.on('mwf-valuechange', function(e, input) {
  709. var v, l;
  710. if ($(input).attr('name') === name) {
  711. v = formdata[name];
  712. l = valueLabel(name, v);
  713. plugin.settings.updateFormValue($form, $elem, name, l);
  714. triggerEvent(document, EVENTS.VALUE_CHANGED, {
  715. detail: {
  716. $form: $form,
  717. $elem: $elem,
  718. name: name,
  719. value: l
  720. }
  721. });
  722. return false;
  723. }
  724. });
  725. });
  726. $.each($form.find('[data-mwf-fileupload]'), function() {
  727. var $upload = $(this),
  728. attr = $(this).data('mwf-fileupload'),
  729. $dropzone = $upload.find('[data-mwf-dropzone]'),
  730. $files = $upload.find('[data-mwf-files]'),
  731. $fileInput = $upload.find('input:file'),
  732. multiple = $fileInput.attr('multiple') !== undefined,
  733. useXhr = (!multiple && $.support.xhrFileUpload) || $.support.xhrFormDataFileUpload,
  734. count = 0,
  735. pendingList = [],
  736. errorRows = [],
  737. enabled = true,
  738. $buttons = null;
  739. $upload.find('[data-mwf-file-upload-all]').on('click', function() {
  740. pendingList.forEach(function(data) {
  741. data.submit();
  742. });
  743. pendingList = [];
  744. });
  745. $upload.find('[data-mwf-file-delete-all]').on('click', function() {
  746. $files.find('[data-mwf-file-delete]').trigger('click');
  747. pendingList = [];
  748. });
  749. $upload.on('disable', function() {
  750. enabled = false;
  751. $upload.fileupload('disable');
  752. $upload.addClass('mwf-upload-disabled');
  753. $upload.find(':button').prop('disabled', true);
  754. $fileInput.prop('disabled', true);
  755. });
  756. $upload.on('enable', function() {
  757. enabled = true;
  758. $upload.fileupload('enable');
  759. $upload.removeClass('mwf-upload-disabled');
  760. $upload.find(':button').prop('disabled', false);
  761. $fileInput.prop('disabled', false);
  762. });
  763. $dropzone.on('dragover', function() {
  764. if (enabled) {
  765. $(this).addClass('mwf-upload-dragover');
  766. }
  767. });
  768. $dropzone.on('dragleave drop', function() {
  769. $(this).removeClass('mwf-upload-dragover');
  770. });
  771. $upload.fileupload({
  772. url: attr.url,
  773. paramName: attr.name,
  774. dataType: 'json',
  775. dropZone: $dropzone,
  776. fileInput: $fileInput,
  777. previewMaxWidth: attr.previewMaxWidth,
  778. previewMaxHeight: attr.previewMaxHeight,
  779. previewCrop: true,
  780. maxNumberOfFiles: 1,
  781. formData: {xhr: useXhr},
  782. add: function(e, data) {
  783. var $this = $upload;
  784. if (!enabled) {
  785. return false;
  786. }
  787. $.each(errorRows, function(index, $row) {
  788. $row.remove();
  789. });
  790. if (multiple || count === 0) {
  791. count++;
  792. } else {
  793. return false;
  794. }
  795. pendingList.push(data);
  796. data.process(function() {
  797. return $this.fileupload('process', data);
  798. }).always(function() {
  799. $.each(data.files, function(index, file) {
  800. var $row = plugin.settings.createUploadFileRow($form, attr, file);
  801. data.context = $row;
  802. $row.find('[data-mwf-file-upload]').data(data).on('click', function() {
  803. pendingList.splice($.inArray(data, pendingList), 1);
  804. data.submit();
  805. });
  806. $row.find('[data-mwf-file-delete]').data(data).on('click', function() {
  807. $row.remove();
  808. pendingList.splice($.inArray(data, pendingList), 1);
  809. count--;
  810. });
  811. $row.find('[data-mwf-file-preview]').append(file.preview);
  812. $files.append($row);
  813. });
  814. if (attr.autoUpload === true) {
  815. data.submit();
  816. }
  817. });
  818. },
  819. submit: function(e, data) {
  820. if ($buttons === null) {
  821. data.xhrFields= { withCredentials: true }; // gfi added
  822. $buttons = $form.find(':button').filter(':not(:disabled)');
  823. $buttons.prop('disabled', true);
  824. }
  825. },
  826. progress: function(e, data) {
  827. var progress = parseInt(data.loaded / data.total * 100, 10);
  828. if (data.context) {
  829. data.context.each(function() {
  830. data.context.find('[data-mwf-file-progress]').attr('aria-valuenow', progress).css('display', 'block').children().first().css('width', progress + '%').text(progress + '%');
  831. });
  832. }
  833. },
  834. done: function(e, data) {
  835. var files = (typeof data.result === 'string') ? JSON.parse(data.result).files : data.result.files;
  836. $.each(files, function(index, file) {
  837. var $row = plugin.settings.createDownloadFileRow($form, attr, file);
  838. if (data.context !== undefined) {
  839. data.context.replaceWith($row)
  840. } else {
  841. $files.append($row);
  842. }
  843. if (file.error === undefined) {
  844. $row.find('[data-mwf-file-delete]').on('click', function() {
  845. if (file.delete_url) {
  846. $.ajax({
  847. url: file.delete_url,
  848. xhrFields: { withCredentials: true } // gfi added
  849. });
  850. }
  851. $row.remove();
  852. pendingList.splice($.inArray(data, pendingList), 1);
  853. // update filenames
  854. if (filenames.hasOwnProperty(attr.name)) {
  855. filenames[attr.name].splice($.inArray(file.name, filenames[attr.name]), 1);
  856. $form.trigger("mwf-valuechange", data.fileInput);
  857. }
  858. count--;
  859. });
  860. // update filenames
  861. if (!filenames.hasOwnProperty(attr.name)) {
  862. filenames[attr.name] = [];
  863. }
  864. filenames[attr.name].push(file.name);
  865. $form.trigger("mwf-valuechange", data.fileInput);
  866. } else {
  867. $row.find('[data-mwf-file-delete]').on('click', function() {
  868. $row.remove();
  869. pendingList.splice($.inArray(data, pendingList), 1);
  870. });
  871. errorRows.push($row);
  872. count--;
  873. }
  874. });
  875. },
  876. fail: function(e, data) {
  877. $.each(data.files, function(index, file) {
  878. var $row = plugin.settings.createDownloadFileRow($form, attr, {
  879. name: file.name,
  880. size: file.size,
  881. error: attr.labels.error
  882. });
  883. $row.find('[data-mwf-file-delete]').data(data).on('click', function() {
  884. $row.remove();
  885. pendingList.splice($.inArray(data, pendingList), 1);
  886. });
  887. errorRows.push($row);
  888. count--;
  889. if (data.context !== undefined) {
  890. data.context.replaceWith($row)
  891. } else {
  892. $files.append($row);
  893. }
  894. });
  895. },
  896. always: function(e, data) {
  897. if ($buttons !== null && $upload.fileupload('active') === 1) {
  898. $buttons.prop('disabled', false);
  899. $buttons = null;
  900. }
  901. }
  902. });
  903. // preload existing files
  904. $.ajax({
  905. url: attr.url,
  906. dataType: "json",
  907. data: {_name: attr.name, _do: 'files'},
  908. xhrFields: { withCredentials: true } // gfi added
  909. }).done(function(result) {
  910. $upload.fileupload('option', 'done').call($upload, $.Event('done'), {result: result});
  911. count = result.files.length;
  912. });
  913. });
  914. $.each($form.find('[data-mwf-datasource]'), function() {
  915. var def = {
  916. params: {},
  917. data: {}
  918. },
  919. attr = $.extend(true, {}, def, $(this).data('mwf-datasource')),
  920. $elem = $(this);
  921. switch (attr.type) {
  922. case 'checkbox':
  923. case 'radio':
  924. ajaxFillSelection($elem, attr);
  925. $form.on('mwf-valuechange', function(e, input) {
  926. if ($.trim(attr.params.dependsOn)) {
  927. $.each(attr.params.dependsOn.split(','), function(i, v) {
  928. if ($(input).attr('name') === v) {
  929. ajaxFillSelection($elem, attr);
  930. return false;
  931. }
  932. });
  933. }
  934. });
  935. break;
  936. case 'selection':
  937. ajaxFillDropdown($elem, attr);
  938. $form.on('mwf-valuechange', function(e, input) {
  939. if ($.trim(attr.params.dependsOn)) {
  940. $.each(attr.params.dependsOn.split(','), function(i, v) {
  941. if ($(input).attr('name') === v) {
  942. ajaxFillDropdown($elem, attr);
  943. return false;
  944. }
  945. });
  946. }
  947. });
  948. break;
  949. case 'suggestion':
  950. ajaxAutocomplete($elem, attr);
  951. break;
  952. case 'hidden':
  953. ajaxFillHidden($elem, attr);
  954. $form.on('mwf-valuechange', function(e, input) {
  955. if ($.trim(attr.params.dependsOn)) {
  956. $.each(attr.params.dependsOn.split(','), function(i, v) {
  957. if ($(input).attr('name') === v) {
  958. ajaxFillHidden($elem, attr);
  959. return false;
  960. }
  961. });
  962. }
  963. });
  964. break;
  965. default:
  966. $.logError(attr.type === undefined ?
  967. 'Please specifiy the datasource type (checkbox, radio, selection or suggestion).' :
  968. 'Unknown datasource type "'.concat(attr.type, '".'));
  969. }
  970. });
  971. //gfi added (behebt Fehler bei dropdowns mit conditions die initial nicht ausgewertet waren):
  972. formdata = serializeForm($form);
  973. // gfi added end
  974. $.each(plugin.settings.conditions, function() {
  975. createCondition($(this).attr('id'), $(this).attr('conjunction'), $(this).attr('conditions'), $(this).attr('fields'));
  976. });
  977. $.each(plugin.settings.calculatedValues, function() {
  978. createCalculatedValue($(this).attr('id'), $(this).attr('js'), $(this).attr('fields'), $(this).attr('vars'));
  979. });
  980. plugin.settings.onInit($form);
  981. };
  982. plugin.init();
  983. }
  984. /* default plugin settings
  985. ----------------------------------------------------------------------------------------------------------- */
  986. globalSettings.def = {
  987. appendUrlVars: false,
  988. operations: {},
  989. conditions: [],
  990. calculatedValues: [],
  991. fileuploadOptions: {},
  992. onConditionTrue: undefined,
  993. onConditionFalse: undefined,
  994. statisticsUrl: null
  995. };
  996. globalSettings.def.operations['visible'] = function($form, field) {
  997. var $field = $form.find('[data-mwf-container="' + field.input + '"]');
  998. $field.removeAttr('disabled');
  999. $field.removeClass('mwf-hidden');
  1000. };
  1001. globalSettings.def.operations['hidden'] = function($form, field) {
  1002. var $field = $form.find('[data-mwf-container="' + field.input + '"]');
  1003. $field.attr("disabled", "true");
  1004. $field.addClass('mwf-hidden');
  1005. };
  1006. globalSettings.def.operations['writable'] = function($form, field) {
  1007. var $field = $form.find('[data-mwf-id="' + field.input + '"]');
  1008. $field.removeAttr('readonly');
  1009. };
  1010. globalSettings.def.operations['readonly'] = function($form, field) {
  1011. var $field = $form.find('[data-mwf-id="' + field.input + '"]');
  1012. $field.val(field.value);
  1013. $field.attr("readonly", "true");
  1014. };
  1015. globalSettings.def.operations['enabled'] = function($form, field) {
  1016. var $field = $form.find('[data-mwf-id="' + field.input + '"]');
  1017. $field.removeAttr('disabled');
  1018. $field.trigger('enable');
  1019. };
  1020. globalSettings.def.operations['disabled'] = function($form, field) {
  1021. var $field = $form.find('[data-mwf-id="' + field.input + '"]');
  1022. $field.attr("disabled", "true");
  1023. $field.trigger('disable');
  1024. };
  1025. globalSettings.def.operations['optional'] = function($form, field) {
  1026. var $label = $form.find('label[for="' + field.input + '"]');
  1027. $label.children('span.mwf-required').remove();
  1028. };
  1029. globalSettings.def.operations['mandatory'] = function($form, field) {
  1030. var $label = $form.find('label[for="' + field.input + '"]'),
  1031. $span = $('<span></span>').attr('class', 'mwf-required').text('*');
  1032. $label.children('span.mwf-required').remove();
  1033. $label.append($span);
  1034. };
  1035. globalSettings.def.createOption = function($form, entry, selected) {
  1036. var $option = $('<option></option>')
  1037. .attr('data-mwf-value', entry.k)
  1038. .attr('data-mwf-label', entry.v)
  1039. .attr('data-mwf-mutable', '')
  1040. .attr('value', JSON.stringify(entry))
  1041. .append(entry.v);
  1042. if (selected) {
  1043. $option.attr('selected', true);
  1044. }
  1045. return $option;
  1046. };
  1047. globalSettings.def.createRadio = function($form, name, entry, checked) {
  1048. var $span, $input, $label;
  1049. $span = $('<span></span>')
  1050. .attr('class', 'mwf-option')
  1051. .attr('data-mwf-mutable', '');
  1052. $input = $('<input/>')
  1053. .attr('type', 'radio')
  1054. .attr('id', entry.i)
  1055. .attr('data-mwf-id', entry.i)
  1056. .attr('data-mwf-value', entry.k)
  1057. .attr('data-mwf-label', entry.v)
  1058. .attr('value', JSON.stringify(entry))
  1059. .attr('name', name)
  1060. .attr('class', 'mwf-radio');
  1061. if (checked) {
  1062. $input.attr('checked', 'checked');
  1063. }
  1064. $label = $('<label></label>')
  1065. .attr('for', entry.i).append(entry.v);
  1066. $span.append($input);
  1067. $span.append(' ');
  1068. $span.append($label);
  1069. return $span;
  1070. };
  1071. globalSettings.def.createCheckBox = function($form, name, entry, checked) {
  1072. var $span, $input, $label;
  1073. $span = $('<span></span>')
  1074. .attr('class', 'mwf-option')
  1075. .attr('data-mwf-mutable', '');
  1076. $input = $('<input/>')
  1077. .attr('type', 'checkbox')
  1078. .attr('id', entry.i)
  1079. .attr('data-mwf-id', entry.i)
  1080. .attr('data-mwf-value', entry.k)
  1081. .attr('data-mwf-label', entry.v)
  1082. .attr('value', JSON.stringify(entry))
  1083. .attr('name', name)
  1084. .attr('class', 'mwf-checkbox');
  1085. if (checked) {
  1086. $input.attr('checked', 'checked');
  1087. }
  1088. $label = $('<label></label>')
  1089. .attr('for', entry.i).append(entry.v);
  1090. $span.append($input);
  1091. $span.append(' ');
  1092. $span.append($label);
  1093. return $span;
  1094. };
  1095. globalSettings.def.updateFormValue = function($form, $elem, name, v) {
  1096. $elem.html($.isArray(v) ? v.join(', ') : v);
  1097. };
  1098. globalSettings.def.createUploadFileRow = function($form, attr, file) {
  1099. var $row, $fileinfo, $meta, $preview, $ul, $name, $size, $buttons, $upload, $delete, $span, $progress, $error;
  1100. $row = $('<div/>').attr('data-mwf-file', '').attr('class', 'mwf-upload-row');
  1101. $fileinfo = $('<div/>').attr('class', 'mwf-upload-fileinfo');
  1102. $preview = $('<div/>').attr('data-mwf-file-preview', '').attr('class', 'mwf-upload-preview');
  1103. $meta = $('<div/>').attr('class', 'mwf-upload-metadata');
  1104. $ul = $('<ul/>');
  1105. $name = $('<li>').text(attr.labels.name + ': ' + file.name);
  1106. $size = $('<li>').text(attr.labels.size + ': ' + $.formatSize(file.size));
  1107. $buttons = $('<div/>').attr('class', ' mwf-upload-actions');
  1108. $upload = $('<button>').attr('data-mwf-file-upload', '').attr('class', 'mwf-upload-upload').text(attr.labels.upload);
  1109. $delete = $('<button>').attr('data-mwf-file-delete', '').attr('class', 'mwf-upload-delete').text(attr.labels.del);
  1110. $span = $('<span>').css('width', '0%');
  1111. $progress = $('<div/>').attr('data-mwf-file-progress', '').attr('class', 'mwf-upload-progressbar');
  1112. $error = $('<div/>').attr('data-mwf-file-error', '').attr('class', 'mwf-upload-error');
  1113. $buttons.append($delete);
  1114. if (attr.autoUpload === false) {
  1115. $buttons.append($upload);
  1116. }
  1117. $ul.append($name);
  1118. $ul.append($size);
  1119. $meta.append($ul);
  1120. $fileinfo.append($preview);
  1121. $fileinfo.append($meta);
  1122. $progress.append($span);
  1123. $row.append($fileinfo);
  1124. $row.append($buttons);
  1125. $row.append($error);
  1126. $row.append($progress);
  1127. return $row;
  1128. };
  1129. globalSettings.def.createDownloadFileRow = function($form, attr, file) {
  1130. var $row, $fileinfo, $meta, $preview, $image, $ul, $name, $size, $buttons, $delete, $span, $error;
  1131. $row = $('<div/>').attr('data-mwf-file', '').attr('class', 'mwf-upload-row');
  1132. $fileinfo = $('<div/>').attr('class', 'mwf-upload-fileinfo');
  1133. $preview = $('<div/>').attr('data-mwf-preview', '').attr('class', 'mwf-upload-preview');
  1134. $meta = $('<div/>').attr('class', 'mwf-upload-metadata');
  1135. $ul = $('<ul/>');
  1136. $name = $('<li>').text(attr.labels.name + ': ' + file.name);
  1137. $size = $('<li>').text(attr.labels.size + ': ' + $.formatSize(file.size));
  1138. $buttons = $('<div/>').attr('class', ' mwf-upload-actions');
  1139. $delete = $('<button>').attr('data-mwf-file-delete', '').attr('class', 'mwf-upload-delete').text(attr.labels.del);
  1140. $buttons.append($delete);
  1141. $ul.append($name);
  1142. $ul.append($size);
  1143. $meta.append($ul);
  1144. if (file.thumbnail_url) {
  1145. $image = $('<img/>').attr('src', file.thumbnail_url);
  1146. $preview.append($image);
  1147. }
  1148. $fileinfo.append($preview);
  1149. $fileinfo.append($meta);
  1150. $row.append($fileinfo);
  1151. $row.append($buttons);
  1152. if (file.error) {
  1153. $error = $('<div/>').attr('data-mwf-file-error', '').attr('class', 'mwf-upload-error');
  1154. $span = $('<span>').text(file.error);
  1155. $error.append($span);
  1156. $row.append($error);
  1157. }
  1158. return $row;
  1159. };
  1160. globalSettings.def.updateCalculatedValue = function($form, id, value) {
  1161. $form.find('[data-mwf-value="' + id + '"]').text(value).html();
  1162. };
  1163. globalSettings.def.onAjaxError = function(jqXHR, status, error) {
  1164. $.logError(jqXHR.responseText);
  1165. };
  1166. globalSettings.def.onSubmit = function($form, url, query) {
  1167. return true;
  1168. };
  1169. globalSettings.def.onConditionCreated = function($form, conditionId, conjunction, conditions, fields) {
  1170. // do nothing
  1171. };
  1172. globalSettings.def.onFillDropdown = function($form, $elem) {
  1173. // do nothing
  1174. };
  1175. globalSettings.def.onFillSelection = function($form, $elem) {
  1176. // do nothing
  1177. };
  1178. globalSettings.def.onInit = function($form) {
  1179. // do nothing
  1180. };
  1181. /* plugin related jQuery functions
  1182. --------------------------------------------------------------------------------------------------------------- */
  1183. $.fn.webforms = function(opt) {
  1184. var dataKey = 'webforms', $this = $(this), $form = $this, settings, id, s;
  1185. if ($this.data('mwf-form') === undefined) {
  1186. $form = $this.find('[data-mwf-form]');
  1187. }
  1188. if ($form.length === 0) {
  1189. return;
  1190. }
  1191. id = $form.dataWithDefault('mwf-id', $form.data('mwf-form'));
  1192. settings = $form.dataWithDefault('mwf-settings', {});
  1193. s = {
  1194. id: id,
  1195. type: 'GET',
  1196. appendUrlVars: false
  1197. };
  1198. $.extend(true, s, globalSettingsWithVariant(settings.variant), settings, opt);
  1199. if ($form .is('form') || $form .find('form').length > 0) {
  1200. return $form.each(function() {
  1201. var instance = $(this).data(dataKey);
  1202. if (instance && instance.dispose) {
  1203. instance.dispose();
  1204. }
  1205. instance = new Webforms($(this), s);
  1206. $(this).data(dataKey, instance);
  1207. });
  1208. } else {
  1209. s.selector = $this;
  1210. $.mwfAjaxReplace(s);
  1211. }
  1212. };
  1213. $.fn.webforms.settings = function(variant) {
  1214. if (variant === undefined) {
  1215. return globalSettings.def;
  1216. } else {
  1217. if (globalSettings[variant] === undefined) {
  1218. globalSettings[variant] = {};
  1219. }
  1220. return globalSettings[variant];
  1221. }
  1222. };
  1223. /* deprecated: Use $.fn.webforms.settings instead. */
  1224. $.fn.webforms.defaults = $.fn.webforms.settings;
  1225. /* general jQuery utility functions
  1226. --------------------------------------------------------------------------------------------------------------- */
  1227. $.fn.replaceWithPush = function(elem) {
  1228. var $elem = $(elem);
  1229. this.replaceWith($elem);
  1230. return $elem;
  1231. };
  1232. $.fn.dataWithDefault = function(key, def) {
  1233. var value = this.data(key);
  1234. return (value !== undefined) ? value : def;
  1235. };
  1236. if (typeof $.fn.serializeObject === 'undefined') {
  1237. $.fn.serializeObject = function() {
  1238. var o = {}, a = this.serializeArray();
  1239. $.each(a, function() {
  1240. if (o[this.name] !== undefined) {
  1241. if (!o[this.name].push) {
  1242. o[this.name] = [o[this.name]];
  1243. }
  1244. o[this.name].push(this.value || '');
  1245. } else {
  1246. o[this.name] = this.value || '';
  1247. }
  1248. });
  1249. return o;
  1250. };
  1251. }
  1252. if (typeof $.logError === 'undefined') {
  1253. $.extend({
  1254. logError: function(msg) {
  1255. try {
  1256. if (msg !== undefined && typeof window.console !== 'undefined') {
  1257. console.error(msg);
  1258. }
  1259. } catch (ex) {
  1260. }
  1261. }
  1262. });
  1263. }
  1264. $.extend({
  1265. mwfAjaxReplace: function(opt) {
  1266. var $dest = $(opt.selector), data = {}, optinId, s;
  1267. if ($dest.length > 0) {
  1268. optinId = $.getOptinIdFromHash(opt.id);
  1269. if (optinId !== null) {
  1270. data._optinId = optinId;
  1271. if (typeof history.replaceState !== 'undefined') {
  1272. history.replaceState({}, document.title, window.location.pathname);
  1273. } else {
  1274. window.location.hash = '';
  1275. }
  1276. // gfi modified
  1277. /*$('html, body').animate({
  1278. scrollTop: $dest.offset().top
  1279. });*/
  1280. }
  1281. s = {
  1282. url: null,
  1283. type: 'POST',
  1284. appendUrlVars: false
  1285. };
  1286. // Create the final settings object
  1287. $.extend(s, opt);
  1288. if (s.appendUrlVars) {
  1289. $.extend(data, $.getUrlVars(window.location.search));
  1290. delete data.view;
  1291. }
  1292. $.extend(data, $.getUrlVars(s.query), opt.data);
  1293. $.ajax({
  1294. url: s.url,
  1295. type: s.type,
  1296. data: data,
  1297. traditional: true,
  1298. cache: false,
  1299. xhrFields: { withCredentials: true } // gfi added
  1300. })
  1301. .done(function(data, textStatus, jqXHR) {
  1302. if (jqXHR && jqXHR.getResponseHeader("webforms_redirect")) {
  1303. location.assign(jqXHR.getResponseHeader("webforms_redirect"));
  1304. return;
  1305. }
  1306. $dest = $dest.replaceWithPush(data);
  1307. if (s.onSuccess !== undefined) {
  1308. s.onSuccess(data, textStatus, jqXHR);
  1309. }
  1310. triggerEvent(document, EVENTS.AJAX_FINISHED, {detail: {$dest: $dest}});
  1311. })
  1312. .fail(function(jqXHR, textStatus, errorThrown) {
  1313. if (s.onError !== undefined) {
  1314. s.onError(jqXHR, textStatus, errorThrown);
  1315. } else {
  1316. $.logError(jqXHR.responseText);
  1317. }
  1318. triggerEvent(document, EVENTS.AJAX_ERROR, {
  1319. detail: {
  1320. $dest: $dest,
  1321. jqXHR: jqXHR,
  1322. textStatus: textStatus,
  1323. errorThrown: errorThrown
  1324. }
  1325. });
  1326. })
  1327. }
  1328. },
  1329. getUrlVars: function(url) {
  1330. var params = {}, i, param, pos, key, value, length;
  1331. if (typeof url === "string" && url.length > 0) {
  1332. if (url[0] === '?') {
  1333. url = url.substring(1);
  1334. }
  1335. url = url.split('&');
  1336. for (i = 0, length = url.length; i < length; i++) {
  1337. if (!url[i] || 0 === url[i].length) {
  1338. continue;
  1339. }
  1340. param = url[i];
  1341. pos = param.indexOf('=');
  1342. if (pos >= 0) {
  1343. key = param.substr(0, pos);
  1344. value = param.substr(pos + 1);
  1345. } else {
  1346. key = param;
  1347. value = '';
  1348. }
  1349. value = decodeURIComponent(value);
  1350. if (params[key] === undefined) {
  1351. params[key] = value;
  1352. } else if (params[key] instanceof Array) {
  1353. params[key].push(value);
  1354. } else {
  1355. params[key] = [params[key], value];
  1356. }
  1357. }
  1358. }
  1359. return params;
  1360. },
  1361. getUrlVar: function(url, name) {
  1362. return $.getUrlVars(url)[name];
  1363. },
  1364. getOptinIdFromHash: function(id) {
  1365. // legacy hash = mwf:uuid
  1366. // new hash = mwf:formId:uuid
  1367. var hash = location.hash.replace('#', ''),
  1368. idx = hash.indexOf("mwf:");
  1369. if (idx !== -1) {
  1370. var elements = hash.split(":");
  1371. if (elements.length === 2 || elements[1] === String(id)) {
  1372. return hash.substring(idx + 4, hash.length);
  1373. }
  1374. }
  1375. return null;
  1376. },
  1377. formatSize: function(bytes) {
  1378. if (typeof bytes !== 'number') {
  1379. return '';
  1380. }
  1381. if (bytes >= 1000000000) {
  1382. return (bytes / 1000000000).toFixed(2) + ' GB';
  1383. }
  1384. if (bytes >= 1000000) {
  1385. return (bytes / 1000000).toFixed(2) + ' MB';
  1386. }
  1387. return (bytes / 1000).toFixed(2) + ' KB';
  1388. }
  1389. });
  1390. /* register event handler
  1391. --------------------------------------------------------------------------------------------------------------- */
  1392. $(document).ready(function() {
  1393. var $document = $(document);
  1394. var $cmCsrfToken = $('[data-mwf-csrf-token]');
  1395. if ($cmCsrfToken.length) {
  1396. $.ajaxSetup({
  1397. beforeSend: function (jqXHR) {
  1398. jqXHR.setRequestHeader('X-CSRFToken', $cmCsrfToken.attr('data-mwf-csrf-token'));
  1399. }
  1400. });
  1401. }
  1402. $document.on(EVENTS.AJAX_FINISHED, function(event) {
  1403. var $dest = event.originalEvent.detail.$dest;
  1404. $dest.webforms( {});
  1405. });
  1406. $('[data-mwf-form]').each(function() {
  1407. $(this).webforms({});
  1408. });
  1409. });
  1410. }));