PageSourceSearch

https://www.flyleafmusic.com/assets/38422b58/javascripts/form-operations.js

js flyleafmusic.com collected 2026-09-25 00:11:51 UTC 21,702 bytes, 612 lines download raw bytes

1/**
2 * Created by dmitry on 20.06.16.
3 */
4
5
6function validate(input) {
7    if (($(input).attr('class') !== undefined) && $(input).attr('class').indexOf('form-control') != -1) {
8
9        inputName = input.name;
10
11        var newKey = inputName.replace(/\[/g, '\\[').replace(/\]/g,'\\]');
12
13        $('#message_' + newKey).hide();
14        $('[name="' + newKey + '"]').attr('aria-invalid', 'false');
15
16        if (input.attributes.regexid !== undefined) {
17            try {
18                reg = eval("regexp_" + input.attributes.regexid.value);
19                if (reg.test(input.value))
20                    $(input).next().hide();
21                else
22                    $(input).next().show();
23            } catch (err) {
24            }
25        }
26    }
27
28    if ($('#g-recaptcha-response')[0] != undefined) {
29        var response = grecaptcha.getResponse();
30        if (response != "") {
31            if ($("input[id^='recaptcha-']")[0] != undefined) {
32                $($("input[id^='recaptcha-']")[0]).val(response);
33            }
34
35            $responseObject = $('#g-recaptcha-response').parent().parent().next();
36
37            if (!$responseObject.is('button')) {
38                $responseObject.hide();
39            }
40        }
41    }
42}
43
44function setItemListeners() {
45    $('.btn.btn-sm').each(function () {
46        if ($(this).children('i.fa').length > 0) {
47            if ($(this).children('i.fa')[0].className == 'fa fa-plus') {
48                $(this).unbind('click');
49                $(this).click(function () {
50                    $this      = $(this);
51                    var parent = $(this).parent().parent().parent();
52                    //parent.append(window['$htm_' + $this[0].id]); //old style
53                    $(window['$htm_' + $this[0].id]).insertAfter(parent);
54                    try {
55                        eval('init_' + $this[0].id + '();');
56                    } catch (err) {
57                    }
58                    setItemNumbers();
59                    setItemListeners();
60                    if (parent.next().children('div.row').length > 0)
61                        ($this).parent().children("div.btn-group.float-right").children('.btn.btn-primary.btn-sm').last().show();
62                });
63
64            } else if ($(this).children('i.fa')[0].className == 'fa fa-minus') {
65                $(this).unbind('click');
66                $(this).click(function () {
67                    $($(this).parent()[0]).remove();
68                });
69
70            } else if ($(this).children('i.fa')[0].className == 'fa fa-arrow-up') {
71                $(this).unbind('click');
72                $(this).click(function () {
73                    var currentObject = $(this).parent()[0];
74                    var nextObject    = currentObject.previousSibling;
75
76                    if ((nextObject === null) || ($(nextObject).prop('tagName') !== "DIV")) {
77                        nextObject = $(currentObject).prev()[0];
78                    }
79
80                    if (nextObject !== null) {
81                        if ($(currentObject).attr('class') === $(nextObject).attr('class'))
82                            $(currentObject).swapWith($(nextObject));
83                    }
84                });
85
86            } else if ($(this).children('i.fa')[0].className == 'fa fa-arrow-down') {
87                $(this).unbind('click');
88                $(this).click(function () {
89                    var currentObject = $(this).parent()[0];
90                    var nextObject    = currentObject.nextSibling;
91
92                    if ((nextObject === null) || ($(nextObject).prop('tagName') !== "DIV")) {
93                        nextObject = $(currentObject).next()[0];
94                    }
95
96                    if (nextObject !== null) {
97                        if ($(currentObject).attr('class') === $(nextObject).attr('class'))
98                            $(currentObject).swapWith($(nextObject));
99                    }
100                });
101            }
102        }
103    });
104}
105
106$.fn.swapWith = function (to) {
107    return this.each(function () {
108        var copy_to   = $(to).clone(true);
109        var copy_from = $(this).clone(true);
110        $(to).replaceWith(copy_from);
111        $(this).replaceWith(copy_to);
112
113		// Swap fields names and ids
114		var fieldPrefixArray = $(this).find('input')[0].id.split('_');
115		var fieldPrefixStr = fieldPrefixArray[0] + '_' + fieldPrefixArray[1] + '_';
116
117		var copyFromEls = copy_from.find('[id*="' + fieldPrefixStr + '"]');
118		var copyToEls = copy_to.find('[id*="' + fieldPrefixStr + '"]');
119
120		for (let i = 0; i < copyFromEls.length; i++) {
121			let name = copyFromEls[i].name;
122			let id = copyFromEls[i].id;
123
124			copyFromEls[i].name = copyToEls[i].name;
125			copyFromEls[i].id = copyToEls[i].id;
126
127			copyToEls[i].name = name;
128			copyToEls[i].id = id;
129		}
130    });
131};
132
133function setItemNumbers() {
134    $('[name*="itemNumber_"]').each(function () {
135        var $this = $(this),
136            nameAttr = $(this).attr('name');
137
138        for (var i = 0; i < $branchIds.length; i++) {
139            var regexp = new RegExp('{itemNumber_' + $branchIds[i] + '}'),
140                regexpGlobal = new RegExp('{itemNumber_' + $branchIds[i] + '}', 'g');
141
142            var index = $('.sub_' + $branchIds[i]).last().index();
143            if (index >= 1 && nameAttr && regexp.test(nameAttr)) {
144                testName = nameAttr.replace(regexpGlobal, index);
145
146                while ($('[name="' + testName + '"]').length) {
147                    index++;
148                    testName = name.replace(regexpGlobal, index);
149                    if (index >= 10000) {
150                        break;
151                    }
152                }
153
154                nameAttr = nameAttr.replace(regexpGlobal, index);
155                $this.attr('name', nameAttr);
156
157                if ($this.attr('ng-model') !== undefined) {
158                    $this.attr('ng-model', $this.attr('ng-model').replace(regexpGlobal, index));
159                }
160
161                if ($this.attr('regexid') !== undefined) {
162                    $this.attr('regexid', $this.attr('regexid').replace(regexpGlobal, index));
163                }
164
165                var msgDiv = $this.next();
166                if (msgDiv.length) {
167                    msgDiv.attr('id', msgDiv.attr('id').replace(regexpGlobal, index));
168                }
169            }
170        }
171    });
172}
173
174function processUserArrayKey(keyItem) {
175    var inputItem    = $(keyItem).parent().next().children('input')[0];
176    var inputName    = inputItem.id;
177    var inputNgModel = $(inputItem).attr('ng-model');
178    var postfix      = '[' + keyItem.value + ']';
179
180    if (!inputName.endsWith(postfix)) {
181        inputItem.name = inputName + postfix;
182        $(inputItem).attr({'ng-model': inputNgModel + '_' + keyItem.value});
183    }
184}
185
186/**
187 * Fixed recaptcha refreshing on ajax-forms
188 */
189function reloadRecaptcha() {
190    if (typeof grecaptcha !== "undefined") {
191        grecaptcha.reset();
192        grecaptcha.reset();
193    }
194
195    $('[id^="recaptcha-"]').each(function() {
196        $(this).removeAttr('value');
197    });
198}
199
200
201//------------------------------------------------------------
202//------------ Processing the response of from in "Custom AJAX: mode             [-azamat/istranger]
203
204function processCustomAjaxResponse(response) {
205    var isCorrectResponse = response && $.isPlainObject(response);
206
207    if (isCorrectResponse) {
208
209        var promiseQueue = $.Deferred(),
210            startPromise = promiseQueue,
211            commands     = response.commands || [];
212
213        // Preparing command queue
214        ConnectApp.fn.log('Started processing of AJAX form response. Preparing queue of ' + commands.length + ' commands.');
215
216        $.each(commands, function (index, commandObj) {
217            var commandName = commandObj.name,
218                commandData = commandObj.data,
219                handler     = _getHandler(commandName);
220
221
222            if (handler) {
223
224                // Next handler will execute only after competes previous handler. Additionally any handler can return promise for async operations.
225                // Promise chains see here: http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/
226                // Test example see here: https://jsfiddle.net/IStranger/9k1Lb636/
227                promiseQueue = promiseQueue.then(function () {
228                    var result = handler(commandData);
229
230                    ConnectApp.fn.log('Executed command "' + commandName + '" with data ', commandData, ' with handler = ', (handler ? ('ConnectApp.forms.handlers.' + commandName) : null), 'handler result = ', result);
231
232                    return $.when(result);  // Promise normalization::  Any type will be converted to $.Deferred(). Non-deferred objects/types will be converted to resolved promise. Deferreds (for example from $.ajax) will be converted to the promise with the same state.
233
234                }, function () {
235
236                    throw new Error('Aborted promise queue!');
237
238                })
239
240            }
241        });
242
243
244        // Starting command queue
245        ConnectApp.fn.log('Start queue.');
246        startPromise.resolve();
247
248        promiseQueue.then(function () {
249            ConnectApp.fn.log('Queue successfully complete.');
250        });
251
252
253    } else {
254        throw new Error('method processCustomAjaxResponse() can\'t process incorrect AJAX response = ', response);
255    }
256
257
258    // ---------------------------------------
259    /**
260     * Returns handler.
261     * @param {String} commandName
262     * @return {null}
263     * @private
264     */
265    function _getHandler(commandName) {
266        var handler;
267
268        if (ConnectApp && ConnectApp.forms) {
269
270            handler = ConnectApp.forms.handlers
271                ? ConnectApp.forms.handlers[commandName]
272                : null;
273
274            return handler && $.isFunction(handler)
275                ? handler
276                : null;
277
278        } else {
279            throw new Error('Not available AJAX form hadlers');
280        }
281    }
282}
283
284
285// -----------------------------------------------------------------------------
286// ---------------------------------- AJAX Form Handlers------------------------        [-azamat/istranger]
287
288(function () {
289
290    'use strict';
291
292
293    if (ConnectApp && ConnectApp.forms) {
294
295        ConnectApp.forms.handlers = ConnectApp.forms.handlers || {};
296
297        // ------------------------------------------------
298        // ------ Defining list of command handlers. TODO probably these handlers may be defined on server side (like yii Validators)
299
300
301        // redirectTo
302        ConnectApp.forms.handlers.redirectTo = function (data) {
303
304            var url = _getRequiredParam(data, 'url');
305
306            ConnectApp.fn.redirectTo(url);
307        };
308
309
310        // showNotification
311        ConnectApp.forms.handlers.showNotification = function (data) {
312            var msg     = _getRequiredParam(data, 'msg'),
313                msgType = _getOptionalParam(data, 'msgType', ConnectApp.ui.NOTY_TYPE_INFORMATION);
314
315            ConnectApp.ui.showNotification(msg, msgType);
316        };
317
318
319        // executeJsCode
320        ConnectApp.forms.handlers.executeJsCode = function (data) {
321            var code = _getRequiredParam(data, 'code');
322
323            ConnectApp.utils.executeJsCode(code);
324        };
325
326
327        // subscribeToConnectMail
328        ConnectApp.forms.handlers.subscribeToConnectMail = function (data) {
329            var $email, $lastName, $firstName, $listSelector, $form, userData, email, mailingListTokens, mailingListTokensFromForm, promises, resultPromise,
330                module                                 = mailCheckerApp.validationModule,
331                apiUrl                                 = _getRequiredParam(data, 'apiUrl'),
332                CONNECT_MAIL_INPUT_ROLE_EMAIL          = _getRequiredParam(data, 'CONNECT_MAIL_INPUT_ROLE_EMAIL'),
333                CONNECT_MAIL_INPUT_ROLE_FIRST_NAME     = _getRequiredParam(data, 'CONNECT_MAIL_INPUT_ROLE_FIRST_NAME'),
334                CONNECT_MAIL_INPUT_ROLE_LAST_NAME      = _getRequiredParam(data, 'CONNECT_MAIL_INPUT_ROLE_LAST_NAME'),
335                CONNECT_MAIL_INPUT_ROLE_CHECKBOX_ALLOW = _getRequiredParam(data, 'CONNECT_MAIL_INPUT_ROLE_CHECKBOX_ALLOW'),
336                CONNECT_MAIL_INPUT_ROLE_LIST_SELECTOR  = _getRequiredParam(data, 'CONNECT_MAIL_INPUT_ROLE_LIST_SELECTOR');
337
338            promises = [];
339
340            // For correct working of validation module.
341            module.setApiDomain(apiUrl);
342
343            // Defining the ConnectMail fields (few may be undefined)
344            $email        = $('[data-connect-mail-role="' + CONNECT_MAIL_INPUT_ROLE_EMAIL + '"]');
345            $lastName     = $('[data-connect-mail-role="' + CONNECT_MAIL_INPUT_ROLE_FIRST_NAME + '"]');
346            $firstName    = $('[data-connect-mail-role="' + CONNECT_MAIL_INPUT_ROLE_LAST_NAME + '"]');
347            $listSelector = $('[data-connect-mail-role="' + CONNECT_MAIL_INPUT_ROLE_LIST_SELECTOR + '"]');
348            $form         = $email.parents('form');
349
350            // If subscription enabled on form.
351            if ($email.size()) {
352
353                // Preparing data for validation and subscription
354                email    = $email.val();
355                userData = {
356                    firstName: $firstName.val(),
357                    lastName : $lastName.val()
358                };
359
360                // Mailing Lists (assigned via FormConstructor + defined on form)
361                mailingListTokens = $email.attr('data-connect-mail-tokens');
362                mailingListTokens = mailingListTokens
363                    ? JSON.parse(mailingListTokens)
364                    : null;
365                mailingListTokens = mailingListTokens || [];
366
367                mailingListTokensFromForm = $listSelector.val();
368                mailingListTokensFromForm = $.isArray(mailingListTokensFromForm)
369                    ? mailingListTokensFromForm
370                    : [];
371
372                mailingListTokens = mailingListTokens.concat(mailingListTokensFromForm);
373
374
375                // Subscription will performed only if defined mailing lists
376                if (mailingListTokens.length) {
377
378                    $.each(mailingListTokens, function (index, mailingListToken) {
379                        var promise;
380
381                        // Validation and subscription
382                        promise = _validateAndSubscribe(email, mailingListToken, userData, function (success, msg) {
383                            ConnectApp.fn.log('_validateAndSubscribe ::>> success = ', success, ' msg = ', msg);
384                        });
385
386                        promises.push(promise);
387                    });
388
389                }
390            }
391
392            // Summary promise will be resolved after all subscriptions
393            resultPromise = $.when.apply($, promises);
394
395
396            // If queue is not completed, show AJAX loader
397            if (resultPromise.state() === 'pending') {
398                ConnectApp.ui.addAjaxLoader($form, resultPromise);
399            }
400
401            return resultPromise;
402        };
403
404
405        // commandForBCOnly
406        ConnectApp.forms.handlers.commandForBCOnly = function commandForBCOnly(data) {
407
408            ConnectApp.fn.log('Command handler "commandForBCOnly" do nothing. Handler data = ', data);
409        };
410
411    } else {
412        throw new Error('Not available "ConnectApp.forms". Form JS handlers didn\'t initialize.');
413    }
414
415
416    //------------------------------------------------------------
417    //------------------- Private module functions                              [-azamat/istranger]
418
419    /**
420     * Returns required param value. If param not found, will be thrown exception.
421     *
422     * @param {Object} data         Command data (params list).
423     * @param {String} paramName    Param name.
424     * @return {*}
425     * @private
426     */
427    function _getRequiredParam(data, paramName) {
428
429        if (data && data[paramName]) {
430            return data[paramName];
431        } else {
432            throw new Error('Command: Missing required param "' + paramName + '".');
433        }
434    }
435
436    /**
437     * Returns required param value. If param not found, will be returned specified default value.
438     *
439     * @param {Object} data                 Command data (params list).
440     * @param {String} paramName            Param name.
441     * @param {*}      [defaultValue=null]  Default value that will be returned when paramName not found.
442     * @return {*}
443     * @private
444     */
445    function _getOptionalParam(data, paramName, defaultValue) {
446        defaultValue = (defaultValue === undefined) ? null : defaultValue;
447
448        if (data && data[paramName]) {
449            return data[paramName];
450        } else {
451            return defaultValue;
452        }
453    }
454
455
456    //------------ Initialization of ConnectMail Integration                [-azamat/istranger]
457    /**
458     * Validates and subscribes specified email to mailing list.
459     * @param {String}   email
460     * @param {String}   mailingListToken       API token for API access and mailing list subscription.
461     * @param {Object}   userData               Additional user data like firstName, lastName
462     * @param {Function} [callback]
463     * @private
464     */
465    function _validateAndSubscribe(email, mailingListToken, userData, callback) {
466
467        var xhrValidate,
468            xhrSubscribe = $.Deferred();
469
470        xhrValidate = _validateEmail(email, userData, mailingListToken, true, function (isValid, msg) {
471
472            if (isValid) {
473
474                _subscribeToMailingList(email, mailingListToken, function (success, msg) {
475
476                    if ($.isFunction(callback)) {
477                        callback(success, msg);
478                    }
479
480                }).then(
481                    function () {
482                        xhrSubscribe.resolve();
483                    },
484                    function () {
485                        xhrSubscribe.reject();
486                    }
487                );
488
489            } else {
490
491                if ($.isFunction(callback)) {
492                    callback(false, msg);
493                }
494
495                xhrSubscribe = xhrSubscribe.resolve();
496
497            }
498        });
499
500        return $.when(xhrValidate, xhrSubscribe);
501    }
502
503    /**
504     * Subscribes email from specified email input.
505     *
506     * @param {String}   email
507     * @param {Object}   userData               Additional user data like firstName, lastName
508     * @param {String}   apiAccessToken         API Token that opens API access.
509     * @param {Boolean}  forceSubscription      Force subscription?
510     * @param {Function} [callback]             Success callback
511     *
512     * @return {jqXHR}                          Deferred object of AJAX request
513     *
514     * @private
515     */
516    function _validateEmail(email, userData, apiAccessToken, forceSubscription, callback) {
517
518        userData          = userData || {};
519        forceSubscription = forceSubscription || false;
520
521        var ajaxOptions,
522            module = mailCheckerApp.validationModule;
523
524        // Preparing ajax request options
525        ajaxOptions = {
526            type: 'post',
527            url : module.getApiDomain() + module.URL_CHECK_EMAIL_STATUS,
528            data: {
529                token            : apiAccessToken,
530                email            : email,
531                firstName        : userData.firstName,
532                lastName         : userData.lastName,
533                forceSubscription: forceSubscription ? 1 : 0
534            },
535
536            success: function (response) {
537                if (!response || response.msg === undefined) {
538                    _throwException('Incorrect format of response of AJAX request at email validation');
539                }
540
541                if ($.isFunction(callback)) {
542                    callback.apply(this, [response.isValid, response.msg]);
543                }
544            },
545
546            error: function () {
547                console.log(['Error at email subscribing: ', arguments], true);
548                _throwException('Error at email subscribing using AJAX');
549            }
550        };
551
552        // Performing ajax request
553        return $.ajax(ajaxOptions);
554    }
555
556    /**
557     * Subscribes email from specified email input.
558     *
559     * @param {String}   email
560     * @param {String}   mailingListToken       API token for API access and mailing list subscription.
561     * @param {Function} [onSuccess]
562     *
563     * @return {jqXHR}                          Deferred object of AJAX request
564     *
565     * @private
566     */
567    function _subscribeToMailingList(email, mailingListToken, onSuccess) {
568
569        var ajaxOptions,
570            module = mailCheckerApp.validationModule;
571
572        // Preparing ajax request options
573        ajaxOptions = {
574            type: 'post',
575            url : module.getApiDomain() + module.URL_SUBSCRIBE_EMAIL_TO_LIST,
576            data: {
577                token: mailingListToken,
578                email: email
579            },
580
581            success: function (response) {
582                if (!response || response.msg === undefined) {
583                    _throwException('Incorrect format of response of AJAX request at email subscribing');
584                }
585
586                if ($.isFunction(onSuccess)) {
587                    onSuccess.apply(this, [response.success, response.msg]);
588                }
589            },
590
591            error: function () {
592                console.log(['Error at email subscribing: ', arguments], true);
593                _throwException('Error at email subscribing using AJAX');
594            }
595        };
596
597
598        // Performing ajax request
599        return $.ajax(ajaxOptions);
600    }
601
602    /**
603     * Throws exception.
604     *
605     * @param {String} msg
606     * @private
607     */
608    function _throwException(msg) {
609        throw new Error(msg);
610    }
611
612}());

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.