PageSourceSearch

https://ez-ocm.ru/DESIGN/SITE/js/modal/FormTender.js

js ez-ocm.ru collected 2026-09-30 16:47:03 UTC 16,487 bytes, 482 lines download raw bytes

1function FormTender() {
2
3    var self = this;
4
5    /**
6     * Префикс для формы
7     * @type {string}
8     */
9    this.form = '.js-form';
10
11    /**
12     * Постфикс для идентификации формы
13     * @type {string}
14     */
15    this.formPostFix = '-order';
16
17    /**
18     * Массив с названиями input'ов
19     * @type {Array}
20     */
21    this.inputsName = ['name', 'secondName', 'phone', 'email', 'product', 'comment'];
22
23    /**
24     * Массив с названиями textarea'ов
25     * @type {Array}
26     */
27    this.textareasName = [];
28
29    /**
30     * Поле input с телефоном на которое будет накладываться маска
31     * @type {string}
32     */
33    this.inputName = 'phone';
34
35    /**
36     * Маска для телефона
37     * @type {string}
38     */
39    this.phoneMask = '+7 (999) 999-99-99';
40
41    /**
42     * Сообщение на случай, если поле не заполнено (ошибка первого уровня)
43     * @type {string}
44     */
45    this.errorLvl1 = "<span class='errorText'>Поле не заполнено</span>";
46
47    /**
48     * Отображение ошибки второго уровня для input'ов
49     * (последовательность ошибок должна быть такая же как у input'ов)
50     * @type {Array}
51     */
52    this.errorLvl2 = [
53        "<span class='errorText'>Имя должно содержать только буквы</span>",
54        "",
55        "<span class='errorText'>Поле должно содержать только цифры</span>",
56        "<span class='errorText'>Электронный адрес введен не верно</span>"
57    ];
58
59    /**
60     * Надпись отображается при успешной отправки формы
61     * @type {string}
62     */
63    this.theEnd = "<span class='succes'>Ваша заявка успешно зарегистрирована! Ваше конкурсное предложение Вы можете направить уполномоченному лицу АО «ЕЗ ОЦМ», указанному в описании тендера.</span>";
64
65    /**
66     * Класс на который повешены текстовые ошибки
67     * @type {string}
68     */
69    this.errorText = 'errorText';
70
71    /**
72     * Класс на который повешены ошибки на input и textarea
73     * @type {string}
74     */
75    this.error = 'error';
76
77    /**
78     * Настройка true, если есть загрузка файла
79     * @type {boolean}
80     */
81    this.withFile = false;
82
83    /**
84     * Объект загрузки
85     */
86    this.uploader;
87
88    /**
89     * Проверка, что есть уже загруженный файл
90     * @type {boolean}
91     */
92    this.fileFirst = false;
93
94    /**
95     * Уникальный идентификатор объекта загрузки
96     * @type {string}
97     */
98    this.idObjectUpload = 'modal';
99
100    /**
101     * Элемент к которому прикрепляется загрузка файла
102     * @type {string}
103     */
104    this.uploadItem = "input[name='files']";
105
106    /**
107     * Список файлов, которые уже прикреплены
108     * @type {string}
109     */
110    this.uploadList = '.js-fileUploadList';
111
112    /**
113     * Область которая отвечает за файлы
114     * @type {string}
115     */
116    this.fileUploadArea = '.js-fileUploadArea';
117
118    /**
119     * Класс для удаления файла
120     * @type {string}
121     */
122    this.deleteFile = '.js-deleteFile';
123
124    /**
125     * Инициализация всех событий
126     */
127    this.init = function () {
128
129        this.initForm();
130        this.initFormEvent();
131        this.initFocusEvent();
132    };
133
134    this.time = function () {
135        return parseInt(new Date().getTime()/1000);
136    };
137
138    this.random = function () {
139        return Math.random();
140    };
141
142    this.initForm = function () {
143
144        $('input[name="' + this.inputName + '"]').mask(this.phoneMask);
145
146        if (self.withFile == true) {
147            self.intUploader();
148
149            /**
150             * Событие на удаление файла
151             */
152            $(document).on('click', this.deleteFile, function(e){
153                e.preventDefault();
154
155                self.deleteFileAction();
156            });
157        }
158    };
159
160    /**
161     * Инициализация загрузчика
162     */
163    this.intUploader = function () {
164
165        var uniqueId = 'browse' + this.time() + this.random();
166
167        // Назначаем id элементу из формы
168        $(this.uploadItem).attr('id', uniqueId);
169
170        // Потом дергаем этот элемент из DOM
171        var elem1 = document.getElementById(uniqueId);
172
173        var fileUrl = $(this.form + this.formPostFix).attr('data-file');
174
175        // Подтыкаем
176
177        var id = this.idObjectUpload;
178
179        this.uploader = new plupload.Uploader({
180            multipart_params: {id : id},
181            browse_button:   elem1,
182            url:             fileUrl,
183            multi_selection: false,
184            filters: {
185                max_file_size: '5mb',
186                mime_types: [
187                    {title: "Image files", extensions: "jpg,gif,png,jpeg,doc,docx,xls,xlsx"}
188                ]
189            }
190        });
191
192        this.uploader.init();
193
194        /**
195         * Добавление файла
196         */
197        this.uploader.bind('FilesAdded', function(up, files) {
198
199            if (self.fileFirst == false) {
200
201                var html = '';
202
203                plupload.each(files, function(file) {
204                    html += '<span data-id="' + file.id + '">' + file.name + ' <a class="js-deleteFile" href="#">&times;</a></span>';
205                });
206
207                $(self.uploadList).append(html);
208                self.uploader.start();
209                self.fileFirst = true;
210            } else {
211                var count = self.uploader.files.length;
212                var tmp = self.uploader.files;
213
214                for (var i = 0; i < count; i++) {
215                    if (i != 0) {
216                        self.uploader.removeFile(tmp[i]);
217                    }
218                }
219
220                alert('Нельзя прикрепить к заявке более одного файла');
221            }
222        });
223
224        /**
225         * Процесс загрузки
226         */
227        this.uploader.bind('UploadProgress', function(up, file) {
228
229            if ($(self.fileUploadArea).hasClass(self.error)) {
230                $(self.fileUploadArea).removeClass(self.error);
231                $(self.fileUploadArea).next().remove();
232            }
233
234            $(self.form + self.formPostFix).addClass('loading');
235        });
236
237        /**
238         * Файл загружен
239         */
240        this.uploader.bind('FileUploaded', function(up, file, info) {
241            // Файл загружен
242            var response = JSON.parse(info.response);
243            $(self.form + self.formPostFix).removeClass('loading');
244
245            if (response.data.error == 'maxSizeFile') {
246                self.resetErrorClass($(self.fileUploadArea));
247
248                $(self.uploadList).empty();
249                self.uploader.removeFile(self.uploader.files[0]);
250                $(self.form + self.formPostFix + " " + self.fileUploadArea).after("<span class='errorText'>Файл слишком большой (файл не должен быть больше 5 Мб)</span>");
251            }
252
253            if (response.data.error == 'noAvaliable') {
254                self.resetErrorClass($(self.fileUploadArea));
255
256                $(self.uploadList).empty();
257                self.uploader.removeFile(self.uploader.files[0]);
258                $(self.form + self.formPostFix + " " + self.fileUploadArea).after("<span class='errorText'>Файл имеет не допустимое расширение (допустимы расширения: jpg,gif,png,jpeg,doc,docx,xls,xlsx)</span>");
259            }
260        });
261
262        this.uploader.bind('Error', function(up, err) {
263            if (err.code == -601) {
264                self.resetErrorClass($(self.fileUploadArea));
265
266                $(self.form + self.formPostFix + " " + self.fileUploadArea).addClass(self.error);
267                $(self.uploadList).empty();
268                $(self.form + self.formPostFix + " " + self.fileUploadArea).after("<span class='errorText'>Файл такого расширения или такого размера загружать нельзя</span>");
269            }
270        });
271    };
272
273    /**
274     * Удаление файла на сервере
275     * @returns {boolean}
276     */
277    this.deleteFileAction = function () {
278
279        var deleteFileUrl = $(this.form + this.formPostFix).attr('data-deleteFile');
280
281        if (deleteFileUrl == undefined) {
282            return false;
283        }
284
285        if (self.fileFirst == true) {
286
287            $.ajax({
288                type: "POST",
289                url: deleteFileUrl,
290                success: function(response)
291                {
292                    if (response.status.code != 1001) {
293                        if (response.data.succes === 'Ok') {
294                            if (self.fileFirst == true) {
295
296                                $(self.uploadList).empty();
297
298                                self.uploader.removeFile(self.uploader.files[0]);
299                                self.fileFirst = false;
300                            }
301                        }
302                    }
303                }
304            }); // $.ajax
305        }
306    };
307
308    /**
309     * Удаление ошибок на input'ах
310     */
311    this.resetInputError = function () {
312
313        this.inputsName.forEach(function(item, i) {
314
315            var $object = $(self.form + self.formPostFix + " input[name='" + item + "']");
316            self.resetErrorClass($object);
317        });
318
319        if (self.withFile == true) {
320
321            var $object = $(self.fileUploadArea);
322            self.resetErrorClass($object);
323
324            self.deleteFileAction();
325        }
326    };
327
328    /**
329     * Удаление ошибок на input'ах
330     */
331    this.resetTextAreaError = function () {
332
333        this.textareasName.forEach(function(item, i) {
334
335            var $object = $(self.form + self.formPostFix + " textarea[name='" + item + "']");
336
337            self.resetErrorClass($object);
338        });
339    };
340
341    /**
342     * Удаление подсвечивания элемента и подписи под ним
343     * @param $object
344     */
345    this.resetErrorClass = function ($object) {
346
347        if ($object.hasClass('error')) {
348
349            $object.removeClass('error');
350            $object.next().remove();
351        }
352    };
353
354    /**
355     * Обработка события отправки формы
356     */
357    this.initFormEvent = function () {
358
359        $(document).on('submit', self.form + self.formPostFix, function(e){
360            e.stopPropagation();
361            e.preventDefault();
362
363            var vars = $(this).serialize();
364            var furl = $(this).attr('action');
365			
366			//if (typeof yaCounter46377009 != 'undefined') {
367			
368						yaCounter46377009.reachGoal('submit_form_tender');
369					
370				//	}
371			
372            $.ajax({
373                type: "POST",
374                url: furl,
375                data: vars,
376                success: function(response)
377                {
378                    if (response.status.code != 1001) {
379
380                        if (response.data.succes === 'Ok') {
381
382                            self.theEndText(response.data);
383                        }
384                    } else {
385
386                        if (response.data.honeyPot != undefined) {
387                            return;
388                        }
389
390                        // снять везде класс ошибки
391                        self.inputsName.forEach(function(item, i) {
392                            $(self.form + self.formPostFix + " input[name='" + item + "']").removeClass(self.error);
393                        });
394
395                        self.textareasName.forEach(function(item, i) {
396                            $(self.form + self.formPostFix + " textarea[name='" + item + "']").removeClass(self.error);
397                        });
398
399                        $(self.form + self.formPostFix + " span[class='" + self.errorText + "']").remove();
400
401                        // Проверка на ошибки первого уровня у input'ов
402                        self.inputsName.forEach(function(item, i) {
403                            $(self.form + self.formPostFix + " input[name='" + item + "']").removeClass(self.error);
404
405                            if (response.data.error[item] != 'undefined') {
406
407                                if (response.data.error[item] == item + '!') {
408
409                                    $(self.form + self.formPostFix + " input[name='" + item + "']").addClass(self.error);
410                                    $(self.form + self.formPostFix + " input[name='" + item + "']").after(self.errorLvl1);
411                                }
412
413                                if (response.data.error[item] == item + '!!') {
414
415                                    $(self.form + self.formPostFix + " input[name='" + item + "']").addClass(self.error);
416                                    $(self.form + self.formPostFix + " input[name='" + item + "']").after(self.errorLvl2[i]);
417                                }
418                            }
419                        });
420
421                        // Проверка на ошибки первого уровня у textarea
422                        self.textareasName.forEach(function(item, i) {
423
424                            $(self.form + self.formPostFix + " textarea[name='" + item + "']").removeClass(self.error);
425
426                            if (response.data.error[item] != 'undefined') {
427
428                                if (response.data.error[item] == item + '!') {
429
430                                    $(self.form + self.formPostFix + " textarea[name='" + item + "']").addClass(self.error);
431                                    $(self.form + self.formPostFix + " textarea[name='" + item + "']").after(self.errorLvl1);
432                                }
433
434                                if (response.data.error[item] == item + '!!') {
435
436                                    $(self.form + self.formPostFix + " textarea[name='" + item + "']").addClass(self.error);
437                                    $(self.form + self.formPostFix + " textarea[name='" + item + "']").after(self.errorLvl2[i]);
438                                }
439                            }
440                        });
441                    }
442                }
443            }); // $.ajax
444        });
445    };
446
447    /**
448     * Кастомные действия при успешной отправки формы
449     */
450    this.theEndText = function (data) {
451
452        $(self.form + self.formPostFix).empty();
453        $(self.form + self.formPostFix).append(self.theEnd);
454    };
455
456    this.initFocusEvent = function () {
457
458        this.inputsName.forEach(function(item, i) {
459
460            $(document).on('focus', self.form + self.formPostFix + " input[name='" + item + "']", function(e) {
461
462                if ($(this).hasClass('error')) {
463
464                    $(this).removeClass('error');
465                    $(this).next().remove();
466                }
467            });
468        });
469
470        this.textareasName.forEach(function(item, i) {
471
472            $(document).on('focus', self.form + self.formPostFix + " textarea[name='" + item + "']", function(e) {
473
474                if ($(this).hasClass('error')) {
475
476                    $(this).removeClass('error');
477                    $(this).next().remove();
478                }
479            });
480        });
481    };
482}

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.