PageSourceSearch

https://www.margaritaville.com/assets/356af372/form-operations.js

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

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.