PageSourceSearch

https://astrology.pro/js/common.js?216

js astrology.pro collected 2026-10-01 13:52:40 UTC 307,357 bytes, 8,503 lines download raw bytes

1$.arcticmodal('setDefault', {
2    modal: false,
3    closeOnEsc: false,
4    openEffect: {
5        type: 'none'
6    },
7    closeEffect: {
8        type: 'none'
9    },
10    fixed: '.header.is-fixed',
11    closeOnOverlayClick: true,
12    afterClose: function(data, el){
13        $(el).find('div.error').remove();
14    }
15});
16
17$.fn.chooseRegion = function(){
18    this.each(function(){
19        var $input = $(this),
20            input_name = $input.attr("name"),
21            regionId = $input.data('region-id'),
22            request,
23            prefix,
24            regions = [];
25
26
27        if($input.data('initialized')) return;
28        $input.data('initialized', true);
29
30        var $holder = $('<div id="select-'+input_name+'-holder" class="select-region-holder">'),
31            $inputId = $('<input type="hidden" name="'+input_name+'_id">'),
32            $choosed = $('<div id="select-'+input_name+'-choosed" class="select-region-choosed">'),
33            $button_clear_region = $('<a href="#" class="button_clear_region" id="button_clear_'+input_name+'"></a>');
34
35        if(regionId){
36            $inputId.val(regionId);
37        }
38
39        $input
40            .closest('.form-input-field').append($holder)
41            .closest('.form-input').append($inputId).append($choosed);
42
43        $holder.on('mousedown', '.select-region-item', function(e){
44            e.preventDefault();
45            choose($(this));
46        });
47
48        $input.on('blur', function(){
49            hide();
50            choosed();
51        });
52        $input.on('focus', function(){
53            $input.triggerHandler('refresh');
54        });
55
56
57        function choose($item){
58            $input.data('region-id', $item.data('region-id')).data('region-title', $item.data('region-title') + ' (' + $item.data('region-parent') + ')');
59            $inputId.val($item.data('region-id'));
60            $input.blur();
61
62            $('#user_region').attr('data-old-region-id', $item.data('region-id'));
63        }
64
65        function choosed(){
66            if($inputId.val()){
67                var $html_ch = $('<div id="select-'+input_name+'" class="select-choosed"></div>');
68                if(!$('#select-'+input_name+'').length){
69                    $choosed.wrapAll($html_ch);
70                }else if($('.select-'+input_name+'').length){
71                    console.log(111);
72                    $('#select'+input_name+'').removeClass('select-choosed_none');
73                }
74
75                $choosed.attr('data-mod', 'choosed').html($input.data('region-title')).hide().fadeIn(300);
76                $choosed.off('.choose-region').on('click.choose-region', function(){
77                    openModal($inputId.val());
78                });
79                $input.hide();
80
81                if(!$('#select-'+input_name+'').find('a#button_clear_'+input_name+'').length){
82                    $('#select-'+input_name+'').append($button_clear_region);
83                }
84
85                $choosed.parents('#select-'+input_name+'').find('a#button_clear_'+input_name+'').on('click', function(e){
86                    e.preventDefault();
87                    $choosed.removeAttr('data-mod', 'choosed').hide().fadeOut(300);
88                    $('#select-'+input_name+'').addClass('select-choosed_none');
89                    if($('#select-'+input_name+'').find('a#button_clear_'+input_name+'').length){
90                        $button_clear_region.remove();
91                    }
92                    $input.show();
93                    $input.val('');
94                    $inputId.val('');
95                });
96
97            }else{
98                if($input.val()){
99                    var $item = $holder.find('.select-region-item').filter(function(){
100                        return $(this).data('region-title').toLowerCase() == $input.val().toLowerCase();
101                    }).eq(0);
102
103                    if($item.length){
104                        choose($item);
105
106                    }else{
107                        $choosed.attr('data-mod', 'notfound').html('К сожалению нам не удалось найти указанный вами город «' + $input.val() + '»<br><button type="button" button="blue small" class="mod-margin-top">Выбрать населенный пункт</button>').hide().fadeIn(300);
108                        $input.hide();
109                        $choosed.find('button').on('click', function(){
110                            console.log(789);
111                            openModal();
112                        });
113                    }
114
115                }
116            }
117
118        }
119
120        function openModal(region_id){
121            $$.openModal({
122                url: $$.urlPrefix + '/api/chooseRegionForm/',
123                data: {region_id: region_id},
124                afterOpen: function(modal, $modal){
125                    var $holder = $modal.find('.form-group');
126
127                    $modal.on('click', '[js-choose-region-select]', function(e){
128                        e.preventDefault();
129
130                        var $button =  $(this),
131                            id = $button.data('id') || '',
132                            $lists = $modal.find('.choose-region'),
133                            $list = $lists.filter('[data-id="'+id+'"]');
134                        if($list.length){
135                            $list.show().siblings($lists).hide();
136                        }else{
137                            $.ajax({
138                                url: $$.urlPrefix + '/api/chooseRegionForm/?list',
139                                data: {region_id: id},
140                                dataType: 'json',
141                                type: 'get',
142                                cache: true,
143                                xhrFields: {
144                                    withCredentials: true
145                                },
146                                crossDomain: true,
147                                success: function(response){
148                                    if(response.list){
149                                        $list = $(response.list);
150                                        $holder.append($list);
151                                        $list.show().siblings($lists).hide();
152                                    }
153                                }
154                            });
155                        }
156                    });
157
158                    $modal.on('click', '[js-choose-region-choose]', function(e){
159                        e.preventDefault();
160                        choose($(this));
161                        $modal.arcticmodal('close');
162                    });
163
164                    $modal.on('keyup', '.choose-region-search input', function(){
165                        var $input = $(this),
166                            $items = $input.closest('.choose-region').find('.choose-region-item'),
167                            value = $input.val();
168
169                        if(value){
170                            $items.hide().filter(function(){return value.toLowerCase() == this.innerHTML.toLowerCase().substring(0, value.length); }).show();
171                        }else{
172                            $items.show();
173                        }
174                    });
175                }
176            });
177        }
178
179        function hide(){
180            $holder.hide();
181        }
182
183        function show(){
184            $holder.show();
185        }
186
187        function render(value){
188            var html = '', count = 0;
189            $.each(regions, function(i, region){
190                if(region[1].toLowerCase().substring(0, value.length) == value.toLowerCase()){
191                    html += '<div class="select-region-item" data-region-id="'+region[0]+'" data-region-title="'+region[1]+'" data-region-parent="'+region[2]+'">' + region[1] + ' (' + region[2] + ')</div>';
192                    if(++count > 10){
193                        return false;
194                    }
195                }
196            });
197            $holder.html(html);
198            return html;
199        }
200
201        $input.on('keyup refresh.choose-region', function(){
202            var value = $input.val();
203
204            if(value.length >= 3){
205                if(prefix == value.substring(0, 3)){
206                    if(render(value)){
207                        show();
208                    }else{
209                        hide();
210                    }
211
212                }else{
213                    prefix = value.substring(0, 3);
214                    regions = [];
215                    request = $.ajax({
216                        url: $$.urlPrefix + '/api/chooseRegion/',
217                        data: {prefix: prefix},
218                        dataType: 'json',
219                        type: 'get',
220                        cache: true,
221                        xhrFields: {
222                            withCredentials: true
223                        },
224                        crossDomain: true,
225                        success: function(response){
226                            if(response){
227                                regions = response;
228                                $input.triggerHandler('refresh')
229                            }
230                        }
231                    });
232                }
233            }else{
234                hide();
235            }
236        });
237
238        choosed();
239    });
240};
241
242$.fn.chooseLibrary = function(){
243    this.each(function(){
244        var $input = $(this),
245            libraryItem = $input.data('library-item'),
246            request,
247            prefix,
248            librarys = [];
249
250
251        if($input.data('initialized')) return;
252        $input.data('initialized', true);
253
254        var $holder = $('<div class="select-library-holder">'),
255            $inputId = $('<input type="hidden" name="library-item">'),
256            $choosed = $('<div class="select-library-choosed">');
257
258        if(libraryItem){
259            $inputId.val(libraryItem);
260        }
261
262        $input
263            .closest('.form-input-field').append($holder)
264            .closest('.form-input').append($inputId).append($choosed);
265
266        $holder.on('mousedown', '.select-library-item', function(e){
267            e.preventDefault();
268            choose($(this));
269        });
270
271        $input.on('blur', function(){
272            hide();
273            choosed();
274        });
275        $input.on('focus', function(){
276            $input.triggerHandler('refresh');
277        });
278
279        //заполняем поле "инпут" тем что выбрали
280        function choose($item){
281            $input.data('library-item', $item.data('library-item')).data('library-item-title', 'Перейти: "' + $item.data('library-item-title') + '"' );
282            $inputId.val($item.data('library-url'));
283            $input.blur();
284        }
285
286        function choosed(){
287            if($inputId.val()){
288                $choosed.attr('data-mod', 'choosed').html($input.data('library-item-title')).hide().fadeIn(300);
289                $choosed.off('.choose-library').on('click.choose-library', function(){
290                    redirectPage($inputId.val());
291                });
292                $input.closest('.form-input-field').hide();
293                $input.hide();
294
295            }
296
297        }
298
299        function redirectPage(libraryUrl){
300            window.location.href = 'http://' + location.hostname + libraryUrl;
301        }
302
303        function hide(){
304            $holder.hide();
305        }
306
307        function show(){
308            $holder.show();
309        }
310
311        function render(value){
312            var html = '', count = 0;
313            $.each(librarys, function(i, lib_item){
314                if(lib_item[1].toLowerCase().substring(0, value.length) == value.toLowerCase()){
315                    html += '<div class="select-library-item" data-library-item="'+lib_item[0]+'" data-library-item-title="'+lib_item[1]+'" data-library-url="'+lib_item[2]+'">' + lib_item[1] + '</div>';
316                    if(++count > 10){
317                        return false;
318                    }
319                }
320            });
321            $holder.html(html);
322            return html;
323        }
324
325        $input.on('keyup refresh.choose-library', function(){
326            var value = $input.val() ; //то что вводим
327
328            if(value.length >= 3){
329                if(prefix == value.substring(0, 3)){
330
331                    if(render(value)){
332                        show();
333                    }else{
334                        hide();
335                    }
336                }else{
337                    prefix = value.substring(0, 3);
338                    librarys = [];
339                    request = $.ajax({
340                        url: $$.urlPrefix + '/api/chooseLibrary/',
341                        data: {prefix: prefix},
342                        dataType: 'json',
343                        type: 'get',
344                        cache: true,
345                        xhrFields: {
346                            withCredentials: true
347                        },
348                        crossDomain: true,
349                        success: function(response){
350                            if(response){
351                                librarys = response;
352                                $input.triggerHandler('refresh')
353                            }
354                        }
355                    });
356                }
357            }else{
358                hide();
359            }
360        });
361
362        choosed();
363    });
364};
365
366/**
367 * Инициализация хелпера
368 */
369$(function(){
370    $$.$body = $('body');
371
372	$$.isAuthenticated = $$.$body.data('is-authenticated') == 1;
373	$$.host = $$.$body.data('host');
374	$$.urlPrefix = '//' + $$.host;
375
376    var init = {
377        tips: function (context){
378            if ( !$.fn.qtip ) return;
379
380            var $tips = $('[js-tip]', context);
381
382            $tips
383                .qtip({
384                    overwrite: true,
385                    position: {
386                        viewport: $$.window,
387                        my: 'bottom center',
388                        at: 'top center'
389                    },
390                    show: {
391                        solo: true
392                    },
393                    hide: {
394                        delay: 100
395                    },
396                    style: {
397                        classes: 'qtip-main',
398                        tip: {
399                            corner: true,
400                            border: 0,
401                            width: 24,
402                            height: 12
403                        }
404                    }
405                })
406                .filter('[data-tip]').each(function (i, tip) {
407                    var $tip = $tips.eq(i);
408                    $tip.qtip('option', $tip.data('tip'));
409                });
410        },
411        tipsTitle: function (context){
412            if ( !$.fn.qtip ) return;
413
414            var $tips = $('[title]:not([js-tip])', context);
415
416            $tips
417                .qtip({
418                    overwrite: true,
419                    position: {
420                        target: 'mouse',
421                        viewport: $$.window,
422                        my: 'top left',
423                        at: 'bottom left',
424                        adjust: {
425                            x: 10,
426                            y: 10,
427                            mouse: false
428                        }
429                    },
430                    show: {
431                        solo: true,
432                        delay: 700
433                    },
434                    hide: {
435                        distance: 15
436                    },
437                    style: {
438                        classes: 'qtip-main'
439                    }
440                });
441        },
442        popup: function (context){
443            Helper.bindPopup($('[js-open-popup]', context));
444        },
445        modal: function (context){
446            Helper.bindModal($('[js-open-modal]', context));
447        },
448        tabs: function (context){
449            Helper.createTabs();
450            Helper.createTabs({
451                tabs: $('[js-collapse-tab]', context),
452                panes: $('[js-collapse-pane]', context),
453                speed: 0,
454                hash: false,
455                openFirst: false,
456                closeOpened: true
457            });
458        },
459        selectus: function (context){
460            if($('[js-selectus]')){
461                $('[js-selectus]', context).selectus();
462            }
463        },
464        range: function (context) {
465            if ( !$.fn.ionRangeSlider ) return;
466
467            $('[js-range]', context).ionRangeSlider({
468                type: 'double',
469                min: 0,
470                max: 10
471            });
472        },
473        formPlugins: function (context) {
474            this.selectus(context);
475        }
476    };
477    init.all = function (context){
478        this.popup(context);
479        this.modal(context);
480        this.tabs(context);
481        this.selectus(context);
482        this.tips(context);
483        this.tipsTitle(context);
484        this.range(context);
485
486
487        $('[js-choose-region]', context).chooseRegion();
488
489        $('[js-choose-region_horar]', context).chooseRegion();
490
491		$('[js-choose-library]', context).chooseLibrary();
492
493        $('[data-inputmask]', context).inputmask();
494    };
495    $$.init = init;
496
497    $$.init.all();
498
499    Helper.bindPopup('[js-open-popup-live]', document, true);
500});
501
502// $(function(){
503//     $('a#button_clear_region').on('click', function(e){
504//         e.preventDefault();
505//        console.log(12323);
506//     });
507// });
508
509
510angular.module('socket', []).factory('$socket', function($rootScope){
511    return {
512        on: function(eventName, callback){
513            socket.on(eventName, function(){
514                var args = [].slice.call(arguments);
515                $rootScope.$apply(function(){
516                    if(callback){
517                        callback.apply(socket, args);
518                    }
519                });
520            });
521        },
522        emit: function(eventName, data, callback){
523            var args = [].slice.call(arguments), cb;
524            if(typeof args[args.length - 1] == "function"){
525                cb = args[args.length - 1];
526                args[args.length - 1] = function(){
527                    var args = [].slice.call(arguments);
528                    $rootScope.$apply(function(){
529                        if(cb){
530                            cb.apply(socket, args);
531                        }
532                    });
533                };
534            }
535            socket.emit.apply(socket, args);
536        }
537    };
538});
539
540(function(){
541
542    var socket = io.connect('//astrology.pro:' + (window.location.protocol == 'http:' ? 8000 : 8443));
543
544
545    socket.join = function(room){
546        this.emit('join', {room: room});
547    };
548
549    socket.leave = function(room){
550        this.emit('leave', {room: room});
551    };
552
553    socket.on('connect', function(){
554    });
555
556    socket.on('disconnect', function(){
557
558    });
559
560    window.socket = socket;
561
562    $(function(){
563        var accessKey = $('body').data('user-token');
564        if(accessKey) socket.emit('register', {accessKey: accessKey});
565    });
566
567})();
568(function(){
569/**
570 * Хэлпер с глобальными функциями
571 */
572var Lib = {
573    dispatcher: new MicroEvent,
574    window: $(window),
575    document: $(document),
576    isMobile: (/iphone|ipad|ipod|android|blackberry|mini|windowssce|palm/i.test(navigator.userAgent)),
577
578    escapeHtml: function(text) {
579        return text
580            .replace(/&/g, "&amp;")
581            .replace(/</g, "&lt;")
582            .replace(/>/g, "&gt;")
583            .replace(/"/g, "&quot;")
584            .replace(/'/g, "&#039;");
585    },
586
587    uniFormBlackout: function($overlayParent){
588        var $overlay, static = $overlayParent.css('position') == 'static';
589
590        if(static){
591            $overlayParent.css('position', 'relative');
592        }
593
594        $overlay = $('<div class="form-overlay"></div>').appendTo($overlayParent);
595        $overlay.css({opacity: 0, borderRadius: $overlayParent.css('border-radius')});
596        $overlay.animate({opacity: .5}, 200);
597
598        return function(){
599            $overlay.remove();
600
601            if(static){
602                $overlayParent.css('position', 'static');
603            }
604        };
605    },
606    uniFormError: function($container, errors){
607        if(errors === undefined){
608            $container.find('div.error:not([data-error-handler])').remove();
609            $container.find('div.error-handler').text('').attr('style', '');
610            $container.find('.error').removeClass('error');
611        }
612        else {
613            $.each(errors, function(key,value){
614                if('#' == key){
615                    $$.alert(value);
616                }
617                else if(typeof value == 'object'){
618                    $.each(value, function(index, value){
619                        var field = $container.find('[name="'+key+'['+index+']"]');
620                        if(!field.length && index == 0) field = $container.find('input[type=text][name^="'+key+'"]:eq(0)');
621                        Lib.uniFormShowError(field, value);
622                    });
623                }
624                else{
625                    var field = $container.find('[name="'+key+'"]'),
626                        fieldHandler = $container.find('[data-error-handler="'+key+'"]');
627
628                    if(fieldHandler.length){
629                        field = fieldHandler;
630                    }
631
632                    if(field.length){
633                        Lib.uniFormShowError(field, value);
634                    }
635                }
636            });
637
638            var $error = $container.find('div.error:eq(0)');
639            if(!Lib.isElementOnView($error)) {
640                Lib.scrollTo($error);
641            }
642        }
643    },
644    uniFormShowError: function($field, message){
645        if(!$field.is(':visible')){
646            return;
647        }
648
649        var $error = $('<div class="error">'+message+'</div>'),
650            reflect = {
651                radius: $field.css('border-radius'),
652                family: $field.css('font-family'),
653                weight: parseFloat($field.css('font-weight')),
654                size: parseFloat($field.css('font-size')),
655                line: $field.css('line-height'),
656                width: $field.width(),
657                height: $field.height(),
658                border: {
659                    top: parseFloat($field.css('border-top-width')) || 0,
660                    right: parseFloat($field.css('border-right-width')) || 0,
661                    bottom: parseFloat($field.css('border-bottom-width')) || 0,
662                    left: parseFloat($field.css('border-left-width')) || 0
663                },
664                padding: {
665                    top: parseFloat($field.css('padding-top')),
666                    right: parseFloat($field.css('padding-right')),
667                    bottom: parseFloat($field.css('padding-bottom')),
668                    left: parseFloat($field.css('padding-left'))
669                }
670            };
671
672        $error.css({
673            borderRadius: reflect.radius,
674            fontFamily: reflect.family,
675            fontWeight: reflect.weight,
676            fontSize: reflect.size,
677            lineHeight: reflect.line,
678            paddingTop: reflect.padding.top,
679            paddingRight: reflect.padding.right,
680            paddingBottom: reflect.padding.bottom,
681            paddingLeft: reflect.padding.left,
682            top: reflect.border.top,
683            right: reflect.border.right,
684            bottom: reflect.border.bottom,
685            left: reflect.border.left
686        });
687
688
689        $field.addClass('error').closest('dd, dt, dl, td, .form-input-field').prepend($error);
690        $field.closest('tr').addClass('error');
691
692        $error.click(function(){
693            if($field.is('[data-error-handler]')){
694                $field.click()
695            }else{
696                $field.focus();
697            }
698            $field.removeClass('error').closest('tr').removeClass('error');
699            $error.remove();
700        });
701
702        $field.on('focus', function(){
703            $field.removeClass('error').closest('tr').removeClass('error');
704            $error.remove();
705        });
706
707        if($field.is('[data-error-handler]')){
708            $error.addClass('error-handler');
709        }
710
711        $error.hide().fadeIn(100);
712    },
713
714    uniFormHandle: function(form, callbacks){
715        form.on('submit', function(e){
716            e.preventDefault();
717            Lib.uniFormSubmit($(this), callbacks);
718        });
719    },
720    uniFormSubmit: function(form, callbacks){
721        var blackout;
722
723        if(callbacks.success){
724            callbacks.afterSuccess = callbacks.success;
725            delete callbacks.success;
726        }
727
728        if(form.data('blocked')) return;
729
730        if(callbacks.beforeData){
731            var beforeData = callbacks.beforeData(form);
732            if(beforeData === false) return false;
733        }
734
735        if(callbacks.overlay){
736            blackout = Lib.uniFormBlackout(callbacks.overlay === true ? form : callbacks.overlay);
737        }
738
739        form.data('blocked', true);
740        var ignoreDefaultLoading = form.data('ignoreDefaultLoading');
741        var url = location.protocol+'//'+location.hostname+location.pathname;
742        var params = {url: url};
743
744        if(callbacks.data){
745            $.extend(params, callbacks.data);
746        }
747
748        if (callbacks.beforeSubmit) callbacks.beforeSubmit(form);
749
750
751        form.find('.attach-images').each(function(){
752            var $root = $(this),
753                $images = $root.find('.attach-images-item'),
754                $input = $root.siblings('.form-input-field').find('textarea, input'),
755                text = $input.val();
756
757            $images.each(function(){
758                var $image = $(this);
759                if($image.data('id')){
760                    if(!text.match(new RegExp('\\[img='+$image.data('id')+'\\]', 'ig'))){
761                        text += '[img='+$image.data('id')+']';
762                    }
763                }
764            });
765
766            $input.val(text);
767        });
768
769        var parameters = { dataType: 'json', data: params,
770            beforeSend: function(){
771                Lib.uniFormError(form);
772            },
773            complete: function(){
774                form.data('blocked', false);
775                if(callbacks.overlay){
776                    blackout();
777                }
778            },
779            success: function(data){
780                form.data('blocked', false);
781                if(data.error){
782                    Lib.uniFormError(form, data.error);
783
784                    if(callbacks.afterData)  callbacks.afterData(form, data);
785
786                }else if(data.success){
787                    form.find('.attach-images').remove();
788                    if(callbacks.afterData)  callbacks.afterData(form, data);
789                    if(callbacks.afterSuccess)  callbacks.afterSuccess(data, form);
790
791                    if(data.$events){
792                        $.each(data.$events, function(event, options){
793                            $$.dispatcher.trigger(event, options);
794                        });
795                    }
796
797                }else{
798                    if(callbacks.afterData)  callbacks.afterData(form, data);
799                }
800
801
802            },
803            error: function(request, type, message){
804                if(type == 'parsererror' || type == 'error'){
805                    (window.open('', '', 'width=950,height=600,scrollbars=yes')).document.write(request.responseText);
806                }
807            }
808        };
809
810        var actionMatch = form.attr('action').match(/^https?:\/\/([^\/]+)/i);
811        if(actionMatch){
812            if(actionMatch[1] != document.location.hostname){
813                $.extend(parameters, {
814                    xhrFields: {
815                        withCredentials: true
816                    },
817                    crossDomain: true
818                });
819            }
820        }
821
822        form.ajaxSubmit(parameters);
823        return false;
824    },
825    createModalBox: function(cssClass, options){
826        return $('<div class="modal-box '+ ( typeof cssClass !== 'object' ? cssClass : '' ) +' '+ ( (options && options.boxCssClass) ? options.boxCssClass : '' ) +'">' +
827        '<i class="arcticmodal-close modal-box-close"></i>' +
828        '<div class="modal-box-content"></div>' +
829        '');
830    },
831    openModal: function(className, options){
832        options = options || {};
833        if (typeof className === 'object' && className.jquery){
834	        return $$.createModalBox(className, options)
835                .find('.modal-box-content')
836                    .html(options.title ? '<div class="modal-box-title">'+options.title+'</div>' : '')
837                    .append(className.clone(true))
838                .end()
839                .arcticmodal(options);
840        }
841        else if(typeof className === 'object' && className.url){
842
843            options = className;
844            options.type = 'ajax';
845
846            if(options.afterOpen){
847                options.afterOpenSuccess = options.afterOpen;
848                delete options.afterOpen;
849            }
850            if(!options.ajax){
851                options.ajax = {};
852            }
853            if(options.data){
854                options.ajax.data = options.data;
855                delete options.data;
856            }
857            $.extend(options.ajax, {
858                type: 'get',
859                success: function(modal, $modal, response){
860                    var responseJSON;
861                    try{
862                        responseJSON = $.parseJSON(response);
863                        response = responseJSON;
864                    }catch(e){
865                        response = {content: response}
866                    }
867
868                    if(response.content){
869                        if(className.cssModClasses !== undefined){
870                            modal.body.html(
871                                $$.createModalBox(className.cssModClasses)
872                            );
873                        }else{
874                            modal.body.html(
875                                $$.createModalBox({})
876                            );
877                        }
878
879
880                        $modal = modal.body.find('.modal-box-content').append(response.content);
881
882                        $$.init.all($modal);
883                        $$.init.listManager($modal);
884
885                        options.modules = options.modules || [];
886                        options.modules.push('ng');
887
888                        if(options.afterOpenSuccess){
889                            options.afterOpenSuccess.call(this, modal, $modal, response);
890                        }
891
892                        angular.injector(options.modules).invoke(function($rootScope, $compile) {
893                            $compile($modal)($rootScope);
894                            $rootScope.$digest();
895                        });
896
897                    }else{
898                        $modal.arcticmodal('close');
899
900                        if(response.error && response.error['#']){
901                            $$.alert(response.error['#']);
902                        }
903
904
905                    }
906                },
907                error: function(modal, $modal){
908
909                }
910            });
911
912            $.arcticmodal(options);
913        }
914        else {
915            return $$.createModalBox(className)
916                .find('.modal-box-content')
917                    .html((options.title ? '<div class="modal-box-title">'+options.title+'</div>' : '') + $('.'+className).html())
918                    .end()
919                    .arcticmodal(options);
920        }
921    },
922    scrollTo: function(elem, speed, offset, callback){
923        if(!elem.length) return false;
924        var selector = 'html:not(:animated), body:not(:animated)';
925        var blocked = false;
926        var $modal = elem.closest('.arcticmodal-container');
927        if($modal.length){
928            selector = $modal.filter(':not(:animated)');
929        }
930
931        if(!speed) speed = 300;
932        if(!offset) offset = 0;
933        var offs = {};
934        if(elem-0 >= 0){
935            offs.top = elem;
936        }else{
937            offs = elem.offset();
938        }
939
940        offset = offs.top - offset;
941        // offset = typeof selector == 'string' ? (offset-50) : (offset - $(document).scrollTop()+$(selector).scrollTop() - 30);
942
943        if(offs){
944            $(selector).animate({ scrollTop: offset}, speed, function(){
945                if(callback && !blocked){
946                    blocked = true;
947                    callback();
948                }
949            });
950            $(window).one('scroll', function(){
951                $(selector).stop();
952                if(callback && !blocked){
953                    blocked = true;
954                    callback();
955                }
956            });
957        }
958
959        blocked = false;
960    },
961	isElementOnView: function (elem, offset){
962		if(!elem.length) return false;
963		if(!offset) offset = 0;
964		var docViewTop = $(window).scrollTop();
965		var docViewBottom = docViewTop + $(window).height();
966
967		var elemTop = $(elem).offset().top;
968		var elemBottom = elemTop + $(elem).height();
969
970		return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop+offset));
971	},
972	initPrettyPhoto: function(context){
973		$("a[rel^='prettyPhoto'], a[rel^='image'], a[rel^='media']", context).prettyPhoto({
974			animation_speed: 'fast', /* fast/slow/normal */
975			opacity: 0.60, /* Value between 0 and 1 */
976			show_title: false, /* true/false */
977			allow_resize: true, /* Resize the photos bigger than viewport. true/false */
978			default_width: 800,
979			default_height: 600,
980			counter_separator_label: ' |В· ', /* The separator for the gallery counter 1 "of" 2 */
981			theme: 'overbyte', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
982			horizontal_padding: 20, /* The padding on each side of the picture */
983			hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
984			wmode: 'opaque', /* Set the flash wmode attribute */
985			autoplay: true, /* Automatically start videos: True/False */
986			modal: false, /* If set to true, only the close button will close the window */
987			deeplinking: false, /* Allow prettyPhoto to update the url to enable deeplinking. */
988			overlay_gallery: false, /* If set to true, a gallery will overlay the fullscreen image on mouse over */
989			keyboard_shortcuts: false,
990			ie6_fallback: true,
991			social_tools: false
992		});
993	},
994    confirm: function(params) {
995        var message = params.message ?  params.message : arguments[0];
996        var onConfirm = params.onConfirm ?  params.onConfirm : arguments[1];
997        var onCancel = params.onCancel ?  params.onCancel : arguments[2];
998
999        var $box = $$.createModalBox('modal-box-message');
1000        var $content = $box.find('.modal-box-content');
1001        $content.html('<div class="modal-box-tabled"><div class="modal-box-tabled-cell"><div class="modal-box-tabled-cell-body">'+message+'</div></div></div>');
1002        $('<div class="modal-box-buttons modal-box-buttons--center"><button button="middle" class="button-confirm-action">OK</button><button  button="middle white" class="button-cancel-action arcticmodal-close">Отмена</button></div></div>').insertAfter($content);
1003        $box.arcticmodal();
1004        $box.find('.button-confirm-action')[0].focus();
1005        if(onCancel) $box.find('.button-cancel-action').on('click', function(){ onCancel() });
1006        $box.find('.button-confirm-action').on('click', function(){
1007            $box.arcticmodal('close');
1008            if(onConfirm) onConfirm();
1009        });
1010    },
1011    alert: function (text, wide, params) {
1012
1013        function _alert(message, params){
1014            var $box = $$.createModalBox('modal-box-message '+(wide ? 'modal-box-message-wide' : ''));
1015            var $content = $box.find('.modal-box-content');
1016            $content.html('<div class="modal-box-tabled"><div class="modal-box-tabled-cell"><div class="modal-box-tabled-cell-body">'+message+'</div></div></div>');
1017            $('<div class="modal-box-buttons modal-box-buttons--center"><button button="middle" class="arcticmodal-close">OK</button></div>').insertAfter($content);
1018            $box.arcticmodal();
1019            $box.find('button')[0].focus();
1020            var onOk = params && params.onOk ?  params.onOk : arguments[2];
1021            $box.find('button').on('click', function(){
1022                if(onOk) onOk();
1023            });
1024        }
1025
1026        _alert(text, wide, params);
1027    },
1028    blockOverlay: function ($elem, css) {
1029        var overlay = $elem.data('block-overlay');
1030
1031        css = $.extend({
1032            zIndex: 100,
1033            opacity: .5,
1034            position: 'absolute',
1035            top: 0,
1036            left: 0,
1037            right: 0,
1038            bottom: 0,
1039            background: '#fff'
1040        }, css);
1041
1042        if ( overlay ) {
1043            $elem.removeData('block-overlay');
1044            overlay.remove();
1045        }
1046        else {
1047            overlay = $('<div class="block-overlay" />').css(css);
1048
1049            if ( $elem.css('position') == 'static' ) {
1050                $elem.css({
1051                    position: 'relative'
1052                });
1053            }
1054
1055            $elem.data('block-overlay', overlay.appendTo($elem));
1056        }
1057    },
1058    getLatFormatted: function (lat) {
1059        var coordinatesLat = lat.toString().split('.');
1060
1061        return Math.abs(coordinatesLat[0]) + (coordinatesLat[0] >= 0 ? 'n' : 's') + (coordinatesLat.length > 1 ? Math.round(parseFloat('0.' + coordinatesLat[1]) * 60) : '00')
1062    },
1063    etlngFormatted: function (lng) {
1064        var coordinatesLat = lng.toString().split('.');
1065
1066        return Math.abs(coordinatesLat[0]) + (coordinatesLat[0] >= 0 ? 'e' : 'w') + (coordinatesLat.length > 1 ? Math.round(parseFloat('0.' + coordinatesLat[1]) * 60) : '00')
1067    },
1068    setDatetimePicker: function (date_timestamp) {
1069        if(date_timestamp){
1070            $('#datetimepicker12').datetimepicker({
1071                defaultDate: date_timestamp,
1072                inline: true,
1073                sideBySide: true,
1074                format: 'DD.MM.YYYY HH:mm',
1075                locale: 'ru',
1076            });
1077        }else{
1078            $('#datetimepicker12').datetimepicker({
1079                inline: true,
1080                sideBySide: true,
1081                format: 'DD.MM.YYYY HH:mm',
1082                locale: 'ru',
1083            });
1084        }
1085
1086        var setDatetimepicker_input = function () {
1087            var q = $('#datetimepicker12').data('DateTimePicker').date().format('DD.MM.YYYY HH:mm');
1088            $('#datetimepicker_input').val(q);
1089        };
1090        setDatetimepicker_input();
1091
1092        $("#datetimepicker12").on("dp.change", function (e) {
1093            setDatetimepicker_input();
1094        });
1095
1096        if($('.dt_free').length){
1097            $$.createCheckbox();
1098        }
1099
1100        if($('.determine-time').length){
1101            $$.createCheckbox();
1102        }
1103
1104        $('input[name^=determine_time]').on('change', function(e){
1105            $$.createCheckbox();
1106        });
1107    },
1108    createCheckbox: function (state_check) {
1109        var $input = $('input[type=text][name^=region]'),
1110            $holder = $('.select-region-holder'),
1111            $inputId = $('input[name^=region_id]'),
1112            $choosed = $('.select-region-choosed'),
1113            $user_region = $('#user_region'),
1114            userRegionId = $('#user_region').data('user-region-id'),
1115            oldRegionId = $('#user_region').data('old-region-id'),
1116            regionId = $input.data('region-id'),
1117            $state_checkbox;
1118
1119
1120        // console.log($inputId);
1121        // console.log($userRegionId);
1122
1123        if(state_check == undefined){
1124            $state_checkbox = $("#determine_time").prop('checked')
1125        }else{
1126            $state_checkbox = state_check;
1127        }
1128
1129        if($state_checkbox){
1130            if(userRegionId){
1131                $inputId.val(userRegionId);
1132            }
1133
1134            $.ajax({
1135                url: $$.urlPrefix + '/api/chooseRegionId/',
1136                data: {region_id: userRegionId},
1137                dataType: 'json',
1138                type: 'get',
1139                cache: true,
1140                xhrFields: {
1141                    withCredentials: true
1142                },
1143                crossDomain: true,
1144                success: function(response){
1145                    if(response){
1146                        regions = response;
1147                        $input.val(regions[0][2] + ' (' + regions[0][5] + ')' );
1148                    }
1149                }
1150            });
1151
1152            $input.attr('disabled', 'disabled');
1153            $input.show();
1154            $choosed.attr('disabled', 'disabled');
1155            $choosed.addClass('mod-user-region');
1156            if($choosed.text()){
1157                $choosed.hide();
1158            }
1159        }else{
1160            var $inp;
1161            
1162            $input.each(function(key,value){
1163                $inp = $(this);
1164
1165                if($choosed.data('mod')){
1166                    $inp.hide();
1167                    $choosed.show();
1168                }else{
1169                    $inp.val('');
1170                }
1171
1172                if(oldRegionId){
1173                    $inputId.val(oldRegionId);
1174                }else{
1175                    $inputId.removeAttr('value');
1176                }
1177                $inp.removeAttr('disabled');
1178                $choosed.removeAttr('disabled');
1179                $choosed.removeClass('mod-user-region');
1180            });
1181        }
1182    },
1183    getSelect: function (){
1184        var x, i, j, selElmnt, a, b, c, v, name, inp;
1185        /*look for any elements with the class "custom-select":*/
1186        x = document.getElementsByClassName("custom-select");
1187        for (i = 0; i < x.length; i++) {
1188            selElmnt = x[i].getElementsByTagName("select")[0];
1189            name = selElmnt.getAttribute("name");
1190            // inp = document.getElementsByName('input_'+name+'');
1191            /*for each element, create a new DIV that will act as the selected item:*/
1192            a = document.createElement("DIV");
1193            a.setAttribute("class", "select-selected");
1194            a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
1195            x[i].appendChild(a);
1196            /*for each element, create a new DIV that will contain the option list:*/
1197            b = document.createElement("DIV");
1198            if(selElmnt.classList.contains('mod_nod')){
1199                b.setAttribute("class", "select-items select-hide mod_nod");
1200            }else{
1201                b.setAttribute("class", "select-items select-hide");
1202            }
1203            b.setAttribute("id", name);
1204            for (j = 0; j < selElmnt.length; j++) {
1205                /*for each option in the original select element,
1206                create a new DIV that will act as an option item:*/
1207                c = document.createElement("DIV");
1208                v = selElmnt.options[j].getAttribute("value");
1209                c.innerHTML = selElmnt.options[j].innerHTML;
1210                c.setAttribute('value', v);
1211                c.addEventListener("click", function(e) {
1212                    /*when an item is clicked, update the original select box,
1213                    and the selected item:*/
1214                    var y, i, k, s, h, y_val, name_s;
1215                    s = this.parentNode.parentNode.getElementsByTagName("select")[0];
1216                    h = this.parentNode.previousSibling;
1217                    name_s = s.getAttribute("name");
1218                    inp = document.getElementsByName('input_'+name_s+'');
1219                    for (i = 0; i < s.length; i++) {
1220                        if (s.options[i].innerHTML == this.innerHTML) {
1221                            s.selectedIndex = i;
1222                            h.innerHTML = this.innerHTML;
1223                            y = this.parentNode.getElementsByClassName("same-as-selected");
1224                            for (k = 0; k < y.length; k++) {
1225                                y[k].removeAttribute("class");
1226                            }
1227                            y_val = this.getAttribute("value");
1228                            if(inp.length){
1229                                inp[0].value = y_val;
1230                            }
1231                            this.setAttribute("class", "same-as-selected");
1232                            break;
1233                        }
1234                    }
1235                    h.click();
1236                });
1237                b.appendChild(c);
1238            }
1239            x[i].appendChild(b);
1240            a.addEventListener("click", function(e) {
1241                /*when the select box is clicked, close any other select boxes,
1242                and open/close the current select box:*/
1243                e.stopPropagation();
1244                closeAllSelect(this);
1245                this.nextSibling.classList.toggle("select-hide");
1246                this.classList.toggle("select-arrow-active");
1247            });
1248        }
1249        function closeAllSelect(elmnt) {
1250            /*a function that will close all select boxes in the document,
1251            except the current select box:*/
1252            var x, y, i, arrNo = [];
1253            x = document.getElementsByClassName("select-items");
1254            y = document.getElementsByClassName("select-selected");
1255            for (i = 0; i < y.length; i++) {
1256                if (elmnt == y[i]) {
1257                    arrNo.push(i)
1258                } else {
1259                    y[i].classList.remove("select-arrow-active");
1260                }
1261            }
1262            for (i = 0; i < x.length; i++) {
1263                if (arrNo.indexOf(i)) {
1264                    x[i].classList.add("select-hide");
1265                }
1266            }
1267        }
1268        /*if the user clicks anywhere outside the select box,
1269        then close all select boxes:*/
1270        document.addEventListener("click", closeAllSelect);
1271    }
1272};
1273
1274(function(){
1275    Lib.Tabs = function (options) {
1276        this.defaults = {
1277            tabs: '[js-tabs-tab]',
1278            panes: '[js-tabs-pane]',
1279            speed: 0,
1280            hash: false,
1281            openFirst: true,
1282            closeOpened: false,
1283            parent: $('body') ,
1284	        prevent: false
1285        };
1286        this.options = $.extend({}, this.defaults, options);
1287        this.$tabs = (typeof this.options.tabs === 'string') ? $(this.options.tabs) : this.options.tabs;
1288        this.$panes = (typeof this.options.panes === 'string') ? $(this.options.panes) : this.options.panes;
1289        this.groups = {};
1290        this.init();
1291
1292    };
1293    var proto = Lib.Tabs.prototype;
1294
1295
1296    proto.select = function (group, id, speed) {
1297        var self = this;
1298        var options = self.options;
1299        var $panes = self.getPanes(group);
1300        var $pane = $panes.filter('[data-tabs-pane~="'+group+':'+id+'"]');
1301        var $tabs = self.getTabs(group);
1302        var $tab = $tabs.filter('[data-tabs-tab~="'+group+':'+id+'"]');
1303
1304        speed = typeof speed == 'undefined' ? options.speed : speed;
1305
1306        if ($pane.length) {
1307            $tabs.removeClass('is-active');
1308            $tab.removeClass('is-broken').addClass('is-active');
1309            $panes.removeClass('is-active').addClass('is-hidden').stop().slideUp(speed);
1310            $pane.stop().slideDown(speed, function() {
1311                options.parent.trigger({
1312                    type: 'tabChanged',
1313                    tab: $tab,
1314                    pane: $pane,
1315                    group: group,
1316                    id: id
1317                });
1318            }).removeClass('is-hidden').addClass('is-active');
1319
1320            options.parent.trigger({
1321                type: 'tabChange',
1322                tab: $tab,
1323                pane: $pane,
1324                group: group,
1325                id: id
1326            });
1327        }
1328        else {
1329            $tab.addClass('is-broken');
1330        }
1331    };
1332    proto.unselect = function (group, speed) {
1333        var self = this;
1334        var options = self.options;
1335        var $panes = self.getPanes(group);
1336        var $tabs = self.getTabs(group);
1337
1338        speed = typeof speed == 'undefined' ? options.speed : speed;
1339
1340        $tabs.removeClass('is-active');
1341        $panes.removeClass('is-active').addClass('is-hidden').stop().slideUp(speed);
1342    };
1343    proto.getPanes = function (group) {
1344        return this.$panes.filter('[data-tabs-pane*="'+group+':"]');
1345    };
1346    proto.getTabs = function (group) {
1347        return this.$tabs.filter('[data-tabs-tab*="'+group+':"]');
1348    };
1349    proto.grouping = function () {
1350        var self = this;
1351        var $tabs = self.$tabs;
1352        var groups = self.groups;
1353
1354        $tabs.each(function (i, item){
1355            var $tab = $tabs.eq(i),
1356                attr = $tab.data('tabs-tab').split(':'),
1357                group = attr[0];
1358            if (typeof groups[group] == 'undefined') {
1359                groups[group] = [];
1360            }
1361            groups[group].push(attr[1]);
1362            $tab.data('js-tabs', attr);
1363        });
1364
1365        this.groups = groups;
1366    };
1367    proto.binding = function () {
1368        var self = this;
1369        var options = self.options;
1370
1371        this.$tabs.off('.js-tabs').on('click.js-tabs', function (e){
1372	        var $tab = $(this);
1373	        if(!$tab.data('tabs-not-prevent')){
1374		        e.preventDefault();
1375	        }
1376
1377            var attr = $tab.data('js-tabs');
1378            var group = attr[0];
1379            var id = attr[1];
1380
1381            if ( $tab.hasClass('is-active') && options.closeOpened ) {
1382                self.unselect(group);
1383                return;
1384            }
1385
1386            self.select(group, id);
1387            if ( options.hash ) {
1388                location.hash = group+':'+id;
1389            }
1390        });
1391    };
1392    proto.parseHash = function () {
1393        return location.hash.substring(1).split(':');
1394    };
1395    proto.init = function () {
1396        var self = this;
1397        var options = self.options;
1398        var hash = self.parseHash();
1399
1400        self.$panes.removeAttr('style');
1401        self.grouping();
1402        self.binding();
1403
1404        if ( options.hash ) {
1405            $(window).on('hashchange', function (e) {
1406                hash = self.parseHash();
1407                if ( self.groups[hash[0]] ) {
1408                    self.select(hash[0], hash[1], 0);
1409                }
1410            });
1411        }
1412
1413        $.each(self.groups, function (group, id){
1414            var $tabs = self.getTabs(group),
1415                $panes = self.getPanes(group),
1416                $active = $tabs.filter('.is-active');
1417
1418            if ( options.hash && hash.length && hash[0] == group ) {
1419                if ( $tabs.filter('[data-tabs-tab~="'+group+':'+hash[1]+'"]').is(':visible') && $panes.filter('[data-tabs-pane~="'+group+':'+hash[1]+'"]').length) {
1420                    self.select(group, hash[1], 0);
1421                }
1422            }
1423            else if ( $active.length && $active.is(':visible') ) {
1424                self.select($active.data('js-tabs')[0], $active.data('js-tabs')[1], 0);
1425            }
1426            else if ( options.openFirst ) {
1427                self.select($tabs.eq(0).data('js-tabs')[0], $tabs.eq(0).data('js-tabs')[1], 0);
1428            }
1429            else {
1430                $tabs.removeClass('is-active');
1431                $panes.addClass('is-hidden').hide();
1432            }
1433   
1433     });
1434    };
1435})();
1436
1437
1438$.fn.formHandle = function(options){
1439    options = options || {};
1440    this.each(function(){
1441        Lib.uniFormHandle($(this), options);
1442    });
1443};
1444
1445window.$$ = Lib;
1446})();
1447
1448
1449(function(){
1450
1451var Helper = {
1452    createTabs: function (options) {
1453        return new $$.Tabs(options);
1454    },
1455    bindPopup: function ($elems, context, live) {
1456        if ( !$.fn.arcticmodal ) return;
1457
1458        if(live){
1459
1460            $(document).on('click.open-modal', $elems, function (e){
1461                e.preventDefault();
1462                $$.openModal($($(this).data('modal')), {
1463                    closeOnEsc: true,
1464                    closeOnOverlayClick: true,
1465                    afterOpen: function (modal, $modal) {
1466                        $$.init.formPlugins($modal);
1467                    }
1468                });
1469            });
1470
1471        }else{
1472            $elems = typeof $elems === 'string' ? $($elems) : $elems;
1473            $elems.off('.open-modal').on('click.open-modal', function (e){
1474                e.preventDefault();
1475                $$.openModal($($(this).data('modal')), {
1476                    closeOnEsc: true,
1477                    closeOnOverlayClick: true,
1478                    afterOpen: function (modal, $modal) {
1479                        $$.init.formPlugins($modal);
1480                    }
1481                });
1482            });
1483        }
1484
1485    },
1486    bindModal: function (elems, context) {
1487        if ( !$.fn.arcticmodal ) return;
1488
1489        var $elems = typeof elems === 'string' ? $(elems) : elems;
1490
1491        $elems.off('.open-modal').on('click.open-modal', function (e){
1492            e.preventDefault();
1493            $$.openModal($($(this).data('modal')), {
1494                closeOnEsc: false,
1495                closeOnOverlayClick: false,
1496                afterOpen: function (modal, $modal) {
1497                    $$.init.formPlugins($modal);
1498                }
1499            });
1500        });
1501    },
1502    morph: function(n, u1, u234, u10){
1503        n = parseInt(n);
1504        n = Math.abs(n) % 100;
1505        if (n>10 && n<20) return u10;
1506        n = n % 10;
1507        if (n>1 && n<5) return u234;
1508        if (n==1) return u1;
1509        return u10;
1510    }
1511};
1512
1513window.Helper = Helper;
1514})();
1515
1516
1517$.fn.selectus = function (options) {
1518    return $(this).each(function (i, select) {
1519        var $select = $(select);
1520        if ( $select.data('selectus') ) {
1521            $select.triggerHandler('update');
1522            return;
1523        }
1524
1525        var $options = $select.children('option');
1526        var $outer = $('<div class="selectus"><div class="selectus-orig"></div><div class="selectus-input"><input type="text" name="selectus_input" value=""><div class="selectus-drop"></div></div></div>');
1527        var $input = $outer.find('input').prop('readonly', true);
1528        var prefix = $select.data('selectus-prefix');
1529        // var value_start = $options.filter('[selected]').val() || $options.eq(0).val();
1530
1531        $select.replaceWith($outer);
1532        $select.appendTo($outer.find('.selectus-orig'));
1533        $input.val($options.filter(':selected').text());
1534
1535        $select.off('.selectus').on({
1536            'change.selectus silentChange.selectus': function (e) {
1537                var text = $options.filter(':selected').text();
1538                $input.val(text == prefix || !prefix ? text : prefix +': '+ text);
1539            },
1540            'focus.selectus': function (e) {
1541                $outer.addClass('is-focus');
1542            },
1543            'blur.selectus': function (e) {
1544                $outer.removeClass('is-focus');
1545            },
1546            'update.selectus': function (e) {
1547                $select = $(this);
1548                $outer = $select.closest('.selectus');
1549                $input = $outer.find('input');
1550                $options = $select.children('option');
1551                $select.trigger('silentChange');
1552            },
1553            'destroy.selectus': function (e) {
1554                $outer.replaceWith($select.off('.selectus').data('selectus', false));
1555            },
1556            'select.selectus': function (e, data) {
1557                if ( !isNaN(data.id) ) {
1558                    $options.eq(data.id).prop('selected', true);
1559                    $select.trigger('silentChange');
1560                }
1561                else if ( data.value ) {
1562                    $options.filter(function (i, opt) {
1563                        return $options.eq(i).attr('value') == data.value;
1564                    }).prop('selected', true);
1565                    $select.trigger('silentChange');
1566                }
1567            }
1568        }).data('selectus', true);
1569
1570    });
1571};
1572
1573
1574(function (analytics) {
1575    analytics.next_prev_one = 0;
1576    analytics.next_prev_two = 0;
1577    // analytics.next_one = 0;
1578    analytics.date_one = 0;
1579    analytics.date_two = 0;
1580
1581    analytics.d_one = 0;
1582    analytics.d_two = 0;
1583
1584    analytics.aim_title_one = 0;
1585    analytics.aim_title_two = 0;
1586
1587    analytics.offset = 0;
1588    analytics.type_rebuild = 0;
1589    analytics.now_time = 0,
1590        analytics.userRegionId = 0;
1591}(window.analytics = window.analytics || {}));
1592
1593
1594$(function () {
1595
1596    var $control = $(this),
1597        $button = $control.find('.mod-one_date').find('.list-extra-button'),
1598        $analyticsEvent = $('[js-analyticsId]'),
1599        $astroChart = $('[js-astroChart]'),
1600        $astroChartTransit = $('[js-astroChartTransit]'),
1601        $ac = [],
1602        $ac_transit = [],
1603        $circle_inner = null,
1604        $league_data = $control.find('[js-service-analytics-a]');
1605
1606    analytics.userRegionId = $('body').data('user-region-id');
1607
1608    $('.range-value').each(function (index, value) {
1609        $(this).html($(this).prev('.range-slider__range').val() / 2);
1610    });
1611
1612    $astroChart.each(function () {
1613        $ac.push($(this).data('order'));
1614    });
1615
1616
1617    $astroChartTransit.each(function () {
1618        $ac_transit.push($(this).data('order'));
1619    });
1620
1621    $$.document.on('click', '.analytics-box-close', function (e) {
1622        e.preventDefault();
1623
1624        var $this = $(this);
1625        $this.parents('.list-controls-col').removeClass('is-opened');
1626    });
1627
1628    if ($('.mod-tags_ext').length) {
1629        $.ajax({
1630            url: $$.urlPrefix + '/api/buildChart/?table_tags_ext',
1631            type: 'post',
1632            dataType: 'json',
1633            // data: {id: $player_id, event_type: $circle_type, type: $type},
1634            success: function (data) {
1635                table_tags_ext(data);
1636                // makeTable(data);
1637            }
1638        });
1639    }
1640
1641    if ($astroChart.length && $analyticsEvent.length) {
1642        $.ajax({
1643            url: '/sport/' + $analyticsEvent.data('uri') + '/' + $analyticsEvent.data('id') + '/?ephemeris',
1644            type: 'post',
1645            dataType: 'json',
1646            success: function (data) {
1647                for (var key in data) {
1648                    var type = data[key]['type_chart_event'],
1649                        circle_type = data[key]['circle_type'],
1650                        dateMatchOffset = 0,
1651                        $astro_cusps_transit = [];
1652
1653                    if (type) {
1654                        var type_arr = type.split('__'),
1655                            buttonRebuild = $('[' + 'js-button-rebuild-map__' + type_arr[1] + ']');
1656
1657                        if (circle_type == 'inner') {
1658                            var $circle_inner = data[key];
1659
1660                            var serialObj = JSON.stringify([$circle_inner, "", $circle_inner['type_chart_event'], 'inner']);
1661
1662                            sessionStorage.setItem($circle_inner['type_chart_event'], serialObj);
1663
1664                            buildCircleInner($circle_inner);
1665                        }
1666
1667                        if (circle_type == 'inner_offset') {
1668                            var $circle_inner = data[key],
1669                                dateMatchOffset = data[key]['dateMatchOffset'],
1670                                dataEventOffset = dataCircleInnerOffset($circle_inner),
1671                                circle_outer_text = '';
1672                        }
1673
1674                        if (circle_type == 'outer' && $circle_inner) {
1675                            var $circle_outer = data[key],
1676                                chartDate = data[key]['chartDate'],
1677                                circle_outer_text = '';
1678
1679                            buttonRebuild.attr('data-radix-value', chartDate);
1680
1681                            circle_outer_text = "event_outer__" + type_arr[1];
1682
1683                            // var serialObj = JSON.stringify([$circle_outer, dataEventOffset , circle_outer_text, 'outer', 'transit'])
1684                            // sessionStorage.setItem(circle_outer_text, serialObj);
1685
1686                            buildCircleTransit($circle_outer, dataEventOffset, circle_outer_text);
1687                        }
1688                    }
1689                }
1690            }
1691        });
1692    }
1693
1694    if ($('#datetimepicker1').length) {
1695        var datetime_default = $('input[name^=datetimepicker]').data('datetime_default');
1696
1697        if (datetime_default) {
1698            var date_timestamp = datetime_default.split('.');
1699            date_timestamp = new Date(date_timestamp[2] + '-' + date_timestamp[1] + '-' + date_timestamp[0]);
1700        } else {
1701            date_timestamp = new Date();
1702        }
1703
1704        $('#datetimepicker1').datetimepicker({
1705            defaultDate: date_timestamp,
1706            format: 'DD.MM.YYYY',
1707            locale: 'ru',
1708            inline: true,
1709            sideBySide: true,
1710        });
1711
1712        if (datetime_default) {
1713            $button.find('span').text(datetime_default);
1714        }
1715
1716        $("#datetimepicker1").on("dp.change", function (e) {
1717            var calendar_date = $('#datetimepicker1').data('DateTimePicker').date().format('DD.MM.YYYY');
1718
1719            $('#datetimepicker_input').val(calendar_date);
1720            $button.find('span').text(calendar_date);
1721        });
1722    }
1723
1724    setTimeout(function () {
1725        $("#analytics-aspects g").powerTip();
1726    }, .5)
1727
1728    $$.document.on('click', '[js-checkbox-offset]', function (e) {
1729        e.preventDefault();
1730        var $this = $(this),
1731            $dropbtn = $this.closest('.dropdown_content').siblings('.list-extra-button');
1732
1733        $dropbtn.text($this.text());
1734        $control.find('.dropdown_content').removeClass('is-opened');
1735    });
1736
1737    $$.document.on('click', '[js-service-analytics-a]', function (e) {
1738        e.preventDefault();
1739        var $this = $(this),
1740            $dropbtn = $this.closest('.dropdown_content').siblings('.list-button');
1741
1742        if ($dropbtn.attr('id') != 'dropdownAspects') {
1743            $dropbtn.text($this.text());
1744            $dropbtn.removeClass('button-arrow-down-rotate').addClass('button-arrow-down');
1745            $control.find('.dropdown_content').removeClass('is-opened');
1746        }
1747    });
1748
1749    $$.document.on('click', '[js-service-analytics]', function (e) {
1750        e.preventDefault();
1751
1752        var $offset = $(this).hasClass("list-extra-button__offset"),
1753            button = $(this);
1754        if ($(this).hasClass("list-button")) {
1755            var $drop_cont = $(this).siblings('.dropdown_content');
1756
1757            $drop_cont.toggleClass('is-opened');
1758            if ($drop_cont.hasClass('is-opened')) {
1759                $offset ? $(this).addClass('list-extra-button__hide') 
1759: $(this).addClass('button-arrow-down-rotate').removeClass('button-arrow-down');
1760            } else {
1761                $offset ? $(this).removeClass('list-extra-button__hide') : $(this).removeClass('button-arrow-down-rotate').addClass('button-arrow-down');
1762            }
1763            if (button.attr('id') == 'dropdownAspects') {
1764                if (button.hasClass('button-arrow-down-rotate')) {
1765                    button.text('Поиск...')
1766                } else {
1767                    button.text('Аспекты')
1768                }
1769            }
1770        }
1771        if ($(this).hasClass("list-extra-button")) {
1772            var $drop_cont = $(this).siblings('.dropdown_content');
1773            $drop_cont.toggleClass('is-opened');
1774            if ($drop_cont.hasClass('is-opened')) {
1775                $offset ? $(this).addClass('list-extra-button__hide') : $(this).addClass('button-arrow-down-rotate').removeClass('button-arrow-down');
1776            } else {
1777                $offset ? $(this).removeClass('list-extra-button__hide') : $(this).removeClass('button-arrow-down-rotate').addClass('button-arrow-down');
1778            }
1779        }
1780    });
1781
1782    $$.document.on('click', '#button_car_pl', function (e) {
1783        e.preventDefault();
1784        var $this = $(this),
1785            $player_id = $this.data('id'),
1786            panel = $('.chart-panel'),
1787            // container = $this.closest('.lineups-container');
1788            container = $('.lineups-container');
1789
1790        container.find('tr').each(function () {
1791            $(this).removeClass('active_lineup');
1792        });
1793        $this.closest('.lineups-container-str').find('tr').each(function () {
1794            $(this).removeClass('active_lineup');
1795        });
1796
1797        $this.closest('tr').addClass('active_lineup');
1798
1799        $.ajax({
1800            url: $$.urlPrefix + '/api/buildChart/?double_chart',
1801            type: 'post',
1802            dataType: 'json',
1803            data: {
1804                id: $player_id,
1805                event_type: 'event_player',
1806                type: 'players',
1807                time_offset: $('[js-analyticsId]').data('time_offset')
1808            },
1809            success: function (data) {
1810                if (data) {
1811                    var returnObjs = JSON.parse(sessionStorage.getItem('event__1')),
1812                        returnObj1 = returnObjs[0],
1813                        dataEventOffset = JSON.parse(sessionStorage.getItem('dataEventOffset'));
1814
1815                    $('.chart-panel_button').each(function (key, value) {
1816                        $(this).attr('data-radix-value', data[1]);
1817                    });
1818
1819                    if (panel.height() > 0) {
1820                        panel.find('.event_player').empty();
1821                        panel.find('.element_chart_row_pl').empty();
1822                    } else {
1823                        panel.css('max-height', panel.prop('scrollHeight') + 800);
1824                    }
1825
1826                    panel.find('.element_chart_row__table').attr('data-id', $player_id);
1827                    panel.find('.element_chart_row_pl').prepend(build_table_player(data[2]));
1828
1829                    buildCircleTransit(data[0], dataEventOffset, 'event_player');
1830
1831                    var windowWidth = $(window).width();
1832                    if (windowWidth > 640) {
1833                        $('html, body').animate({
1834                            scrollTop: $(".chart-panel").offset().top - 70
1835                        }, 500);
1836                    }
1837
1838                }
1839            }
1840        });
1841
1842    });
1843
1844    $('[js-get-composition]').on('click', function (e) {
1845        e.preventDefault();
1846
1847        $.ajax({
1848            url: $$.urlPrefix + '/api/getComposition/?composition',
1849            type: 'post',
1850            dataType: 'json',
1851            data: {id: $('[js-analyticsId]').data('id')},
1852            success: function (response) {
1853                if (response.success) {
1854                    location.reload();
1855                }
1856            }
1857        });
1858    });
1859
1860    $('[js-get_match_day]').on('click', function (e) {
1861        e.preventDefault();
1862        var $this = $(this),
1863            param_query;
1864
1865        switch ($this.data('match_true')) {
1866            case 1:
1867                param_query = 'delete_match_day';
1868                break;
1869            case 0:
1870                param_query = 'set_match_day';
1871                break;
1872        }
1873        $.ajax({
1874            url: $$.urlPrefix + '/api/setMatchDay/?' + param_query,
1875            type: 'post',
1876            dataType: 'json',
1877            data: {id: $('[js-analyticsId]').data('id'), id_prop: $this.data('id_prop')},
1878            success: function (response) {
1879                if (response.success) {
1880                    // $this.text(response.text);
1881                    // $this.attr('data-match_true', response.match_true);
1882                    location.reload();
1883                }
1884            }
1885        });
1886    });
1887
1888});
1889
1890function table_tags_ext(data) {
1891
1892    var data_arr = data['data'],
1893        all = data['all'];
1894    var columns = 3;
1895
1896    if ($(window).width() <= 400) {
1897        columns = 1;
1898    } else if ($(window).width() <= 580) {
1899        columns = 2;
1900    }
1901    var res_is_active = all ? 'is-active' : '';
1902    var tags = "<a href='#' class='list-filter-tag " + res_is_active + "' data-value='all' js-filter-reset>Все</a>"
1903
1904    for (var key in data_arr) {
1905        var arr = data_arr[key];
1906        tags += "<h4 class='list-extra-filter-title'>" + key + "</h4>";
1907
1908        var q = 0,
1909            i = 0,
1910            tags_class = 'list-filter-tag',
1911            len = Object.keys(arr).length;
1912
1913        tags += "<table class='tags_ext_table'>";
1914        for (var k in arr) {
1915            if (i == 0 || q % columns == 0) {
1916                tags += "<tr>";
1917            }
1918
1919            if (arr[k]['prec_id'] && !all) {
1920                tags_class = '"list-filter-tag is-active"';
1921            } else {
1922                tags_class = '"list-filter-tag"';
1923            }
1924
1925            tags += "<td class='tags_ext_table-col'>";
1926            tags += "<a href='#' class=" + tags_class + " js-filter-value data-value='" + k + "'>";
1927            tags += "<span id='analytics-aspects' style='font-family:AstrologyPro;' >" + arr[k]['symbol'] + "</span>" + arr[k]['name'];
1928            tags += "</a>";
1929            tags += "</td>";
1930
1931            if (i != 0) {
1932                if (i == len && (q + 1) % columns == 0) {
1933                    for (var i = 0; i < (columns - (i / columns)); i++) {
1934                        tags += "<td>&nbsp;</td>";
1935                    }
1936                }
1937            }
1938            if (i != 0) {
1939                if (i == len || (q + 1) % columns == 0) {
1940                    tags += "</tr>";
1941                }
1942            }
1943
1944            q++;
1945            i++;
1946        }
1947        tags += "</table>";
1948    }
1949
1950    $('.mod-tags_ext').find('.list-filter').empty();
1951    $('.mod-tags_ext').find('.list-filter').append(tags);
1952
1953}
1954
1955function dataCircleInnerOffset($circle_inner) {
1956    var $astro_cusps_inner_offset = [];
1957
1958    for (var key in $circle_inner['cuspsData']) {
1959        $astro_cusps_inner_offset.push(parseFloat($circle_inner['cuspsData'][key]));
1960    }
1961
1962    var dataEventOffset = {
1963        "planets": JSON.parse(JSON.stringify($circle_inner['planetData'])),
1964        "cusps": $astro_cusps_inner_offset,
1965        "typechart": $circle_inner['typechart'],
1966        "aspecthouse": $circle_inner['aspecthouse'],
1967        "zet_str": $circle_inner['zet_str'],
1968        "gradus": 1
1969    };
1970
1971    sessionStorage.setItem('dataEventOffset', JSON.stringify(dataEventOffset));
1972
1973    return dataEventOffset;
1974}
1975
1976function date_timestamp($date) {
1977    var date_timestamp = $date.split('.');
1978    date_timestamp = Date.parse(date_timestamp[2] + '-' + date_timestamp[1] + '-' + date_timestamp[0] + 'T00:00:00.417Z');
1979    date_timestamp = date_timestamp.toString().slice(0, -3);
1980
1981    return date_timestamp;
1982}
1983
1984function CopyText(zet) {
1985
1986    var inp = document.createElement('input');
1987    document.body.appendChild(inp);
1988    inp.value = zet;
1989    inp.select();
1990    document.execCommand('copy', false);
1991    inp.remove();
1992}
1993
1994$(function () {
1995
1996
1997    $$.document.on('click', '#button_zet', function (e) {
1998        e.preventDefault();
1999
2000        var $this = $(this),
2001            $message = $this.data('zet_message'),
2002            $message_saved = $this.next('.zet-saved');
2003
2004        $message_saved.animate({
2005            opacity: 1
2006        }, 300);
2007
2008        CopyText($message);
2009
2010        setTimeout(function () {
2011            $message_saved.stop().animate({
2012                opacity: 0
2013            }, 150);
2014        }, 1500);
2015    });
2016
2017    $(document).ready(function () {
2018        $("#content div.tab").hide(); // Скрываем содержание
2019
2020        $(".tabs-container").each(function () {
2021            $(this).find("#tabs-chart li:first").find('a').attr("id", "current");
2022            $(this).find("#content div:first").fadeIn();
2023        });
2024
2025        $('#tabs-chart a').click(function (e) {
2026            e.preventDefault();
2027
2028            var $tabs_container = $(this).parents('.tabs-container');
2029
2030            $tabs_container.find("#content div.tab").hide(); //Скрыть все сожержание
2031            $tabs_container.find("#tabs-chart a").attr("id", ""); //Сброс ID
2032            $(this).attr("id", "current"); // Активируем закладку
2033            $tabs_container.find("#content").find('#' + $(this).attr('class')).fadeIn(); // Выводим содержание текущей закладки
2034        });
2035    });
2036
2037});
2038
2039function changedBorder() {
2040    var formObj = document.forms[0];
2041    var st = dom.parseStyle(formObj.style.value);
2042
2043    // Update border width if the element has a color
2044    if (formObj.border.value != "" && (isCssSize(formObj.border.value) || formObj.bordercolor.value != ""))
2045        st['border-width'] = cssSize(formObj.border.value);
2046    else {
2047        if (!formObj.border.value) {
2048            st['border'] = '';
2049            st['border-width'] = '';
2050        }
2051    }
2052
2053    formObj.style.value = dom.serializeStyle(st);
2054}
2055
2056$(document).ready(function () {
2057
2058    var constructor_menu = $('.constructor_menu'),
2059        pathname = location.pathname,
2060        button = constructor_menu.find('.offset-button'),
2061        offset_block_one = constructor_menu.find('.offset_block_one'),
2062        offset_block_two = constructor_menu.find('.offset_block_two'),
2063        // for_dс = constructor_menu.find('.for_dс'),
2064        for_dс = $('.for_dс'),
2065        constructor_block_but = constructor_menu.find('.constructor_block_but');
2066
2067    for_dс.each(function (e) {
2068        $(this).css('display', 'none');
2069    });
2070
2071    offset_block_two.css('display', 'none');
2072    constructor_block_but.css('display', 'none');
2073    // for_dс.css('display', 'none');
2074
2075    if (pathname == '/constructor/') {
2076        $('html, body').css({
2077            // overflow: 'hidden',
2078            height: '100vh'
2079        });
2080
2081        var sidebar_constructor = $('.sidebar_constructor');
2082
2083        if (sidebar_constructor.length > 0) {
2084            $$.getSelect();
2085
2086            // var button_c = sidebar_constructor.find('.offset-button');
2087            // button_c.on('click', function (e) {
2088            //     e.preventDefault();
2089            //
2090            // });
2091            var button_c = sidebar_constructor.find('.offset-button');
2092            button_c.on('click', function (e) {
2093                e.preventDefault();
2094
2095                var input_elem = constructor_menu.find('input[name*=input_house_card_time]'),
2096                    offset = input_elem.val(),
2097                    id_element = $(this).attr('id'),
2098                    type_botton = $(this).attr('data-type_rebuild');
2099
2100                $(this).closest('.sidebar__nav-list').find('li').each(function () {
2101                    $(this).removeClass('active');
2102                });
2103
2104                $(this).closest('.fake-button').toggleClass("active");
2105
2106                analytics.next_prev_one = 0;
2107                analytics.next_prev_two = 0;
2108
2109                switch (id_element) {
2110                    case 'prev_one':
2111                        analytics.next_prev_one = -1;
2112                        break;
2113                    case 'next_one':
2114                        analytics.next_prev_one = +1;
2115                        break;
2116                    case 'prev_two':
2117                        analytics.next_prev_two = -1;
2118                        break;
2119                    case 'next_two':
2120                        analytics.next_prev_two = +1;
2121                        break;
2122                }
2123
2124                if (type_botton) {
2125                    analytics.type_rebuild = type_botton;
2126                }
2127
2128                analytics.offset = offset;
2129                build_constructor();
2130            });
2131
2132            $('.select-items').on('click', function (e) {
2133                e.preventDefault();
2134
2135                if (!$(this).hasClass('mod_nod')) {
2136                    build_constructor();
2137                }
2138            });
2139
2140            // set_variables();
2141            build_constructor_new();
2142        }
2143    } else {
2144        if (constructor_menu.length > 0) {
2145            $$.getSelect();
2146
2147            button.on('click', function (e) {
2148                e.preventDefault();
2149
2150                var input_elem = constructor_menu.find('input[name*=input_house_card_time]'),
2151                    offset = input_elem.val(),
2152                    id_element = $(this).attr('id'),
2153                    type_botton = $(this).attr('data-type_rebuild');
2154
2155                analytics.next_prev_one = 0;
2156                analytics.next_prev_two = 0;
2157
2158                switch (id_element) {
2159                    case 'prev_one':
2160                        analytics.next_prev_one = -1;
2161                        break;
2162                    case 'next_one':
2163                        analytics.next_prev_one = +1;
2164                        break;
2165                    case 'prev_two':
2166                        analytics.next_prev_two = -1;
2167                        break;
2168                    case 'next_two':
2169                        analytics.next_prev_two = +1;
2170                        break;
2171                }
2172
2173                if (type_botton) {
2174                    analytics.type_rebuild = type_botton;
2175                }
2176
2177                analytics.offset = offset;
2178                build_constructor();
2179
2180            });
2181
2182            $('.select-items').on('click', function (e) {
2183                e.preventDefault();
2184
2185                if (!$(this).hasClass('mod_nod')) {
2186                    build_constructor();
2187                }
2188            });
2189
2190            build_constructor();
2191        }
2192    }
2193
2194
2195    $('.menu__dropdown').on('click', function (e) {
2196        e.preventDefault();
2197        $(this).next('.submenu').toggle();
2198        $(this).toggleClass('active');
2199    })
2200
2201    // $('.menu__dropdown_a').on('click', function (e) {
2202    $$.document.on('click', '.menu__dropdown_a', function (e) {
2203        e.preventDefault();
2204
2205        var $this = $(this),
2206            type_botton = $this.attr('data-value'),
2207            now_time = $this.attr('data-now_time');
2208        analytics.now_time = now_time == 1 ? 1 : 0;
2209        analytics.next_prev_one = 0;
2210        analytics.next_prev_two = 0;
2211
2212        if(type_botton != 0){
2213            if (type_botton == 1) {
2214                $('.menu').find('.chart_one').removeClass('chart_one');
2215                $this.addClass('chart_one');
2216                map_change(type_botton);
2217            } else if (type_botton == 2) {
2218                if ($('.menu').find('.chart_one').length != 0) {
2219                    if ($this.hasClass('chart_two')) {
2220                        analytics.type_rebuild = 0;
2221                        $('.menu').find('.chart_two').removeClass('chart_two');
2222                        for_dс.css('display', 'none');
2223                    } else {
2224                        $('.menu').find('.chart_two').removeClass('chart_two');
2225                        for_dс.css('display', 'flex');
2226                        $this.toggleClass('chart_two');
2227                    }
2228                }
2229                map_change(type_botton);
2230            }
2231        }
2232        // updating_variables(true);
2233        build_constructor();
2234    })
2235})
2236
2237function build_constructor() {
2238    var type_house = $('.constructor_menu').find('#house_card_constructor').find('.same-as-selected'),
2239        type_house_val = 1;
2240
2241    if (type_house.length > 0) {
2242        type_house_val = type_house.attr('value');
2243    }
2244
2245    if (analytics.next_prev_one != 0) {
2246        var el_arr_one = JSON.parse(analytics.d_one);
2247        analytics.date_one = changeTime(el_arr_one['date'], analytics.offset, analytics.next_prev_one);
2248        el_arr_one['date'] = analytics.date_one;
2249        analytics.d_one = JSON.stringify(el_arr_one);
2250    }
2251
2252    if (analytics.next_prev_two != 0) {
2253        var el_arr_two = JSON.parse(analytics.d_two);
2254        analytics.date_two = changeTime(el_arr_two['date'], analytics.offset, analytics.next_prev_two);
2255        el_arr_two['date'] = analytics.date_two;
2256        analytics.d_two = JSON.stringify(el_arr_two);
2257    }
2258
2259    updating_variables();
2260
2261    $.ajax({
2262        url: $$.urlPrefix + '/api/buildChart/?constructor',
2263        type: 'post',
2264        dataType: 'json',
2265        data: {
2266            // data_one: data_one,
2267            // data_two: data_two,
2268            data_one: analytics.d_one,
2269            data_two: analytics.d_two,
2270            type_house_val: type_house_val,
2271            date_one: analytics.date_one,
2272            date_two: analytics.date_two,
2273            type_rebuild: analytics.type_rebuild
2274        },
2275        success: function (data) {
2276            if (data['data_one'] && !data['data_two']) {
2277                var $circle_inner = data['data_one'];
2278                var serialObj = JSON.stringify([$circle_inner, "", $circle_inner['type_chart_event'], 'inner']);
2279                sessionStorage.setItem($circle_inner['type_chart_event'], serialObj);
2280                var one_zet_str = JSON.parse(data['data_one']['zet_str']);
2281                buildCircleInner($circle_inner);
2282
2283                getMatchHeadlines('one', one_zet_str);
2284            } else if (data['data_one'] && data['data_two']) {
2285                var one_zet_str = JSON.parse(data['data_one']['zet_str']);
2286                var two_zet_str = JSON.parse(data['data_two']['zet_str']);
2287
2288                getMatchHeadlines('one', one_zet_str)
2289                getMatchHeadlines('two', two_zet_str)
2290
2291                buildCircleTransit_v2(data['data_one'], data['data_two'], 'event__constructor');
2292            }
2293        }
2294    });
2295}
2296
2297function build_constructor_new(){
2298    var type_house = $('.constructor_menu').find('#house_card_constructor').find('.same-as-selected'),
2299        type_house_val = 1;
2300
2301    if (type_house.length > 0) {
2302        type_house_val = type_house.attr('value');
2303    }
2304
2305    updating_variables();
2306
2307    $.ajax({
2308        url: $$.urlPrefix + '/api/buildChart/?constructor_new',
2309        type: 'post',
2310        dataType: 'json',
2311        data: {
2312            type_house_val: type_house_val
2313        },
2314        success: function (data) {
2315            if (data['data_one'] && !data['data_two']) {
2316                var $circle_inner = data['data_one'];
2317                var serialObj = JSON.stringify([$circle_inner, "", $circle_inner['type_chart_event'], 'inner']);
2318                sessionStorage.setItem($circle_inner['type_chart_event'], serialObj);
2319                var one_zet_str = JSON.parse(data['data_one']['zet_str']);
2320
2321
2322                var elem_one = $('.menu').find('.chart_one'),
2323                    // data_one = elem_one.closest('.data-value').attr('data-value'),
2324                    type_botton = elem_one.attr('data-value');
2325
2326                // if (typeof analytics.d_one === 'undefined' || analytics.d_one == 0) {
2327                //     analytics.d_one = data_one;
2328                // }
2329
2330                map_change(type_botton)
2331                buildCircleInner($circle_inner);
2332                getMatchHeadlines('one', one_zet_str)
2333            } else if (data['data_one'] && data['data_two']) {
2334                var one_zet_str = JSON.parse(data['data_two']['zet_str']);
2335                getMatchHeadlines('two', one_zet_str)
2336                buildCircleTransit_v2(data['data_one'], data['data_two'], 'event__constructor');
2337            }
2338        }
2339    });
2340}
2341function getMatchHeadlines(n, zet_str) {
2342    // var mh_header = $('#match_headlines_item__'+n+'').
2343
2344    var time = zet_str.date_str.split(' ');
2345    var place = zet_str.place.split(' ');
2346    var sz = "" + zet_str.title + "; " + time[0] + "; " + time[1] + "; 0; " + place[0] + "; " + zet_str.lat + "; " + zet_str.lng + "; —; ;";
2347
2348    var title = n == 'one' ? analytics.aim_title_one : analytics.aim_title_two;
2349
2350    var tags = "<div class='mh_item_element'>" +
2351        "<div class='mh_header'>" + title + "</div>" +
2352        "<div class='mh_header_time'>" +
2353        "<button data_type="+n+" type='submit' id='set_time_free' js-set_time title='Установить дату сейчас'></button>" +
2354        "<div class='mh_time'>" + zet_str.date_str + " GMT" + zet_str.tz + "</div>" +
2355        "</div> " +
2356        "</div>" +
2357        "<div class='mh_item_element mh_item_element__flex'>" +
2358        "<button data_type="+n+" type='submit' id='set_place_free' js-set_place title='Установить дату сейчас'></button>" +
2359        "<div class='mh_region'>" + zet_str.place + "</div>" +
2360        // "<div class='mh_region_coordinates'>20Т23 38К23</div>" +
2361        "</div>" +
2362        "<div class='mh_item_element mh_item_element_but'>" +
2363        "<button button='transparent' id='button_zet' js-tip " +
2364        "title='При нажатии данные копируются в буфер обмена. Затем просто вставьте данные в Zet через форму исходных данных.' " +
2365        "data-zet_message='" + sz + "'>Zet</button>" +
2366        "</div>";
2367
2368    $('#match_headlines_item__' + n + '').empty();
2369    $('#match_headlines_item__' + n + '').append(tags);
2370}
2371
2372function changeTime(timestamp, offset, prev) {
2373
2374    var d = new Date(timestamp * 1000);
2375
2376    if (offset == 31556926) {
2377        d.setFullYear(d.getFullYear() + prev);
2378    } else if (offset == 2629743) {
2379        d.setMonth(d.getMonth() + prev);
2380    } else if (offset == 86400) {
2381        d.setDate(d.getDate() + prev);
2382    } else if (offset == 3600) {
2383        d.setHours(d.getHours() + prev);
2384    } else if (offset == 300) {
2385        d.setMinutes(d.getMinutes() + 5 * prev);
2386    }
2387
2388    yyyy = d.getFullYear();
2389    mm = ('0' + (d.getMonth() + 1)).slice(-2);
2390    dd = ('0' + d.getDate()).slice(-2);
2391    hh = ('0' + d.getHours()).slice(-2);
2392    min = ('0' + d.getMinutes()).slice(-2);
2393    ss = ('0' + d.getSeconds()).slice(-2);
2394
2395    str = mm + ' ' + dd + ' ' + yyyy + ' ' + hh + ':' + min + ':' + ss;
2396
2397    time = Date.parse(str) / 1000;
2398
2399    return time;
2400}
2401
2402function map_change(type_botton){
2403    var elem_one = $('.menu').find('.chart_one'),
2404        data_one = elem_one.closest('.data-value').attr('data-value'),
2405
2406        elem_two = $('.menu').find('.chart_two'),
2407        data_two = elem_two.closest('.data-value').attr('data-value');
2408
2409    var aim_one = elem_one.closest('.articles-item-main');
2410    var aim_two = elem_two.closest('.articles-item-main');
2411    if(aim_one.length){
2412        analytics.aim_title_one = aim_one.find('.articles-item-title').text()
2413    }
2414    if(aim_two.length){
2415        analytics.aim_title_two = aim_two.find('.articles-item-title').text()
2416    }
2417
2418    if (type_botton == 1) {
2419        analytics.d_one = data_one;
2420    }
2421    if (type_botton == 2) {
2422        analytics.d_two = data_two;
2423    }
2424}
2425
2426function updating_variables($update = false) {
2427    if (typeof analytics.d_one !== 'undefined' || analytics.d_one == 0) {
2428        var date_one = JSON.parse(analytics.d_one)['date'];
2429        if ($update) {
2430            analytics.date_one = date_one;
2431        }
2432        if (analytics.date_one == 0) {
2433            analytics.date_one = date_one;
2434        }
2435    }
2436
2437    if (typeof analytics.d_two !== 'undefined' || analytics.d_two == 0) {
2438        var date_two = JSON.parse(analytics.d_two)['date'];
2439        if ($update) {
2440            analytics.date_two = date_two;
2441        }
2442        if (analytics.date_two == 0) {
2443            analytics.date_two = date_two;
2444        }
2445    }
2446
2447}
2448
2449//Constructor
2450$(function () {
2451
2452    $$.openSetUserModal = function () {
2453
2454        $$.openModal({
2455            url: $$.urlPrefix + '/api/userSetting/?user_setting',
2456            // data: {horarId: horarId},
2457            closeOnEsc: false,
2458            closeOnOverlayClick: false,
2459            cssModClasses: 'mod-constructor',
2460            afterOpen: function (modal, $modal, modalResponse) {
2461
2462                var $body = $('body');
2463                $body.on('submit', 'form[action="/office/settings/horoscope/?horoscope-checkbox-save"]', function (e) {
2464                    e.preventDefault();
2465                    $$.uniFormSubmit($(this), {
2466                        beforeData: function ($form) {
2467                            $form.stop().animate({opacity: 0.8}, 150);
2468
2469                            $form.find('.office-data-saved')
2470                                .animate({
2471                                    opacity: 0
2472                                }, 150);
2473                        },
2474                        afterData: function ($form, data) {
2475                            $form.stop().animate({opacity: 1}, 150);
2476                        },
2477                        afterSuccess: function (data, $form) {
2478                            var $list = $(data.cu_checkbox);
2479                            $form.closest('.office-house_cards-list').html($list);
2480                            var $message = $list.find('.office-data-saved');
2481                            $message.animate({
2482                                opacity: 1
2483                            }, 300);
2484
2485                            setTimeout(function () {
2486                                $message.animate({
2487                                    opacity: 0
2488                                }, 150, function () {
2489                                    $message.remove()
2490                                });
2491                            }, 3000);
2492                        }
2493                    });
2494                });
2495
2496                $body.on('submit', 'form[action="/office/settings/horoscope/?horoscope-planet-save"]', function (e) {
2497                    e.preventDefault();
2498                    $$.uniFormSubmit($(this), {
2499                        beforeData: function ($form) {
2500                            $form.stop().animate({opacity: 0.8}, 150);
2501
2502                            $form.find('.office-data-saved')
2503                                .animate({
2504                                    opacity: 0
2505                                }, 150);
2506                        },
2507                        afterData: function ($form, data) {
2508                            $form.stop().animate({opacity: 1}, 150);
2509                        },
2510                        afterSuccess: function (data, $form) {
2511                            var $list = $(data.cu_widgets);
2512                            $form.closest('.office-house_cards-list').html($list);
2513                            var $message = $list.find('.house_cards-item-saved');
2514                            $message.animate({
2515                                opacity: 1
2516                            }, 300);
2517
2518                            setTimeout(function () {
2519                                $message.animate({
2520                                    opacity: 0
2521                                }, 150, function () {
2522                                    $message.remove()
2523                                });
2524                            }, 3000);
2525                        }
2526                    });
2527                });
2528
2529                $body.on('submit', 'form[action="/office/settings/horoscope/?aspects-save"]', function (e) {
2530                    e.preventDefault();
2531
2532                    $$.uniFormSubmit($(this), {
2533                        beforeData: function ($form) {
2534                            $form.stop().animate({opacity: 0.8}, 150);
2535
2536                            $form.find('.office-data-saved')
2537                                .animate({
2538                                    opacity: 0
2539                                }, 150);
2540                        },
2541                        afterData: function ($form, data) {
2542                            $form.stop().animate({opacity: 1}, 150);
2543                        },
2544                        afterSuccess: function (data, $form) {
2545                            var $list = $(data.cu_widgets);
2546                            $form.closest('.office-house_cards-list').html($list);
2547                            var $message = $list.find('.house_cards-item-saved');
2548                            $message.animate({
2549                                opacity: 1
2550                            }, 300);
2551
2552                            setTimeout(function () {
2553                                $message.animate({
2554                                    opacity: 0
2555                                }, 150, function () {
2556                                    $message.remove()
2557                                });
2558                            }, 3000);
2559                        }
2560                    });
2561                });
2562
2563            },
2564            beforeClose: function () {
2565                build_constructor();
2566                // $('.select-region-holder').remove();
2567            }
2568        });
2569    };
2570
2571    $$.openSetTimeFree = function (data) {
2572
2573        // var data_arr = JSON.parse(data);
2574
2575        $$.openModal({
2576            url: $$.urlPrefix + '/api/userSetting/?set_time_free',
2577            data: {data_arr: data},
2578            closeOnEsc: false,
2579            closeOnOverlayClick: false,
2580            cssModClasses: 'mod-constructor',
2581            afterOpen: function (modal, $modal, modalResponse) {
2582                var data_arr = JSON.parse(data),
2583                    date_timestamp = new Date(data_arr['date'] * 1000);
2584
2585                $$.setDatetimePicker(date_timestamp);
2586
2587                $('.dt_free form').formHandle({
2588                    beforeSubmit: function () {
2589                        $('.determine-time-result').hide(300);
2590                        $('.determine-time-result_table').empty();
2591
2592                        $('.determine-time-result__admin').hide(300);
2593                        $('.determine-time-result_table__admin').empty();
2594                    },
2595                    afterSuccess: function (response) {
2596                        var id_form = $('.dt_free').attr('data-id'),
2597                            menu = $('.element_con__meny');
2598
2599                        menu.find('li').each(function () {
2600                            var val_el = $(this).attr('data-value');
2601
2602                            if (val_el) {
2603                                var val_el_arr = JSON.parse(val_el);
2604                                if (val_el_arr['id'] == id_form) {
2605                                    val_el_arr['date'] = response.dt;
2606                                    val_el_arr['rid'] = response.rid;
2607
2608                                    $(this).attr('data-value', JSON.stringify(val_el_arr));
2609                                }
2610                            }
2611                        });
2612
2613                        $('.determine-time-result').show(600);
2614                        $('.determine-time-result__admin').show(600);
2615                        $('.svg-container').css('padding-bottom', '100%');
2616                        $modal.arcticmodal('close');
2617                    }
2618                });
2619            },
2620            beforeClose: function () {
2621                // updating_variables(true);
2622                build_constructor();
2623            }
2624        });
2625    };
2626
2627    $('[js-set_user]').on('click', function (e) {
2628        e.preventDefault();
2629        $$.openSetUserModal();
2630    });
2631
2632    $('[js-set_time_free]').on('click', function (e) {
2633        e.preventDefault();
2634        var data = $(this).closest('.data-value').attr('data-value');
2635        console.log(data);
2636        $$.openSetTimeFree(data);
2637    });
2638
2639    $$.document.on('click', '[js-set_time]', function (e) {
2640        e.preventDefault();
2641        var data_type = $(this).attr('data_type');
2642
2643        change_array(data_type, ['now_time:1']);
2644        build_constructor();
2645    });
2646
2647    $$.document.on('click', '[js-set_place]', function (e) {
2648        e.preventDefault();
2649        var data_type = $(this).attr('data_type');
2650
2651        change_array(data_type, ['rid:'+analytics.userRegionId+'','now_time:0']);
2652        build_constructor();
2653    });
2654
2655
2656    $('input[name^=hidden_menu_ticker]').on('input', function(e){
2657        e.preventDefault();
2658
2659        let checkboxStatus = $(this).prop('checked')
2660        if(checkboxStatus == true){
2661            $('#modal_constructor').show();
2662        }else {
2663            $('#modal_constructor').hide();
2664        }
2665
2666    });
2667
2668    $('#modal_constructor').hide();
2669
2670    // if ($('.hidden-menu').length) {
2671    //     $$.document.on('click', '[js-hm_services]', function (e) {
2672    //         e.preventDefault();
2673    //
2674    //         let languageSelector = $(this).next();
2675    //
2676    //         $(this).toggleClass('is-open');
2677    //         toggleARIA(languageSelector, 'aria-expanded');
2678    //         toggleARIA(languageSelector, 'aria-hidden');
2679    //
2680    //         console.log($(this).next());
2681    //     });
2682    // }
2683});
2684
2685function change_array(data_type, $arr){
2686    if(data_type == 'one'){
2687        var k_el = $arr[0].split(':'),
2688            el_arr_one = JSON.parse(analytics.d_one);
2689        el_arr_one[k_el[0]] = k_el[1];
2690        analytics.d_one = JSON.stringify(el_arr_one);
2691        // for (var k in $arr) {
2692        //     var k_el = $arr[k].split(':'),
2693        //         el_arr_one = JSON.parse(analytics.d_one);
2694        //     el_arr_one[k_el[0]] = k_el[1];
2695        //     analytics.d_one = JSON.stringify(el_arr_one);
2696        //     console.log(analytics.d_one);
2697        // }
2698    }else if(data_type == 'two'){
2699        var k_el = $arr[0].split(':'),
2700            el_arr_two = JSON.parse(analytics.d_two);
2701        el_arr_two[k_el[0]] = k_el[1];
2702        analytics.d_two = JSON.stringify(el_arr_two);
2703        // for (var k in $arr) {
2704        //     var k_el = $arr[k].split(':'),
2705        //         el_arr_two = JSON.parse(analytics.d_two);
2706        //     el_arr_two[k_el[0]] = k_el[1];
2707        //     analytics.d_two = JSON.stringify(el_arr_two);
2708        // }
2709    }
2710}
2711
2712
2713$(document).ready(function () {
2714    // DOM variables
2715    let languageDesktopButton = $('.extra-content__language'),
2716        hamburguerMenu = $('.menu'),
2717        languageMobileButton = $('.language'),
2718        languageSelector = '.extra-content__language-selector';
2719
2720    $('[js-set_userrr]').on('click', function (e) {
2721        e.preventDefault();
2722
2723        $('.extra-content__language').toggleClass('is-open');
2724    });
2725});
2726
2727// Toggle ARIA attributes
2728function toggleARIA(selector, ARIA) {
2729    selector.attr(ARIA, function (i, attr) {
2730        return attr == 'true' ? 'false' : 'true';
2731    });
2732}
2733
2734$(function () {
2735    if($("#range1").length){
2736        let range1 = new rSlider({
2737            element: "#range1",
2738            tick: 1
2739        });
2740    }
2741    // range2 = new rSlider({
2742    //     element: "#range2",
2743    //     tick: 4
2744    // }),
2745    // range3 = new rSlider({
2746    //     element:"#range3",
2747    //     tick: 10
2748    // });
2749});
2750
2751class rSlider {
2752    constructor(args) {
2753        this.el = document.querySelector(args.element);
2754        this.min = +this.el.min || 0;
2755        this.max = +this.el.max || 100;
2756        this.step = +this.el.step || 1;
2757        this.tick = args.tick || this.step;
2758        // this.addTicks();
2759        this.dataRange = document.createElement("div");
2760        this.dataRange.className = "data-range";
2761        this.el.parentElement.appendChild(this.dataRange,this.el);
2762        this.updatePos();
2763        this.el.addEventListener("input",() => {
2764            this.updatePos();
2765        });
2766    }
2767    addTicks() {
2768        let wrap = document.createElement("div");
2769        wrap.className = "range";
2770        this.el.parentElement.insertBefore(wrap,this.el);
2771        wrap.appendChild(this.el);
2772        let ticks = document.createElement("div");
2773        ticks.className = "range-ticks";
2774        wrap.appendChild(ticks);
2775        for (let t = this.min; t <= this.max; t += this.tick) {
2776            let tick = document.createElement("span");
2777            tick.className = "range-tick";
2778            ticks.appendChild(tick);
2779            let tickText = document.createElement("span");
2780            tickText.className = "range-tick-text";
2781            tick.appendChild(tickText);
2782            tickText.textContent = t;
2783        }
2784    }
2785    getRangePercent() {
2786        let max = this.el.max,
2787            min = this.el.min,
2788            relativeValue = this.el.value - min,
2789            ticks = max - min,
2790            percent = relativeValue / ticks;
2791        return percent;
2792    }
2793    updatePos() {
2794        let percent = this.getRangePercent(),
2795            left = percent * 100,
2796            emAdjust = percent * 3;
2797        this.dataRange.style.left = `calc(${left}% - ${emAdjust}em)`;
2798        this.dataRange.innerHTML = this.el.value;
2799    }
2800}
2801
2802document.addEventListener("DOMContentLoaded", (function () {
2803
2804  let w_height = $(window).height(),
2805      w_width = $(window).width();
2806
2807  if($('.container-change').length) {
2808
2809    !function (e) {
2810      e((function () {
2811        var t = e(".change-star .star"), o = e(".change-star .star-bg"), r = 0, s = [0, 2, 1];
2812
2813        if (t !== null || o !== null) {
2814          setInterval((function () {
2815            r >= s.length && (r = 0), t.removeClass("shimmer"), o.removeClass("shimmer-bg"), t[s[r]].classList.add("shimmer"), o[s[r]].classList.add("shimmer-bg"), r++
2816          }), 5e3)
2817        }
2818      }))
2819    }(jQuery), function (e) {
2820      e((function () {
2821        var t = e(".course-item-img img");
2822        e(window).scroll((function () {
2823          t.addClass("flash"), clearTimeout(e.data(this, "scrollCheck")), e.data(this, "scrollCheck", setTimeout((function () {
2824            t.removeClass("flash")
2825          }), 500))
2826        }))
2827      }))
2828    }(jQuery);
2829    let e = document.querySelector(".container-program-img-1 img"),
2830        t = document.querySelector(".container-program-img-2 img"),
2831        o = document.querySelector(".container-program-img-3 img"), r = document.querySelector(".program-item-1"),
2832        s = document.querySelector(".program-item-2"), a = document.querySelector(".program-item-3");
2833    if (o !== null) {
2834      o.addEventListener("mousemove", (function (r) {
2835        let s = o.offsetHeight / r.layerY;
2836        s < 4.825 & s > 2.4125 && (e.parentNode.parentNode.classList.contains("show") || (i = 1, m(i)));
2837        s < 2.4125 & s > 1.7545 && (t.parentNode.parentNode.classList.contains("show") || (i = 2, m(i)));
2838        s < 1.7545 & s > 1.2697 && (o.parentNode.parentNode.classList.contains("show") || (i = 3, m(i)))
2839      }));
2840    }
2841
2842    let n = !0, c = document.querySelector(".container-program");
2843    c.onmouseover = () => {
2844      n = !1
2845    }, c.onmouseout = () => {
2846      n = !0
2847    };
2848    let i = 1;
2849
2850    function m(n) {
2851      switch (n) {
2852        case 1:
2853          document.querySelector(".container-program-img.show").classList.remove("show"), document.querySelector(".program-item.show").classList.remove("show"), e.parentNode.parentNode.classList.add("show"), r.classList.add("show");
2854          break;
2855        case 2:
2856          document.querySelector(".container-program-img.show").classList.remove("show"), document.querySelector(".program-item.show").classList.remove("show"), t.parentNode.parentNode.classList.add("show"), s.classList.add("show");
2857          break;
2858        case 3:
2859          document.querySelector(".container-program-img.show").classList.remove("show"), document.querySelector(".program-item.show").classList.remove("show"), o.parentNode.parentNode.classList.add("show"), a.classList.add("show")
2860      }
2861    }
2862
2863    setInterval(() => {
2864      1 == n && (i > 3 ? (i = 1, m(i)) : m(i), i++)
2865    }, 2e3);
2866    document.querySelector(".change-comet"), document.querySelector(".change-comet img"), document.querySelector(".change-comet1"), document.querySelector(".change-comet1 img"), document.querySelector(".change-comet2"), document.querySelector(".change-comet2 img");
2867    let l = document.querySelectorAll(".change-comet"), u = document.querySelectorAll(".change-comet img"),
2868        d = document.querySelector(".container-change"), h = d.offsetWidth, g = d.offsetHeight, p = h > g ? h : g,
2869        f = [];
2870
2871    function w() {
2872      for (let e = 0; e < l.length; e++) f[e] = [v(0, 1.5 * p), v(0, 1.5 * p), v(p / 2, p), v(p / 2, p), v(1200, 2400), v(0, 2)]
2873    }
2874
2875    w();
2876    let y = 0, timer;
2877
2878    function v(e, t) {
2879      return Math.floor(Math.random() * Math.floor(t - e) + e)
2880    }
2881
2882    timer = setInterval(() => {
2883      y++, function (e) {
2884        if (w_width < 520) {
2885          clearInterval(timer);
2886        }
2887        l.forEach((t, o) => {
2888          t.style.transform = `translate(${Math.sin((f[o][5] ? -1 : 1) * e / f[o][4]) * f[o][2] + f[o][0]}px, ${Math.cos((f[o][5] ? -1 : 1) * e / f[o][4]) * f[o][3] - f[o][1]}px)`, u[o].style.transform = `rotate(${(f[o][5] ? 1 : -1) * e / Math.PI * 180 / f[o][4]}deg) scaleX(${f[o][5] ? -1 : 1})`
2889        })
2890      }(y), y > 3600 && (l.forEach(e => {
2891        e.classList.add("transp")
2892      }), setTimeout(() => {
2893        w(), y = 0
2894      }, 3e3), setTimeout(() => {
2895        l.forEach(e => {
2896          e.classList.remove("transp")
2897        })
2898      }, 6e3))
2899    }, 5), setTimeout(() => {
2900      l.forEach(e => {
2901        e.classList.remove("transp")
2902      })
2903    }, 2e3)
2904  }
2905}));
2906
2907
2908
2909$(function(){
2910
2911    $('a.various').fancybox({
2912      maxWidth    : 800,
2913      maxHeight    : 600,
2914      fitToView    : false,
2915      width        : '70%',
2916      height        : '70%',
2917      autoSize    : false,
2918      closeClick    : true,
2919      openEffect    : 'none',
2920      closeEffect    : 'none',
2921      autoDimensions: true,
2922      padding : 0
2923    });
2924
2925  $('.articles-list.mod-about').owlCarousel({
2926    dragEndSpeed: 600,
2927    loop: true,
2928    items: 1,
2929    stagePadding: 0,
2930    margin: 33,
2931    autoHeight: false,
2932    mouseDrag: true,
2933    nav: true,
2934    pagination : true,
2935    autoplay: false
2936  });
2937});
2938
2939
2940$(function(){
2941
2942    var $exam = $('.article-exam');
2943    if(!$exam.length) return false;
2944
2945    var question;
2946
2947    function sync(data){
2948
2949        $.ajax({
2950            url: '?exam',
2951            dataType: 'json',
2952            data: $.extend({question: question}, data || {}),
2953            type: 'post',
2954            success: function(response){
2955                question = response.question;
2956                $exam.html(response.content);
2957            }
2958        });
2959
2960    }
2961
2962
2963    $exam.on('click', '[js-exam-submit]', function(e){
2964        e.preventDefault();
2965        var answer = $exam.find('input[type=radio]:checked').val() || null;
2966        if(answer || $(this).data('skip')){
2967            sync({answer: answer});
2968        }else{
2969            $$.alert('Выберите ответ');
2970        }
2971    });
2972
2973    $exam.on('click', '[js-exam-reset]', function(e){
2974        e.preventDefault();
2975        sync({reset: true});
2976    });
2977
2978    sync();
2979
2980});
2981$(function(){
2982
2983	$('[js-open-lessons-list]').on('click', function(e){
2984		var $this = $(this);
2985		$this.addClass('is-opened');
2986
2987		$('body').on('click.js-open-lessons-list', function(e){
2988			var attr = $(e.target).attr('js-open-lessons-list');
2989
2990			/*
2991			if(e.target.tagName == 'A'){
2992				$this.removeClass('is-opened');
2993			}
2994			*/
2995
2996			if(e.target.tagName != 'A' && $(e.target).attr('js-open-lessons-list') != 1 && !$(e.target).closest('[js-open-lessons-list]').length){
2997				$this.removeClass('is-opened');
2998				$('body').off('click.js-open-lessons-list');
2999			}
3000
3001		});
3002	});
3003
3004});
3005$(function(){
3006
3007    var $root = $('.article');
3008    if(!$root.length) return;
3009
3010    var $reviewButton = $root.find('[js-article-review]');
3011
3012    $reviewButton.on('click', function(){
3013        $$.openModal({
3014            url: $$.urlPrefix + '/api/articleReviewForm/',
3015            data: {article_id: $(this).data('id')},
3016            afterOpen: function(modal, $modal){
3017                $modal.find('form').formHandle({
3018                    success: function(response){
3019                        $modal.arcticmodal('close');
3020                    }
3021                });
3022            }
3023        });
3024    });
3025
3026    $$.dispatcher.bind('article-review-save', function(data){
3027        var $reviews = $(data.reviews),
3028            $button = $(data.reviewButton),
3029            $stats = $root.find('.article-stats-item.mod-purchases, .article-stats-item.mod-reviews, .article-stats-item.mod-ratings');
3030
3031        $('#reviews').find('.comments-list').find('.comments-item').remove().end().append($reviews);
3032        $reviewButton.html($button.html());
3033        $stats.remove();
3034        $root.find('.article-stats').prepend(data.stats);
3035
3036    });
3037
3038});
3039
3040$(function(){
3041
3042    var $articles = $('[js-article]');
3043    if($articles.length && document.location.hash.length > 1){
3044        var $element = $('#' + document.location.hash.substring(1));
3045        if($element.length){
3046            $$.scrollTo($element, 500, 100);
3047        }
3048    }
3049
3050    $articles.find('a[href^="#"]').on('click', function(e){
3051        e.preventDefault();
3052        var $element = $('#' + $(this).attr('href').substring(1));
3053        if($element.length){
3054            $$.scrollTo($element, 500, 150);
3055        }
3056    });
3057
3058});
3059$(function(){
3060
3061    var $consultationQuestion = $('[js-consultation]');
3062
3063    if($consultationQuestion.length){
3064        $.ajax({
3065            url: $$.urlPrefix + '/api/astroChart/?consultation',
3066            type: 'post',
3067            dataType: 'json',
3068            data: {id: $consultationQuestion.data('id')},
3069            success: function(data){
3070                buildCircleInner(data[0]);
3071            }
3072        });
3073    }
3074
3075    //Конструктор
3076
3077    // $('[js-constructor-profection]').click(function(e){
3078    //     e.preventDefault();
3079    //     var $this = $(this), type = 'profection';
3080    //
3081    //     analytics.type_rebuild = type;
3082    //     build_constructor();
3083    //
3084    // });
3085
3086    $(".rebuild_map_profection").click(function(){
3087        var $this = $(this),
3088            $type = $this.data('type'),
3089            $circle_type = $this.data('circle_type'),
3090            $player_id = $this.parents('.element_chart_row__table').data('id');
3091
3092        $.ajax({
3093            url: $$.urlPrefix + '/api/buildChart/?double_chart',
3094            type: 'post',
3095            dataType: 'json',
3096            data: {id: $player_id, event_type: $circle_type, type: $type},
3097            success: function(data){
3098                var radixValue = $this.attr("data-radix-value"),
3099                    newValue = $this.attr("data-new-value");
3100
3101                for (var key in data) {
3102                    var type = data[key]['type_chart_event'],
3103                        circle_type = data[key]['circle_type'],
3104                        typeChartEvent = data[key]['type_chart_event'],
3105                        $circle_outer_text = $this.closest('.element_chart_row').find('.element_chart_row_event').children().prop('id');
3106
3107                    if(type){
3108                        var $circle_outer_text = $this.prevAll().attr('id');
3109
3110                        if(typeChartEvent == $this.data('circle_type') ){
3111                            var $circle_outer = data[key],
3112                                dataTransit = [],
3113                                dataTransit2 = [],
3114                                $astro_cusps_outer = [],
3115                                $astro_cusps_outer2 = [],
3116                                $circle_outer_text = $this.closest('.element_chart_row').find('.element_chart_row_event').children().prop('id');
3117
3118                            for(var key in $circle_outer['cuspsData']){
3119                                $astro_cusps_outer.push(parseFloat($circle_outer['cuspsData'][key]));
3120                            }
3121                            for(var key in $circle_outer['cuspsData']){
3122                                $astro_cusps_outer2.push(parseFloat($circle_outer['cuspsData'][key]));
3123                            }
3124
3125                            var user_setting;
3126
3127                            if($circle_outer['user_setting']){
3128                                user_setting = $circle_outer['user_setting']
3129                            }else{
3130                                user_setting = false;
3131                            }
3132
3133                            dataTransit = {
3134                                "planets": JSON.parse(JSON.stringify($circle_outer['planetData'])),
3135                                "cusps": $astro_cusps_outer,
3136                                "typechart": $circle_outer['typechart'],
3137                                "aspecthouse": $circle_outer['aspecthouse'],
3138                                "dataArray": $circle_outer['dataArray'],
3139                                "circle_type": $circle_outer['circle_type'],
3140                                "houseMethods": $circle_outer['houseMethods'],
3141                                "user_aspects": $circle_outer['user_aspects'],
3142                                "user_planet": $circle_outer['user_planet'],
3143                                "gradus": 1,
3144                                "user_setting": user_setting,
3145                                "zet_str": $circle_outer['zet_str']
3146                            };
3147                            dataTransit2 = {
3148                                "planets": JSON.parse(JSON.stringify($circle_outer['planetData'])),
3149                                "cusps": $astro_cusps_outer2,
3150                                "typechart": $circle_outer['typechart'],
3151                                "aspecthouse": $circle_outer['aspecthouse'],
3152                                "dataArray": $circle_outer['dataArray'],
3153                                "circle_type": $circle_outer['circle_type'],
3154                                "houseMethods": $circle_outer['houseMethods'],
3155                                "user_aspects": $circle_outer['user_aspects'],
3156                                "user_planet": $circle_outer['user_planet'],
3157                                "gradus": 1,
3158                                "user_setting": user_setting,
3159                                "zet_str": $circle_outer['zet_str']
3160                            };
3161                        }
3162                    }
3163                }
3164
3165                if($circle_outer_text == $this.data('circle_type') && dataTransit){
3166                    var $input_orbit = $("input[name^="+$circle_outer_text+"]");
3167                    $input_orbit.attr('data-type', 'profection');
3168
3169                    var serialObj = JSON.stringify([dataTransit, dataTransit2 , $circle_outer_text, 'outer', 'profection', radixValue, newValue])
3170                    sessionStorage.setItem($circle_outer_text, seri
3170alObj);
3171
3172                    rebuild_transit(dataTransit, dataTransit2, $circle_outer_text, radixValue, newValue);
3173                    $this.toggleClass('rebuild_map_activ').siblings().removeClass('rebuild_map_activ');
3174                }
3175            }
3176        });
3177    });
3178
3179    $(".rebuild_map_transit").click(function(){
3180        var $this = $(this),
3181            $type = $this.data('type'),
3182            $circle_type = $this.data('circle_type'),
3183            $player_id = $this.parents('.element_chart_row__table').data('id');
3184
3185        $.ajax({
3186            url: $$.urlPrefix + '/api/buildChart/?double_chart',
3187            type: 'post',
3188            dataType: 'json',
3189            data: {id: $player_id, event_type: $circle_type, type: $type},
3190            success: function(data){
3191                var dataEventOffset = JSON.parse(sessionStorage.getItem('dataEventOffset'));
3192                for (var key in data) {
3193                    var type = data[key]['type_chart_event'],
3194                        circle_type = data[key]['circle_type'],
3195                        typeChartEvent = data[key]['type_chart_event'];
3196
3197                    if(type){
3198                        var $circle_outer_text = $this.closest('.element_chart_row').find('.element_chart_row_event').children().eq(0).attr('id');
3199
3200                        if(typeChartEvent == $this.data('circle_type') && dataEventOffset){
3201                            var $circle_outer = data[0];
3202                        }
3203                    }
3204                }
3205
3206                if($circle_outer_text == $this.data('circle_type') && dataEventOffset){
3207
3208                    // var serialObj = JSON.stringify([$circle_outer, dataEventOffset , $circle_outer_text, 'outer', 'transit'])
3209                    // sessionStorage.setItem($circle_outer_text, serialObj);
3210
3211                    var $input_orbit = $("input[name^="+$circle_outer_text+"]");
3212                    $input_orbit.attr('data-type', 'transit');
3213
3214                    buildCircleTransit($circle_outer, dataEventOffset, $circle_outer_text);
3215                    $this.toggleClass('rebuild_map_activ').siblings().removeClass('rebuild_map_activ');
3216                }
3217            }
3218        });
3219    });
3220
3221    $(".rebuild_map_solar").click(function(){
3222        var $this = $(this),
3223            $type = $this.data('type'),
3224            $circle_type = $this.data('circle_type'),
3225            $player_id = $this.parents('.element_chart_row__table').data('id'),
3226            radixValue2 = $this.attr("data-radix-value2");
3227
3228        $.ajax({
3229            url: $$.urlPrefix + '/api/buildChart/?double_chart_solar',
3230            type: 'post',
3231            dataType: 'json',
3232            data: {id: $player_id, event_type: $circle_type, type: $type, data2: radixValue2},
3233            success: function(data){
3234                var dataEventOffset = JSON.parse(sessionStorage.getItem('dataEventOffset'));
3235
3236                for (var key in data) {
3237                    var type = data[key]['type_chart_event'],
3238                        circle_type = data[key]['circle_type'],
3239                        typeChartEvent = data[key]['type_chart_event'];
3240
3241                    if(type){
3242                        var $circle_outer_text = $this.closest('.element_chart_row').find('.element_chart_row_event').children().eq(0).attr('id');
3243
3244                        if(typeChartEvent == $this.data('circle_type') && dataEventOffset){
3245                            var $circle_outer = data[0];
3246                        }
3247                    }
3248                }
3249
3250                if($circle_outer_text == $this.data('circle_type') && dataEventOffset){
3251                    var $input_orbit = $("input[name^="+$circle_outer_text+"]");
3252                    $input_orbit.attr('data-type', 'transit');
3253
3254                    buildCircleTransit($circle_outer, dataEventOffset, $circle_outer_text);
3255                    $this.toggleClass('rebuild_map_activ').siblings().removeClass('rebuild_map_activ');
3256                }
3257            }
3258        });
3259    });
3260
3261});
3262
3263function getSolar(){
3264    var $this = $(this),
3265        $type = $this.data('type'),
3266        $circle_type = $this.data('circle_type'),
3267        $player_id = $this.parents('.element_chart_row__table').data('id'),
3268        radixValue2 = $this.attr("data-radix-value2");
3269
3270    $.ajax({
3271        url: $$.urlPrefix + '/api/buildChart/?constructor',
3272        type: 'post',
3273        dataType: 'json',
3274        data: {id: $player_id, event_type: $circle_type, type: $type, data2: radixValue2},
3275        success: function(data){
3276            var dataEventOffset = JSON.parse(sessionStorage.getItem('dataEventOffset'));
3277
3278            for (var key in data) {
3279                var type = data[key]['type_chart_event'],
3280                    circle_type = data[key]['circle_type'],
3281                    typeChartEvent = data[key]['type_chart_event'];
3282
3283                if(type){
3284                    var $circle_outer_text = $this.closest('.element_chart_row').find('.element_chart_row_event').children().eq(0).attr('id');
3285
3286                    if(typeChartEvent == $this.data('circle_type') && dataEventOffset){
3287                        var $circle_outer = data[0];
3288                    }
3289                }
3290            }
3291
3292            if($circle_outer_text == $this.data('circle_type') && dataEventOffset){
3293                var $input_orbit = $("input[name^="+$circle_outer_text+"]");
3294                $input_orbit.attr('data-type', 'transit');
3295
3296                buildCircleTransit($circle_outer, dataEventOffset, $circle_outer_text);
3297                $this.toggleClass('rebuild_map_activ').siblings().removeClass('rebuild_map_activ');
3298            }
3299        }
3300    });
3301}
3302
3303function buildCircleInner($circle_inner, margin_chart = 70, height_chart = 800, width_chart = 800, test = ''){
3304
3305    switch (test) {
3306        case 'calibration':
3307            build_test($circle_inner['type_chart_event'], margin_chart, height_chart, width_chart);
3308            break;
3309        case '':
3310            var user_setting;
3311            var $astro_cusps_inner = [];
3312
3313            if($circle_inner['user_setting']){
3314                user_setting = $circle_inner['user_setting']
3315            }else{
3316                user_setting = false;
3317            }
3318
3319            for (var key in $circle_inner['cuspsData']) {
3320                $astro_cusps_inner.push(parseFloat($circle_inner['cuspsData'][key]));
3321            }
3322
3323            var dataEvent = {
3324                "planets": JSON.parse(JSON.stringify($circle_inner['planetData'])),
3325                "cusps": $astro_cusps_inner,
3326                "typechart": $circle_inner['typechart'],
3327                "aspecthouse": $circle_inner['aspecthouse'],
3328                "circle_type": $circle_inner['circle_type'],
3329                "houseMethods": $circle_inner['houseMethods'],
3330                "user_aspects": $circle_inner['user_aspects'],
3331                "user_planet": $circle_inner['user_planet'],
3332                "gradus": 1,
3333                "user_setting": user_setting,
3334                "zet_str": $circle_inner['zet_str']
3335            };
3336
3337            if(analytics.type_rebuild == 'profection') {
3338                let dataEvent2 = JSON.parse(JSON.stringify(dataEvent))
3339                rebuild_transit_v2(dataEvent, dataEvent2, $circle_inner['type_chart_event'], analytics.date_two, analytics.date_one);
3340            }else if(analytics.type_rebuild == 'solar_tr'){
3341                let dataEvent2 = JSON.parse(JSON.stringify(dataEvent))
3342                rebuild_transit_v2(dataEvent, dataEvent2, $circle_inner['type_chart_event'], analytics.date_two, analytics.date_one);
3343            }else{
3344                build(dataEvent, "", $circle_inner['type_chart_event'], margin_chart, height_chart, width_chart);
3345            }
3346
3347            break;
3348    }
3349
3350    // build(dataEvent, "", $circle_inner['type_chart_event'], margin_chart, height_chart, width_chart);
3351}
3352
3353function buildCircleTransit_v2($circle_one, $circle_two, circle_outer_text, margin_chart = 70, height_chart = 800, width_chart = 800){
3354    var serialObj = JSON.stringify([$circle_one, $circle_two , circle_outer_text, 'outer', 'transit']);
3355    sessionStorage.setItem(circle_outer_text, serialObj);
3356
3357    var user_setting, typechart;
3358    var $astro_cusps_outer1 = [];
3359    var $astro_cusps_outer2 = [];
3360    var $astro_cusps_outer_p = {};
3361
3362    if($circle_one['user_setting']){
3363        user_setting = $circle_one['user_setting']
3364    }else{
3365        user_setting = false;
3366    }
3367
3368    for (var key in $circle_two['cuspsData']) {
3369        $astro_cusps_outer1.push(parseFloat($circle_one['cuspsData'][key]));
3370    }
3371
3372    var dataOne = {
3373        "planets": JSON.parse(JSON.stringify($circle_one['planetData'])),
3374        "cusps": $astro_cusps_outer1,
3375        "typechart": $circle_two ? $circle_two['typechart'] : $circle_one['typechart'],
3376        "aspecthouse": $circle_one['aspecthouse'],
3377        "circle_type": $circle_one['circle_type'],
3378        "houseMethods": $circle_one['houseMethods'],
3379        "user_aspects": $circle_one['user_aspects'],
3380        "user_planet": $circle_one['user_planet'],
3381        "gradus": 1,
3382        "user_setting": user_setting,
3383        "zet_str": $circle_one['zet_str']
3384    };
3385
3386    for(var key in $circle_one['cuspsData']){
3387        $astro_cusps_outer2.push(parseFloat($circle_two['cuspsData'][key]));
3388    }
3389
3390    let dataTwo = {
3391        "planets": JSON.parse(JSON.stringify($circle_two['planetData'])),
3392        "cusps": JSON.parse(JSON.stringify($astro_cusps_outer2)),
3393        "typechart": $circle_two['typechart'],
3394        "aspecthouse": $circle_two['aspecthouse'],
3395        "dataArray": $circle_two['dataArray'],
3396        "circle_type": $circle_two['circle_type'],
3397        "houseMethods": $circle_two['houseMethods'],
3398        "user_aspects": $circle_two['user_aspects'],
3399        "user_planet": $circle_two['user_planet'],
3400        "gradus": 1,
3401        "user_setting": user_setting,
3402        "zet_str": $circle_two['zet_str']
3403    };
3404
3405    if(analytics.type_rebuild == 'profection'){
3406        let dataTwo2 = Object.assign({}, dataTwo);
3407        rebuild_transit(dataTwo, dataTwo2, $circle_two['type_chart_event'], JSON.parse(analytics.d_one)['date'], JSON.parse(analytics.d_two)['date']);
3408    }else{
3409        build(dataOne, dataTwo, circle_outer_text);
3410    }
3411
3412}
3413
3414function buildCircleTransit($circle_outer, dataEventOffset, circle_outer_text, margin_chart = 70, height_chart = 800, width_chart = 800){
3415
3416    var serialObj = JSON.stringify([$circle_outer, dataEventOffset , circle_outer_text, 'outer', 'transit']);
3417    sessionStorage.setItem(circle_outer_text, serialObj);
3418
3419    var user_setting;
3420    var $astro_cusps_outer = [];
3421
3422    if($circle_outer['user_setting']){
3423        user_setting = $circle_outer['user_setting']
3424    }else{
3425        user_setting = false;
3426    }
3427
3428    for(var key in $circle_outer['cuspsData']){
3429        $astro_cusps_outer.push(parseFloat($circle_outer['cuspsData'][key]));
3430    }
3431
3432    var dataTransit = {
3433        "planets": JSON.parse(JSON.stringify($circle_outer['planetData'])),
3434        "cusps": $astro_cusps_outer,
3435        "typechart": $circle_outer['typechart'],
3436        "aspecthouse": $circle_outer['aspecthouse'],
3437        "dataArray": $circle_outer['dataArray'],
3438        "circle_type": $circle_outer['circle_type'],
3439        "houseMethods": $circle_outer['houseMethods'],
3440        "user_aspects": $circle_outer['user_aspects'],
3441        "user_planet": $circle_outer['user_planet'],
3442        "gradus": 1,
3443        "user_setting": user_setting,
3444        "zet_str": $circle_outer['zet_str']
3445    };
3446
3447    build(dataTransit, dataEventOffset, circle_outer_text);
3448}
3449
3450function build_table_player($add_data) {
3451
3452    var place = $.trim($('.place_match_info').text()),
3453        date_match = $.trim($('.date_match_info').text());
3454
3455    var tags = "<table class='transits_table'><tbody>";
3456    tags += "<tr>";
3457    tags += "<td class='transits_table_col transits_table_col__one'><div class='transits_table_col__coache'>" + $add_data['name'] + "</div>";
3458    if($add_data['rr_content']){
3459        tags += "<div class='astro-event-rating_analytics' js-tip title='' data-hasqtip='66' aria-describedby='qtip-66' oldtitle="+'\u0022'+$add_data['rr_content']+'\u0022'+">";
3460        // tags += "<div class='astro-event-rating_analytics'>";
3461        tags += "<span>"+$add_data['rr_name']+"</span>";
3462        tags += "</div>";
3463    }
3464    tags += "<button button='white_str' id='button_zet' data-zet_message="+ '\u0022'+$add_data['zet_line']+'\u0022' +">Zet</button>";
3465    tags += "</td>";
3466
3467    tags += "<td class='transits_table_col transits_table_col__right'>" + place + "</td>";
3468    tags += "</tr>";
3469
3470    tags += "<tr>";
3471    tags += "<td></td>";
3472    tags += "<td class='transits_table_col transits_table_col__right'>" + date_match + "</td>";
3473    tags += "</tr>";
3474
3475    tags += "</table></tbody>";
3476
3477    return tags;
3478}
3479
3480
3481
3482
3483(function(){
3484
3485    var timeAccuracies = [], timeSources = [], timeRatingSchema, $rootElement;
3486
3487    angular.module('astroEvent', ['ng', 'green.inputmask4angular'])
3488        .controller('TimeController', function($scope, $timeout){
3489            $scope.timeMask = {
3490                placeholder: 'чч:мм'
3491            };
3492
3493            $scope.time = $rootElement.find('input[name=time]').val();
3494
3495            $scope.timeAccuracies = timeAccuracies;
3496            $scope.timeSources = timeSources;
3497            $scope.timeRatingSchema = timeRatingSchema;
3498
3499            $scope.$watch('timeAccuracies', function(value){
3500                $rootElement.find('select[name=time_accuracy]').trigger('update');
3501            });
3502
3503            $scope.$watch('timeSource', function(value){
3504                $rootElement.find('select[name=time_source]').trigger('update');
3505            });
3506
3507            $timeout(function(){
3508                $rootElement.find('select[name=time_accuracy]').trigger('update');
3509                $rootElement.find('select[name=time_source]').trigger('update');
3510            });
3511        });
3512
3513    window.astroEventEdit = function(listManager, options){
3514        $$.openModal({
3515            url: $$.urlPrefix + '/office/data/?get',
3516            data: {id: options.id},
3517            modules: ['astroEvent'],
3518            ajax: {
3519                xhrFields: {
3520                    withCredentials: true
3521                },
3522                crossDomain: true
3523            },
3524            afterOpen: function(modal, $modal, modalResponse){
3525                timeAccuracies = [];
3526                $.each(modalResponse.accuracies, function(key, value){
3527                    timeAccuracies.push({id: key, value: value});
3528                });
3529
3530                timeSources = [];
3531                $.each(modalResponse.sources, function(key, value){
3532                    timeSources.push({id: key, value: value});
3533                });
3534
3535                timeRatingSchema = modalResponse.schema;
3536
3537                $rootElement = $modal;
3538
3539                $modal.find('form').formHandle({
3540                    success: function(response){
3541                        $modal.closest('.arcticmodal-container').arcticmodal('close');
3542                        listManager.load();
3543                    }
3544                });
3545            }
3546        });
3547
3548    };
3549
3550    window.astroEventDelete = function(listManager, options, $button){
3551        if($button.data('lock')){
3552            return;
3553        }
3554
3555        $button.data('lock', true);
3556
3557        var action = function(){
3558            $.ajax({
3559                url: $$.urlPrefix + '/office/data/?delete',
3560                type: 'post',
3561                dataType: 'json',
3562                data: {id: options.id},
3563                xhrFields: {
3564                    withCredentials: true
3565                },
3566                crossDomain: true,
3567                success: function(){
3568                    listManager.load();
3569                }
3570            });
3571        };
3572
3573        $$.confirm({
3574            message: 'Событие будет удалено. Продолжить?',
3575            onConfirm: function(){
3576                $button.closest('.articles-item').remove();
3577                action();
3578            }
3579        });
3580    }
3581
3582
3583})();
3584
3585$(function(){
3586
3587});
3588$(function(){
3589
3590    function attachImage($button){
3591        var $parent = $button.parent(),
3592            $list = $parent.siblings('.attach-images').eq(0);
3593
3594        if(!$list.length){
3595            $list = $('<div class="attach-images"></div>');
3596            $parent.after($list);
3597        }
3598        var $input = $("<input type=\"file\">"),
3599            startTimer;
3600
3601        $input.damnUploader({
3602            url: "/api/attachImage/",
3603            fieldName:  "file",
3604            multiple: true,
3605            dataType: 'json'
3606        })
3607            .on('du.add', function(e) {
3608                var ui = e.uploadItem,
3609                    $image = $('<div class="attach-images-item"><div class="attach-images-item-name"></div><div class="attach-images-item-loading"></div><div class="attach-images-item-error"></div></div>'),
3610                    file = {
3611                        name: ui.file.name,
3612                        progress: 0,
3613                        id: 0
3614                    },
3615                    invalid = false;
3616
3617                $list.append($image);
3618
3619                function render(){
3620                    $image.find('.attach-images-item-name').text(file.name);
3621                    $image.find('.attach-images-item-loading').text('Загрузка ' + file.progress + '%');
3622                    $image.find('.attach-images-item-error').text(file.error);
3623                    $image.find('.attach-images-item-loading')[(!file.error && !file.id && (file.progress || file.progress === 0)) ? 'show' : 'hide']();
3624                    $image.find('.attach-images-item-error')[file.error ? 'show' : 'hide']();
3625                }
3626
3627
3628                if(!ui.file.type.match(/^(image.*)$/g)){
3629                    file.error = 'Формат ' + ui.file.type + ' не поддерживается';
3630                    invalid = true;
3631                }
3632
3633
3634                if(ui.file.size > 10485760){
3635                    file.error = 'Максимальный размер файла 10Мб';
3636                    invalid = true;
3637                }
3638
3639                render();
3640
3641                if(invalid){
3642                    setTimeout(function(){
3643                        $image.fadeOut();
3644                    }, 2000);
3645
3646                    return;
3647                }
3648
3649                ui.completeCallback = function(success, response) {
3650                    if(response.success){
3651                        var $input = $parent.find('textarea, input');
3652
3653                        file.id = response.image_id;
3654                        $image.data('id', response.image_id);
3655                        $image.append('<div class="attach-images-item-actions">(<a href="#" class="attach-images-item-actions-insert">Вставить в текст</a>|<a href="#" class="attach-images-item-actions-delete">Удалить</a>)</div>');
3656                        $image.find('.attach-images-item-actions-insert').on('click', function(e){
3657                            e.preventDefault();
3658                            $input.val($input.val() + '[img='+$image.data('id')+']');
3659                        });
3660                        $image.find('.attach-images-item-actions-delete').on('click', function(e){
3661                            e.preventDefault();
3662                            $input.val($input.val().replace(/\[img=\d+\]/, ''));
3663                            $image.remove();
3664                        });
3665                    
3666                    }else{
3667                        file.error = response.error['#'] || 'Ошибка загрузки';
3668                    }
3669                    render();
3670                };
3671
3672                ui.progressCallback = function(progress) {
3673                    file.progress = progress;
3674                    render();
3675                };
3676
3677                clearTimeout(startTimer);
3678                startTimer = setTimeout(function(){
3679                    $input.duStart();
3680                }, 100);
3681
3682            })
3683            .on('du.completed', function(e) {
3684                $input.remove();
3685            })
3686            .click();
3687
3688
3689    }
3690
3691
3692    $$.document.on('click', '[js-attach-image]', function(){
3693        attachImage($(this));
3694    });
3695
3696    $$.document.on('click', 'a[rel^="external"]', function(e){
3697        e.preventDefault();
3698        $.fancybox([{href: $(this).attr('href')}]);
3699    });
3700
3701
3702});
3703$(function(){
3704
3705	$$.getUrlParameter = function getUrlParameter(sParam) {
3706		var sPageURL = decodeURIComponent(window.location.search.substring(1)),
3707			sURLVariables = sPageURL.split('&'),
3708			sParameterName,
3709			i;
3710
3711		for (i = 0; i < sURLVariables.length; i++) {
3712			sParameterName = sURLVariables[i].split('=');
3713
3714			if (sParameterName[0] === sParam) {
3715				return sParameterName[1] === undefined ? true : sParameterName[1];
3716			}
3717		}
3718	};
3719
3720	var lesid = $$.getUrlParameter('les_id');
3721
3722
3723	$$.openAuth = function(type, options){
3724		options = options || {};
3725
3726		options.afterOpen = function(modal, $modal){
3727			//$modal.find('.arcticmodal-close.modal-box-close').hide();
3728		};
3729
3730	    var $modal = $$.openModal($('.modal-auth'), options);
3731		$modal.addClass('mod-auth');
3732	    authOpened($modal, type);
3733	};
3734
3735
3736	var $links = $('[js-signup-open], [js-signin-open]');
3737
3738	$links.off('.modal').on('click.modal', function (e) {
3739	    e.preventDefault();
3740	    $$.openAuth($(this).data('tab'), {closeOnOverlayClick: false, closeOnEsc: false});
3741	});
3742
3743	function authOpened(modal, type) {
3744	    var tabs = Helper.createTabs({
3745	        tabs: $('[js-tabs-tab]', modal),
3746	        panes: $('[js-tabs-pane]', modal)
3747	    });
3748
3749	    tabs.select('auth', type);
3750	}
3751
3752	$('body').on('submit', 'form[action="'+$$.urlPrefix+'/office/signin/"], form[action="'+$$.urlPrefix+'/office/signup/"], form[action="'+$$.urlPrefix+'/office/forgot/"], form[action="'+$$.urlPrefix+'/office/reset/?reset"]', function(e){
3753		e.preventDefault();
3754		var $form = $(this);
3755		$$.uniFormSubmit($form, {
3756			overlay: true,
3757			afterSuccess: function(data, $form){
3758
3759				if($form.attr('action') == ''+$$.urlPrefix+'/office/signin/'){
3760					location.reload();
3761				}else if($form.attr('action') == ''+$$.urlPrefix+'/office/signup/'){
3762					var $pane = $form.closest('.content-pane');
3763					$pane.find('.auth-socials').slideUp();
3764					$form.find('.form-actions').slideUp();
3765					$form.find('.form-inputs').slideUp(300, function(){
3766						$(this).html(data.message).slideDown();
3767					});
3768				}else if($form.attr('action') == ''+$$.urlPrefix+'/office/forgot/'){
3769					$form.find('.form-actions').slideUp();
3770					$form.find('.form-inputs').slideUp(300, function(){
3771						$(this).html(data.message).slideDown();
3772					});
3773				}else if($form.attr('action') == ''+$$.urlPrefix+'/office/reset/?reset'){
3774					$form.find('.form-actions').slideUp();
3775					$form.find('.form-inputs').slideUp(300, function(){
3776						$(this).html(data.message).slideDown();
3777					});
3778				}
3779			}
3780		});
3781	});
3782
3783
3784
3785	//смена пароля
3786	$('.auth-new-pass').on('submit', function(e){
3787		e.preventDefault();
3788		var $form = $(this);
3789		$$.uniFormSubmit($form, {
3790			overlay: $form.closest('.form'),
3791			afterSuccess: function(data){
3792				$form.closest('.auth-form-new-pass').slideUp(300, function(){
3793					$(this).html(data.message).slideDown();
3794					$(this).find('.js-sign-in-open-button').on('click', function(){
3795						$$.openAuth('mod-login', {closeOnOverlayClick: false, closeOnEsc: false});
3796					});
3797				});
3798			}
3799		});
3800	});
3801
3802	//Exit
3803	$('[js-sign-out]').on('click', function(e){
3804		e.preventDefault();
3805		$.ajax({
3806			url: $$.urlPrefix + '/office/signout/', type: 'post',
3807			success: function(){ location.href = '/'; }
3808		});
3809	});
3810
3811
3812	if(document.location.hash == '#signin'){
3813		document.location.hash = '';
3814		$$.openAuth('mod-login', {closeOnOverlayClick: false, closeOnEsc: false});
3815	}
3816
3817	var $body = $('body');
3818
3819	//if(!$body.data('is-authenticated')){ $$.openAuth('signin'); }
3820
3821	if($body.data('confirm-account-type')){
3822		$$.openModal($('.modal-confirm-account-type'), {
3823			closeOnOverlayClick: false,
3824			beforeOpen: function(obj, $modal){
3825				$modal.find('.arcticmodal-close').remove();
3826			},
3827			afterOpen: function(obj, $modal){
3828				$modal.find('[js-confirm-account-type]').on('click', function(){
3829					$modal.arcticmodal('close');
3830					$.ajax({
3831						url: $$.urlPrefix + '/office/confirmAccountType/', type: 'post',
3832						xhrFields: {
3833							withCredentials: true
3834						},
3835						crossDomain: true,
3836						data: {type: $(this).data('type')}
3837					});
3838				});
3839			}
3840		});
3841	}
3842
3843	var $confirmModal = $('.modal-confirm-email');
3844	if($confirmModal.length){
3845		$$.openModal($confirmModal);
3846	}
3847
3848	var $resetModal = $('.modal-reset-password');
3849	if($resetModal.length){
3850		$$.openModal($resetModal);
3851	}
3852
3853
3854	$('[js-signin]').on('click', function(e){
3855		e.preventDefault();
3856		$$.openAuth();
3857
3858	});
3859
3860});
3861
3862$(function(){
3863
3864    var $achives_wrapper = $('[js-box-achives]');
3865    if ( !$achives_wrapper.length ) return;
3866
3867    var $crops;
3868    var $toggler = $("<div class='box-achives-more'><a href='#'></a></div>");
3869    var $toggler_link = $toggler.children();
3870    var toggler_text = 'Ещё {length} наград';
3871    var $achives = $achives_wrapper.children();
3872    var achives_w = $achives_wrapper.width();
3873    var isOpen = false;
3874    var crop_w = 0;
3875    var crops_len = 0;
3876
3877
3878
3879    if ( $achives_wrapper.is(':visible') ) {
3880        $achives.each(function (i, achive) {
3881            var $achive = $achives.eq(i);
3882            var achive_w = $achive.outerWidth(true);
3883
3884            if ( crop_w >= achives_w ) {
3885                $crops ? $crops = $crops.add($achive) : $crops = $achive;
3886            }
3887            else {
3888                crop_w = crop_w + achive_w;
3889            }
3890        });
3891
3892        if ( !$crops ) return;
3893
3894        crops_len = $crops.length;
3895        toggler_text = toggler_text.replace('{length}', crops_len) + ( crops_len == 1 ? 'а' : crops_len > 1 && crops_len < 5 ? 'ы' : '');
3896
3897        if ( crops_len ) {
3898            $crops.hide();
3899            $toggler_link
3900                .text(toggler_text)
3901                .off('.achives')
3902                .on({
3903                'click.achives': function (e) {
3904                    e.preventDefault();
3905                    if ( isOpen ) {
3906                        isOpen = false;
3907                        $crops.hide();
3908                        $toggler_link.text(toggler_text);
3909                        $achives_wrapper.toggleClass('is-open', isOpen);
3910                    }
3911                    else {
3912                        isOpen = true;
3913                        $crops.show();
3914                        $toggler_link.text('Свернуть');
3915                        $achives_wrapper.toggleClass('is-open', isOpen);
3916                    }
3917                }
3918            });
3919            $toggler.appendTo($achives_wrapper);
3920        }
3921    }
3922});
3923
3924$(function() {
3925    $('.career-table-content').on('click', '.career-table-col__car',function() {
3926        if(!$(this).hasClass('non-active')){
3927            var tr = $(this).parent('tr');
3928            $('.career-table-content').find('tr').each(function () {
3929                $(this).find('.career-table-col__car').removeClass('active');
3930                $(this).find('.career-table-col__teams').removeClass('mod-bold');
3931            });
3932
3933            $(this).toggleClass("active");
3934            tr.find('.career-table-col__teams').addClass('mod-bold');
3935
3936            var panel = $('.coach-panel'),
3937                $coache_event = $('[js-coache]'),
3938                $item_id = $(this).data('id');
3939
3940            $.ajax({
3941                url: '/sport/coaches/'+$coache_event.data('uri')+'/'+$coache_event.data('id')+'/?works',
3942                type: 'post',
3943                data: {coache_id: $coache_event.data('id'), item_id: $item_id},
3944                dataType: 'json',
3945                success: function(response){
3946                    if(response.success) panel.html(response.content);
3947                },
3948                complete: function(){
3949                    // $item.removeClass('is-loading');
3950                    // lock = false;
3951                }
3952            });
3953        }
3954
3955    });
3956});
3957$(function(){
3958
3959    $('.comments').each(function(){
3960
3961
3962        var $comments = $(this),
3963            $list = $comments.find('.comments-list'),
3964            $mainForm = $comments.find('.comments-form'),
3965            $count = $comments.find('.comments-head-count'),
3966            externalId = $comments.data('external-id');
3967
3968        var lock;
3969
3970
3971        function countRecalc(){
3972            $count.text($comments.find('.comments-item').length);
3973        }
3974
3975        $comments.on('submit', '.comments-form form', function(e){
3976            e.preventDefault();
3977
3978            if(lock) return;
3979            lock = true;
3980
3981            var $form = $(this),
3982                $formContainer = $form.closest('.comments-form'),
3983                commentId = +$form.data('comment-id');
3984
3985            $$.uniFormError($form);
3986            $formContainer.addClass('is-loading');
3987
3988            $form.find('.attach-images').each(function(){
3989                var $root = $(this),
3990                    $images = $root.find('.attach-images-item'),
3991                    $input = $form.find('textarea, input'),
3992                    text = $input.val();
3993
3994                $images.each(function(){
3995                    var $image = $(this);
3996                    if($image.data('id')){
3997                        if(!text.match(new RegExp('\\[img='+$image.data('id')+'\\]', 'ig'))){
3998                            text += '[img='+$image.data('id')+']';
3999                        }
4000                    }
4001                });
4002
4003                $input.val(text);
4004            });
4005
4006            $.ajax({
4007                url: '?commentAction=add' + (commentId ? '&commentId=' + commentId : ''),
4008                data: $form.serialize(),
4009                dataType: 'json',
4010                type: 'post',
4011                success: function(response){
4012                    if(response.error){
4013                        $$.uniFormShowError($form.find('textarea'), response.error === true ? 'Ошибка добавления комментария' : response.error);
4014
4015                    }else if(response.success){
4016                        var $comment = $(response.success);
4017                        if(commentId){
4018                            var $item = $formContainer.prev('.comments-item'),
4019                                level = $item.data('level'),
4020                                $next = $item.nextAll('.comments-item').filter(function(){
4021                                    return $(this).data('level') <= level;
4022                                }).eq(0);
4023                            if($next.length){
4024                                $next.before($comment);
4025                            }else{
4026                                $list.append($comment);
4027                            }
4028                            $formContainer.remove();
4029
4030                        }else{
4031                            $list.append($comment);
4032                            $form.resetForm();
4033                        }
4034
4035                        $$.scrollTo($comment, 300, 300);
4036                        $comment.addClass('is-created').delay(1000).queue(function(){
4037                            $comment.removeClass('is-created');
4038                        });
4039
4040                        countRecalc();
4041
4042                        $form.find('.attach-images').remove();
4043                    }
4044                },
4045                complete: function(){
4046                    lock = false;
4047                    $form.removeClass('is-loading');
4048                }
4049            });
4050        });
4051
4052        $comments.on('click', 'a.comment', function(e){
4053            e.preventDefault();
4054            if(lock) return;
4055            var $button = $(this),
4056                $item = $button.closest('.comments-item'),
4057                $form = $item.next('.comments-form');
4058
4059            if(!$form.length){
4060                $list.find('.comments-form').remove();
4061                $form = $mainForm.clone().css({marginLeft: (+$item.data('level')+1) * 50}).insertAfter($item).find('form').data('comment-id', $item.data('id'));
4062            }
4063            $form.find('textarea').focus();
4064            $$.scrollTo($item, 300, 300)
4065
4066        });
4067
4068
4069
4070        $comments.on('click', 'a.approve', function(e){
4071            e.preventDefault();
4072            if(lock) return; lock = true;
4073            var $button = $(this),
4074                $item = $button.closest('.comments-item');
4075
4076            $item.addClass('is-loading');
4077
4078            $.ajax({
4079                url: '?commentAction=approve',
4080                type: 'post',
4081                data: {commentId: $item.data('id'), externalId: externalId},
4082                dataType: 'json',
4083                success: function(response){
4084                    if(response.success){
4085                        $item.html($(response.success).html());
4086                        countRecalc();
4087                    }
4088                },
4089                complete: function(){
4090                    $item.removeClass('is-loading');
4091                    lock = false;
4092
4093                }
4094            });
4095        });
4096
4097        $comments.on('click', 'a.reject', function(e){
4098            e.preventDefault();
4099            if(lock) return; lock = true;
4100            var $button = $(this),
4101                $item = $button.closest('.comments-item');
4102
4103            $item.addClass('is-loading');
4104
4105            $.ajax({
4106                url: '?commentAction=reject',
4107                type: 'post',
4108                data: {commentId: $item.data('id'), externalId: externalId},
4109                dataType: 'json',
4110                success: function(response){
4111                    if(response.success){
4112                        $item.html($(response.success).html());
4113                        countRecalc();
4114                    }
4115                },
4116                complete: function(){
4117                    $item.removeClass('is-loading');
4118                    lock = false;
4119                }
4120            });
4121        });
4122
4123        $comments.on('click', 'a.delete', function(e){
4124            e.preventDefault();
4125            if(lock) return; lock = true;
4126            var $button = $(this),
4127                $item = $button.closest('.comments-item');
4128
4129            $item.addClass('is-loading');
4130
4131            $.ajax({
4132                url: '?commentAction=delete',
4133                type: 'post',
4134                data: {commentId: $item.data('id'), externalId: externalId},
4135                dataType: 'json',
4136                success: function(response){
4137
4138                    if(response.deleted){
4139
4140                        $list.find('.comments-form').remove();
4141
4142                        var level = $item.data('level');
4143                        $item.nextAll('.comments-item').each(function(index, it){
4144                            if($(it).data('level') <= level) return false;
4145                            $(this).remove();
4146                        });
4147
4148                        $item.remove();
4149
4150                    }else if(response.success){
4151                        $item.html($(response.success).html());
4152                    }
4153
4154                    countRecalc();
4155
4156                },
4157                complete: function(){
4158                    $item.removeClass('is-loading');
4159                    lock = false;
4160                }
4161            });
4162
4163
4164        });
4165
4166
4167        $comments.on('click', '.comments-item-vote', function(e){
4168            e.preventDefault();
4169            if(lock) return; lock = true;
4170            var $button = $(this),
4171                $item = $button.closest('.comments-item');
4172
4173            $item.addClass('is-loading');
4174
4175            $.ajax({
4176                url: '?commentAction=vote',
4177                type: 'post',
4178                data: {commentId: $item.data('id'), value: $button.hasClass('mod-positive') ? 1 : -1, externalId: externalId},
4179                dataType: 'json',
4180                success: function(response){
4181                    if(response.success) $item.html($(response.success).html());
4182                },
4183                complete: function(){
4184                    $item.removeClass('is-loading');
4185                    lock = false;
4186                }
4187            });
4188        });
4189
4190        $comments.find('.comments-head-add').on('click', function(e){
4191            e.preventDefault();
4192            $mainForm.find('textarea').focus();
4193            $$.scrollTo($mainForm, 300, 300)
4194        })
4195
4196
4197    });
4198
4199});
4200$(function($, undefined){
4201
4202    (function(){
4203        var $notification = $('.header-action[data-notification]'),
4204            $mailNotification = $('.header-action[data-mail]'),
4205            $officeMenuMail = $('.snav-item-link[data-menu="mail"]'),
4206            officeMenuTimer;
4207
4208        var audioNotification =  new Audio(),
4209            audioMail = new Audio();
4210
4211            audioNotification.preload = 'auto';
4212            audioNotification.volume = 1;
4213            audioNotification.src = '/audio/notification.mp3';
4214
4215            audioMail.preload = 'auto';
4216            audioMail.volume = 1;
4217            audioMail.src = '/audio/mail.mp3';
4218
4219        $$.dispatcher.bind('notification', function(data){
4220            if(data.notifications !== undefined){
4221                $$.dispatcher.trigger('notifications', data);
4222            }
4223
4224            if(data.common !== undefined){
4225                if(+$notification.data('notification') < data.common && window.isMaster()){
4226                    audioNotification.play();
4227                }
4228                $notification.attr('data-notification', data.common);
4229            }
4230
4231            if(data.mail !== undefined && $officeMenuMail.length){
4232
4233                var $sup = $officeMenuMail.find('sup');
4234                if(!$sup.length){
4235                    $sup = $('<sup></sup>').appendTo($officeMenuMail).hide();
4236                }
4237
4238                if(data.mail){
4239                    if(+$sup.text() < data.mail && window.isMaster()){
4240                        // ---
4241                    }
4242                }
4243
4244                clearTimeout(officeMenuTimer);
4245                officeMenuTimer = setTimeout(function(){
4246                    if(data.mail){
4247                        $sup.text(data.mail).fadeIn(300);
4248                    }else{
4249                        $sup.fadeOut(300);
4250                    }
4251
4252                    if(+$mailNotification.data('mail') < data.mail && window.isMaster()){
4253                        audioMail.play();
4254                    }
4255                    $mailNotification.attr('data-mail', data.mail);
4256
4257                    var $officeMailList = $('.mail .list');
4258                    if($officeMailList.length && $officeMailList.is(':visible') && $officeMailList.data('listManager')){
4259                        $officeMailList.data('listManager').load();
4260                    }
4261
4262                }, 500);
4263            }else{
4264                if(+$mailNotification.data('mail') < data.mail && window.isMaster()){
4265                    audioMail.play();
4266                }
4267                $mailNotification.attr('data-mail', data.mail);
4268            }
4269
4270        });
4271
4272        socket.on('notification', function(data){
4273            $$.dispatcher.trigger('notification', data);
4274        });
4275
4276    }());
4277
4278
4279    $('.topics-list').owlCarousel({
4280        dragEndSpeed: 600,
4281        loop: true,
4282        items: 3,
4283        stagePadding: 0,
4284        margin: 0,
4285        autoHeight: false,
4286        mouseDrag: true,
4287        dots: false,
4288        nav: true,
4289        autoplay: false
4290    });
4291
4292    $('.articles-list.mod-slider').owlCarousel({
4293        dragEndSpeed: 600,
4294        loop: false,
4295        items: 3,
4296        responsive: {
4297            0: {
4298                items: 1,
4299            },
4300            760: {
4301                items: 2
4302            },
4303            1000: {
4304                items: 3
4305            }
4306        },
4307        stagePadding: 0,
4308        margin: 33,
4309        autoHeight: false,
4310        mouseDrag: true,
4311        dots: true,
4312        nav: false,
4313        autoplay: false
4314    });
4315
4316    $$.document.on('click', '[js-like]', function(e){
4317        e.preventDefault();
4318
4319        var $button = $(this),
4320            request = $button.data('request');
4321
4322
4323        if($$.isAuthenticated){
4324            if(request){
4325                request.abort();
4326            }
4327
4328            $button
4329                .toggleClass('is-active')
4330                .text(+$button.text() + ($button.hasClass('is-active') ? 1 : -1))
4331                .data('request', $.ajax({
4332                    url: $$.urlPrefix + '/api/like/',
4333                    type: 'post',
4334                    dataType: 'json',
4335                    data: {id: $button.attr('js-like')},
4336                    xhrFields: {
4337                        withCredentials: true
4338                    },
4339                    crossDomain: true,
4340                    success: function(response){
4341                        if(undefined !== response.likes){
4342                            $button.text(response.likes);
4343                        }
4344                    },
4345                    complete: function(){
4346                        $button.data('lock', false);
4347                    }
4348                })
4349            );
4350
4351        }else{
4352	        $$.openAuth();
4353        }
4354
4355
4356    });
4357
4358
4359
4360});
4361
4362$(function(){
4363
4364    window.reloadList = function(listManager){
4365        listManager.load();
4366    }
4367
4368});
4369
4370$(function(){
4371
4372    var ua = $$.getUrlParameter('ua');
4373
4374    if (ua == "false"){
4375        if(!$$.isAuthenticated){
4376            return $$.openAuth();
4377        }
4378    };
4379
4380});
4381(function(){
4382
4383	window.consultationChoose = function(listManager, options, $caller){
4384		var $chooseHolder = $('.consultation-form-chosen'),
4385			$chosenItem = $caller.closest('.articles-item'),
4386			$step = $caller.closest('.consultation-form-step'),
4387			$modal = $caller.closest('.modal-box')
4388		;
4389
4390		listManager.parameters.choose = options.id;
4391		listManager.load();
4392
4393
4394		$chooseHolder.find('.holder').empty().addClass('is-active');
4395		$chooseHolder.find('.holder').append($chosenItem.clone().find('.articles-item-order').text('Продолжить').attr('js-consultation-next', '').end()).end().addClass('is-active mod-step2').removeClass('mod-step1');
4396
4397		$step.hide();
4398		$modal.find('[data-step=question]').show();
4399
4400		$chosenItem.closest('.modal-box-content').find('[js-consultation-form] input[name=expert_id]').val($chosenItem.data('id'));
4401
4402
4403	};
4404
4405})();
4406
4407$(function(){
4408	var $body = $('body');
4409
4410	$('[js-consult-open]').on('click', function(e){
4411		e.preventDefault();
4412
4413		$$.openModal($('.modal-consultation-choose'), {
4414			afterOpen: function(modal, $modal){
4415				$modal.addClass('is-inview');
4416			}
4417		});
4418	});
4419
4420
4421
4422	$('[js-consultation-choose]').on('click', function(e){
4423		e.preventDefault();
4424
4425		if(!$$.isAuthenticated){
4426			return $$.openAuth();
4427		}
4428
4429		$.arcticmodal('close');
4430		if($(this).data('type') == 'free'){
4431
4432			if(!+$body.attr('data-has-avatar')){
4433				$$.openModal($('.modal-avatar-load'), {
4434					afterOpen: function(modal, $modal){
4435						$modal.find('button').on('click', function(e){
4436							e.preventDefault();
4437							$modal.arcticmodal('close');
4438						});
4439					},
4440					afterClose: function(){
4441						setTimeout(function(){
4442							if(+$body.attr('data-has-avatar')){
4443								$('[js-consultation-choose][data-type="free"]').eq(0).click();
4444							}else{
4445								$('[js-consult-open]').eq(0).click();
4446							}
4447						}, 10);
4448					}
4449				});
4450				return;
4451			}
4452
4453			$$.openModal($('.modal-consultation-free').clone(), {
4454				afterOpen: function(modal, $modal){
4455                    var chooseEvents = [];
4456
4457                    $modal.closest('.modal-box').addClass('mod-consultation');
4458					$modal.find('.list').removeClass('is-initialized');
4459
4460
4461					$$.init.all($modal);
4462
4463
4464                    $modal.on('change', 'input[name^=events]', function(){
4465                        var $input = $(this);
4466                        if($input.prop('checked')){
4467                            chooseEvents.push($input.prop('name'));
4468                        }else{
4469                            chooseEvents = chooseEvents.filter(function(item){
4470                                return item != $input.prop('name');
4471                            });
4472                        }
4473
4474                    });
4475
4476                    $modal.find('input[name^=events]').each(function(){
4477                        chooseEvents.push($(this).prop('checked', true).prop('name'));
4478                    });
4479
4480                    $modal.find('.list').on('afterInstall', function(){
4481                        $modal.find('input[name^=events]').each(function(){
4482                            $(this).prop('checked', chooseEvents.indexOf($(this).prop('name')) >=0);
4483                        });
4484                    });
4485
4486                    $$.init.listManager();
4487
4488                    $modal.find('form').formHandle({
4489						success: function(data, $form){
4490							$form.closest('.consultation-form').find('.consultation-form-description').slide
4490Up();
4491							$form.closest('.form-group').slideUp(300, function(){
4492								$(this).html(data.message).slideDown();
4493							});
4494						}
4495					});
4496
4497				},
4498				beforeClose: function(){
4499					$('.select-region-holder').remove();
4500				}
4501			});
4502		}else{
4503			$$.openModal({
4504				url: '/consultation/?consultation-payed-step1',
4505				afterOpen: function(modal, $modal){
4506                    var chooseEvents = [];
4507
4508					$modal.closest('.modal-box').addClass('mod-consultation');
4509
4510					var $back = $modal.find('[js-consultation-back]');
4511					$back.on('click', function(e){
4512						e.preventDefault();
4513						$modal.find('.list').data('listManager').load();
4514						$modal.find('.consultation-form-chosen').removeClass('mod-step2').addClass('mod-step1');
4515						$modal.find('[data-step=question]').slideUp();
4516						$modal.find('[data-step=astrologer]').slideDown();
4517					});
4518
4519					$modal.on('click', '[js-consultation-next]', function(){
4520						$modal.find('.consultation-form-step').hide().next().show();
4521						$modal.find('.consultation-form-chosen').removeClass('mod-step1').addClass('mod-step2');
4522					});
4523
4524                    $$.init.all($modal);
4525
4526
4527                    $modal.on('change', 'input[name^=events]', function(){
4528                        var $input = $(this);
4529                        if($input.prop('checked')){
4530                            chooseEvents.push($input.prop('name'));
4531                        }else{
4532                            chooseEvents = chooseEvents.filter(function(item){
4533                                return item != $input.prop('name');
4534                            });
4535                        }
4536
4537                    });
4538
4539                    $modal.find('input[name^=events]').each(function(){
4540                        chooseEvents.push($(this).prop('checked', true).prop('name'));
4541                    });
4542
4543                    $modal.find('.list').on('afterInstall', function(){
4544                        $modal.find('input[name^=events]').each(function(){
4545                            $(this).prop('checked', chooseEvents.indexOf($(this).prop('name')) >=0);
4546                        });
4547                    });
4548
4549
4550					$modal.find('[js-consultation-form]').formHandle({
4551						afterData: function($form, data){
4552							if(data.error && data.error['#']){
4553								//$back.trigger('click');
4554							}
4555						},
4556						success: function(data, $form){
4557							$modal.arcticmodal('close');
4558							$$.payment(data.holderId);
4559						}
4560					});
4561
4562				},
4563				beforeClose: function(){
4564					$('.select-region-holder').remove();
4565				}
4566			});
4567		}
4568
4569	});
4570
4571
4572
4573});
4574
4575$(function(){
4576
4577    $('.consultation-review').find('form').formHandle({
4578        success: function(response){
4579            $$.alert('Спасибо, ваш отзыв был опубликован на сайте!');
4580            document.location.reload();
4581        }
4582    });
4583    
4584});
4585(function(){
4586    var $consultation;
4587
4588    var audio = new Audio();
4589    audio.preload = 'auto';
4590    audio.volume = 1;
4591    audio.src = '/audio/consultation.mp3';
4592
4593    angular
4594        .module('consultation', ['ng', 'socket'])
4595        .run(function($rootScope, $timeout, $socket){
4596            $consultation.addClass('is-loaded');
4597
4598
4599            var state = $consultation.data('state');
4600            if(state){
4601                $.extend($rootScope, state);
4602            }
4603
4604            $rootScope.settings = function(){
4605                $$.openModal({
4606                    url: $$.urlPrefix + '/api/consultation/?settings',
4607                    ajax: {
4608                        xhrFields: {
4609                            withCredentials: true
4610                        },
4611                        crossDomain: true
4612                    },
4613                    afterOpen: function(modal, $modal, modalResponse){
4614                        $modal.find('form').formHandle({
4615                            success: function(response){
4616                                $modal.arcticmodal('close');
4617                                if(response.work){
4618                                    $timeout(function(){
4619                                        $rootScope.work = response.work;
4620                                    });
4621                                }
4622                            }
4623                        });
4624
4625                        $modal.find('[js-consultation-stop]').on('click', function(e){
4626                            e.preventDefault();
4627                            $modal.arcticmodal('close');
4628                            $.ajax({
4629                                url: $$.urlPrefix + '/api/consultation/?stop',
4630                                xhrFields: {
4631                                    withCredentials: true
4632                                },
4633                                crossDomain: true,
4634                                dataType: 'json',
4635                                type: 'post',
4636                                success: function(response){
4637                                    if(response.work){
4638                                        $timeout(function(){
4639                                            $rootScope.work = response.work;
4640                                        });
4641                                    }
4642                                }
4643                            });
4644                        });
4645                    }
4646                });
4647            };
4648
4649            $rootScope.read = function(){
4650                $$.openModal({
4651                    url: $$.urlPrefix + '/api/consultation/?read',
4652                    ajax: {
4653                        xhrFields: {
4654                            withCredentials: true
4655                        },
4656                        crossDomain: true
4657                    },
4658                    afterOpen: function(modal, $modal, modalResponse){
4659                        $modal.find('.consultation-answer-form').formHandle({
4660                            success: function(response){
4661                                $modal.arcticmodal('close');
4662                                if(response.work){
4663                                    $timeout(function(){
4664                                        $rootScope.work = response.work;
4665                                        $rootScope.request = null;
4666                                    });
4667                                }
4668
4669
4670                            }
4671                        });
4672
4673                        $modal.find('[js-consultation-request-reject]').on('click', function(){
4674                            $$.openModal('consultation-request-reject-form', {
4675                                afterOpen: function(modal, $m){
4676                                    $m.find('textarea').focus();
4677                                    $m.find('form').formHandle({
4678                                        success: function(response){
4679                                            $m.arcticmodal('close');
4680                                            $modal.arcticmodal('close');
4681                                            if(response.work){
4682                                                $timeout(function(){
4683                                                    $rootScope.work = response.work;
4684                                                    $rootScope.request = null;
4685                                                });
4686                                            }
4687                                        }
4688                                    });
4689                                }
4690                            })
4691                        });
4692
4693                        $modal.find('[js-consultation-request-approve]').on('click', function(){
4694                            $.ajax({
4695                                url: $$.urlPrefix + '/api/consultation/?requestApprove',
4696                                xhrFields: {
4697                                    withCredentials: true
4698                                },
4699                                crossDomain: true,
4700                                dataType: 'json',
4701                                type: 'post',
4702                                success: function(response){
4703                                    if(response.error){
4704                                        $$.alert(response.error['#']);
4705                                    }else{
4706                                        $modal.arcticmodal('close');
4707                                        $timeout(function(){
4708                                            $rootScope.work = response.work;
4709                                            $rootScope.request = response.request;
4710                                        });
4711                                        $rootScope.read();
4712                                    }
4713                                }
4714                            });
4715
4716                        });
4717                    }
4718                });
4719            };
4720
4721            $socket.on('consultation_work', function(response){
4722                if(response.work){
4723                    $rootScope.work = response.work;
4724                }
4725                if(response.request){
4726                    $rootScope.request = response.request;
4727                    audio.play();
4728                }
4729            });
4730
4731
4732            window.consultationInfo = function(listManager, options){
4733                if($rootScope.request && $rootScope.request.question_id == options.id){
4734                    $rootScope.read();
4735                }else{
4736                    $$.openModal({
4737                        url: $$.urlPrefix + '/api/consultation/?info',
4738                        ajax: {
4739                            xhrFields: {
4740                                withCredentials: true
4741                            },
4742                            crossDomain: true
4743                        },
4744                        data: {id: options.id},
4745                        afterOpen: function(modal, $modal, modalResponse){
4746                            var $consultationQuestion = $('[js-consultation]');
4747
4748                            if($consultationQuestion.length){
4749                                $.ajax({
4750                                    url: $$.urlPrefix + '/api/astroChart/?consultation',
4751                                    type: 'post',
4752                                    dataType: 'json',
4753                                    data: {id: options.id},
4754                                    success: function(data){
4755                                        buildCircleInner(data[0], 28, 510, 510);
4756                                    }
4757                                });
4758                            }
4759                        }
4760                    });
4761                }
4762            };
4763
4764            $rootScope.$watch('work', function(){
4765                var $list = $('#office-consultation-list').find('.list');
4766                if($list.length && $list.data('listManager')){
4767                    $list.data('listManager').load();
4768                }
4769            });
4770
4771
4772            $('[js-consult-start]').on('click', function(e){
4773                e.preventDefault();
4774                $rootScope.settings();
4775            })
4776        });
4777
4778    $(function(){
4779        $consultation = $('.consultation');
4780        if($consultation.length){
4781            angular.bootstrap($consultation[0], ['consultation']);
4782        }
4783    });
4784
4785    window.consultationQuestionInfo = function(listManager, options){
4786        $$.openModal({
4787            url: $$.urlPrefix + '/api/consultationQuestion/?info',
4788            ajax: {
4789                xhrFields: {
4790                    withCredentials: true
4791                },
4792                crossDomain: true
4793            },
4794            data: {id: options.id},
4795            afterOpen: function(modal, $modal, modalResponse){}
4796        });
4797    };
4798
4799}());
4800
4801
4802$(function(){
4803
4804    $$.document.on('click', '[js-data]', function(e){
4805		e.preventDefault();
4806        var id = $(this).attr('js-data');
4807
4808        $$.openModal({
4809            url: $$.urlPrefix + '/api/data/',
4810            data: {id: id},
4811            afterOpen: function(modal, $modal, modalResponse){
4812
4813            }
4814        });
4815    });
4816
4817    $$.document.on('click', '[js-data-print]', function(){
4818        var id = $(this).attr('js-data-print');
4819        window.open('/api/data/?id='+id+'&print');
4820    });
4821
4822    $$.document.on('click', '[js-data-export]', function(){
4823        var id = $(this).attr('js-data-export');
4824        window.open('/api/data/?id='+id+'&export');
4825    });
4826
4827});
4828$(function(){
4829    var regions = [];
4830
4831    $('.determine-time-result').hide();
4832    $('.determine-time form').formHandle({
4833        beforeSubmit: function(){
4834            $('.determine-time-result').hide(300);
4835            $('.determine-time-result_table').empty();
4836
4837            $('.determine-time-result__admin').hide(300);
4838            $('.determine-time-result_table__admin').empty();
4839        },
4840        afterSuccess: function(response){
4841
4842            if(response.build_circle){
4843                $('.determine-time-result').show(600);
4844                $('.determine-time-result_table').append(createTable(response));
4845
4846                $('.determine-time-result__admin').show(600);
4847                $('.determine-time-result_table__admin').append(response.dd_points);
4848
4849                $('.svg-container').css('padding-bottom', '100%');
4850                buildCircleInner(response.dateEphemeris, 70 , 800, 800);
4851            }else{
4852                $('.determine-time-result').show(600);
4853                $('.determine-time-result__admin').show(600);
4854                $('.determine-time-result_table__admin').append(response.dd_points);
4855            }
4856        }
4857    });
4858
4859/* ***************************** ТЕСТ Калибровка! ************************** */
4860    $('.determine-time-colibr form').formHandle({
4861        beforeSubmit: function(){
4862            $('.determine-time-result').hide(300);
4863            $('.determine-time-result_table').empty();
4864        },
4865        afterSuccess: function(response){
4866            $('.determine-time-result').show(600);
4867            $('.svg-container').css('padding-bottom', '100%');
4868            buildCircleInner(response.dateEphemeris, 70 , 800, 800, 'calibration');
4869        }
4870    });
4871    /* ************************************************************ */
4872
4873    if($('#datetimepicker12').length){
4874        $$.setDatetimePicker(false);
4875    }
4876
4877
4878    function getRegion(region_id){
4879        $.ajax({
4880            url: $$.urlPrefix + '/api/chooseRegionId/',
4881            data: {region_id: region_id},
4882            dataType: 'json',
4883            type: 'get',
4884            cache: true,
4885            xhrFields: {
4886                withCredentials: true
4887            },
4888            crossDomain: true,
4889            success: function(response){
4890                if(response){
4891                    return response;
4892                }
4893                return null;
4894            }
4895        });
4896    }
4897    
4898    function createTable(data) {
4899        var tags = "<table>";
4900
4901        tags += "<tr>"
4902        tags += "<td>"+data.date+' часовой пояс '+data.offset+"</td>";
4903        tags += "<td>" + data.title +"</td>";
4904        tags += "</tr>";
4905
4906        tags += "<tr>"
4907        // tags += "<td>" + data.chartUserHouseSymbol + "</td>";
4908        tags += "<td>" + "</td>";
4909        //tags += "<td>" + "Широта: " + $$.getLatFormatted(data.lat) + ", Долгота: " + $$.getlngFormatted(data.lng)+ "</td>";
4910        tags += "</tr>";
4911
4912        tags += "</table>";
4913
4914        return tags;
4915    }
4916
4917    // function createCheckbox() {
4918    //     var $input = $('input[type=text][name^=region]'),
4919    //         $holder = $('.select-region-holder'),
4920    //         $inputId = $('input[name^=region_id]'),
4921    //         $choosed = $('.select-region-choosed'),
4922    //         $user_region = $('#user_region'),
4923    //         userRegionId = $('#user_region').data('user-region-id'),
4924    //         oldRegionId = $('#user_region').data('old-region-id'),
4925    //         regionId = $input.data('region-id'),
4926    //         $state_checkbox = $("#determine_time").prop('checked');
4927    //
4928    //     // $state_checkbox = $("#determine_time").prop('checked');
4929    //     if($state_checkbox){
4930    //
4931    //         if(userRegionId){
4932    //             $inputId.val(userRegionId);
4933    //         }
4934    //
4935    //         $input
4936    //             .closest('.form-input-field').append($holder)
4937    //             .closest('.form-input').append($inputId).append($choosed);
4938    //
4939    //         $.ajax({
4940    //             url: $$.urlPrefix + '/api/chooseRegionId/',
4941    //             data: {region_id: userRegionId},
4942    //             dataT
4942ype: 'json',
4943    //             type: 'get',
4944    //             cache: true,
4945    //             xhrFields: {
4946    //                 withCredentials: true
4947    //             },
4948    //             crossDomain: true,
4949    //             success: function(response){
4950    //                 if(response){
4951    //                     regions = response;
4952    //                     $input.val(regions[0][2] + ' (' + regions[0][5] + ')' );
4953    //                 }
4954    //             }
4955    //         });
4956    //
4957    //         $input.attr('disabled', 'disabled');
4958    //         $input.show();
4959    //         $choosed.attr('disabled', 'disabled');
4960    //         $choosed.addClass('mod-user-region');
4961    //         if($choosed.text()){
4962    //             $choosed.hide();
4963    //         }
4964    //     }else{
4965    //         if($choosed.data('mod')){
4966    //             $input.hide();
4967    //             $choosed.show();
4968    //         }else{
4969    //             $input.val('');
4970    //         }
4971    //
4972    //         if(oldRegionId){
4973    //             $inputId.val(oldRegionId);
4974    //         }else{
4975    //             $inputId.removeAttr('value');
4976    //         }
4977    //         $input.removeAttr('disabled');
4978    //         $choosed.removeAttr('disabled');
4979    //         $choosed.removeClass('mod-user-region');
4980    //     }
4981    // }
4982
4983});
4984
4985
4986
4987$(function () {
4988
4989    var mql = window.matchMedia("(orientation: portrait)");
4990
4991    mql.addListener(function(m) {
4992        if($('.svg-content').length){
4993            if(m.matches) {
4994                $('.determine-time form').submit();
4995            }else {
4996                $('.determine-time form').submit();
4997            }
4998        }
4999    })
5000
5001});
5002
5003
5004
5005$(function(){
5006
5007    var $emoji,
5008        $context,
5009        request;
5010
5011    function loadEmoji(){
5012        if(request){
5013            return;
5014        }
5015        request = $.ajax({
5016            url: $$.urlPrefix + '/api/emoji/',
5017            type: 'get',
5018            cache: true,
5019            dataType: 'json',
5020            success: function(emoji){
5021                var body = '';
5022                body += '<div class="emoji">';
5023                emoji.forEach(function(item){
5024                    body += '<a href="#" data-code="'+item.code+'" class="emoji-item"><img src="'+item.src+'" class="emoji-smile" alt=""></a>';
5025                });
5026                body += '</div>';
5027                $emoji = $(body);
5028                // keep the caret in the field while picking
5029                $emoji.on('mousedown', '.emoji-item', function(e){
5030                    e.preventDefault();
5031                });
5032                $emoji.on('click', '.emoji-item', function(e){
5033                    e.preventDefault();
5034                    attachItem($(this).attr('data-code'));
5035                });
5036                // the panel grows as images load, so place it again
5037                $emoji.find('img').on('load', placeEmoji);
5038                $emoji.appendTo($('body')).hide();
5039                if($context){
5040                    openEmoji($context);
5041                }
5042            },
5043            error: function(){
5044                // let the next click retry instead of staying broken
5045                request = null;
5046            }
5047        });
5048    }
5049
5050    function placeEmoji(){
5051        if(!$emoji || !$context || !$emoji.is(':visible')){
5052            return;
5053        }
5054
5055        var contextOffset = $context.offset(),
5056            $window = $(window),
5057            top = contextOffset.top - $emoji.outerHeight() - 5,
5058            left = Math.min(contextOffset.left, $window.scrollLeft() + $window.width() - $emoji.outerWidth() - 10);
5059
5060        if(top < $window.scrollTop() + 5){
5061            top = contextOffset.top + $context.outerHeight() + 5;
5062        }
5063
5064        $emoji.css({
5065            top: top,
5066            left: Math.max(left, 10)
5067        });
5068    }
5069
5070    function closeEmoji(){
5071        if($emoji){
5072            $emoji.hide();
5073        }
5074        $context = null;
5075    }
5076
5077    function openEmoji($button){
5078        // a second click on the same button closes the panel
5079        if($emoji && $emoji.is(':visible') && $context && $context.is($button)){
5080            closeEmoji();
5081            return;
5082        }
5083
5084        $context = $button;
5085        if(!$emoji){
5086            loadEmoji();
5087            return;
5088        }
5089
5090        $emoji.show();
5091        placeEmoji();
5092    }
5093
5094    function insertAtCaret($input, code){
5095        var input = $input[0],
5096            value = $input.val(),
5097            start = typeof input.selectionStart === 'number' ? input.selectionStart : value.length,
5098            end = typeof input.selectionEnd === 'number' ? input.selectionEnd : value.length,
5099            before = value.slice(0, start),
5100            after = value.slice(end),
5101            text = (before && !/\s$/.test(before) ? ' ' : '') + code + (/^\s/.test(after) ? '' : ' ');
5102
5103        $input.val(before + text + after);
5104        if(input.setSelectionRange){
5105            input.setSelectionRange(before.length + text.length, before.length + text.length);
5106        }
5107        $input.trigger('focus').trigger('input');
5108    }
5109
5110    function attachItem(code){
5111        if(!$context){
5112            return;
5113        }
5114
5115        var $input = $context.parent().find('input, textarea').eq(0);
5116        if($input.length){
5117
5118            if(window.emojiController){
5119                window.emojiController.timeout(function(){
5120                    if(!window.emojiController.scope.text){
5121                        window.emojiController.scope.text = '';
5122                    }
5123                    window.emojiController.scope.text += (window.emojiController.scope.text.match(/ $/) ? '' : ' ') + code;
5124                });
5125            }else{
5126                insertAtCaret($input, code);
5127            }
5128
5129        }
5130    }
5131
5132    $$.document.on('click', '[js-emoji]', function(){
5133        openEmoji($(this));
5134    });
5135
5136    // one shared "click outside" handler: the old $(document).one('click') added on every open
5137    // piled up and closed the panel right after the next open
5138    $$.document.on('click', function(e){
5139        if(!$emoji || !$emoji.is(':visible')){
5140            return;
5141        }
5142        var $target = $(e.target);
5143        if($target.closest('.emoji, [js-emoji]').length){
5144            return;
5145        }
5146        // the button sits inside <label class="form-input">, so the browser repeats the click on the textarea;
5147        // clicks in the field itself (also moving the caret) keep the panel open
5148        if($context && $target.is('input, textarea') && $target.closest($context.parent()).length){
5149            return;
5150        }
5151        closeEmoji();
5152    });
5153
5154    $$.document.on('keydown', function(e){
5155        if(e.keyCode === 27 && $emoji && $emoji.is(':visible')){
5156            closeEmoji();
5157        }
5158    });
5159
5160    $(window).on('resize', placeEmoji);
5161
5162    window.openEmoji = openEmoji;
5163
5164});
5165$(function(){
5166    var table = $('#express_table'),
5167        express = $('.mod-express');
5168
5169    table.find('.analytics-table-content .analytics-table-col__coef').click(function(){
5170        $(this).toggleClass('active_coef');
5171    });
5172
5173    $$.document.on('click', '#button_express_save', function(e) {
5174        e.preventDefault();
5175        var arr = {};
5176        table.find('tr.express_element').each(function () {
5177            var tr_coef = $(this).find('.analytics-table-col__coef'),
5178                match_id = $(this).data('id'), arr_coef = {};
5179
5180            tr_coef.each(function () {
5181                var th_coef = $(this);
5182                if(th_coef.hasClass('active_coef')){
5183                    var tupe_coef = th_coef.data('coef');
5184                    // arr_coef.push(tupe_coef);
5185                    arr_coef[tupe_coef] = tupe_coef;
5186                }
5187            });
5188            // if(arr_coef.length > 0){
5189            if(!$.isEmptyObject(arr_coef)){
5190                arr[match_id] = arr_coef;
5191            }
5192        });
5193
5194        if(express && !$.isEmptyObject(arr)){
5195            var express_id = express.data('id');
5196            $.ajax({
5197                url: $$.urlPrefix + '/api/express/?express_user',
5198                type: 'post',
5199                dataType: 'json',
5200                data: {id: express_id, arr: arr},
5201                success: function(data, $form){
5202                    var $message = express.find('.office-data-saved');
5203                    $message.animate({
5204                        opacity: 1
5205                    }, 300);
5206
5207                    setTimeout(function(){
5208                        $message.stop().animate({
5209                            opacity: 0
5210                        }, 150);
5211                    }, 3000);
5212                }
5213
5214            });
5215        }
5216
5217
5218        // console.log($.parseJSON(arr));
5219    });
5220});
5221(function(){
5222
5223	window.forumPostAdd = function(listManager, options){
5224		if(!$$.isAuthenticated){
5225			$$.openAuth();
5226			return false;
5227		}
5228
5229		$$.openModal({
5230			url: '?get',
5231			data: {id: options.id, category_id: $('.page-menu-item.is-active').data('id')},
5232			afterOpen: function(modal, $modal){
5233				$modal.find('form').formHandle({
5234					overlay: true,
5235					afterData: function($form, data){
5236						if(data.error && data.error['#']){
5237							$$.init.payment($('.modal-box.modal-box-message'));
5238						}
5239					},
5240					success: function(e, $modal){
5241						$modal.arcticmodal('close');
5242						listManager.load();
5243					}
5244				});
5245			}
5246		});
5247	};
5248
5249
5250
5251
5252})();
5253
5254$(function(){
5255	if($('[js-live-comments]').length){
5256		var $liveComments = $('[js-live-comments]');
5257		socket.join('forum-live');
5258		socket.on('forum-add-comment', function(response){
5259			var $new = $(response.comment);
5260			$new.hide();
5261			var $last = $liveComments.find('.box-comment:last');
5262			console.log($last);
5263			$liveComments.prepend($new);
5264            $new.slideDown();
5265			$last.slideUp(300, function(){
5266				$last.remove();
5267			});
5268
5269		});
5270	}
5271});
5272$(function () {
5273    if ( !$.fn.fancybox ) return;
5274
5275    $.extend($.fancybox.defaults, {
5276        openEffect: 'elastic',
5277        closeEffect: 'elastic',
5278        // nextEffect: 'fade',
5279        // prevEffect: 'fade',
5280	    titleShow: true,
5281        helpers:  {
5282	        title: 'outside',
5283            overlay : {
5284                locked: true
5285            }
5286        }
5287    });
5288
5289	$(window).on('load', function(){
5290		$('.article-widget-image-img').each(function(key, item){
5291			var $item = $(this),
5292				width = $item.find('img').width(),
5293				nwidth = $item.find('img')[0].naturalWidth;
5294
5295			if(nwidth / width > 1.5){
5296				$item.addClass('mod-popup').on('click', function(){
5297					$.fancybox.open([{ href : $item.find('img').attr('src'), title : $item.data('title')}]);
5298				});
5299
5300			}
5301		});
5302	});
5303
5304
5305/*    $('.fancybox-image').fancybox({
5306        type: 'image',
5307	    beforeShow : function() {
5308		    this.title = this.element.data('title');
5309	    }
5310    });*/
5311
5312    $('.article-gallery a').fancybox({
5313        type: 'image',
5314	    beforeShow : function() {
5315		    this.title = this.element.data('title');
5316	    }
5317    });
5318});
5319
5320$(function(){
5321
5322    if ( screen.width < 1050 ) return;
5323
5324    var $document = $$.document,
5325        $header = $('.header'),
5326        scrollTop = $document.scrollTop();
5327
5328    $document.on('scroll', function(){
5329        if($document.scrollTop() > 118 + 50){
5330
5331            if(scrollTop < $document.scrollTop() /* && $document.scrollTop() < $.documentHeight() - $.windowHeight() - 100 */ ){
5332                $header.addClass('is-compact');
5333            }else{
5334                $header.removeClass('is-compact');
5335            }
5336
5337        }else{
5338            $header.removeClass('is-compact');
5339        }
5340
5341        scrollTop = $document.scrollTop();
5342    });
5343
5344});
5345
5346
5347$(function(){
5348
5349    var $search = $('[js-header-search]');
5350    var $button = $search.find('button');
5351    var $caption = $button.find('span'),
5352        caption = $caption.text();
5353
5354    $button.off('.search-toggle').on('click.search-toggle', function (e) {
5355        if ( !$search.hasClass('is-open') ) {
5356            $search.addClass('is-open').find('input').focus();
5357            $caption.text('Найти');
5358            e.preventDefault();
5359
5360            $$.$body.on('click.search-close', function (e) {
5361                if ( $(e.target).closest($search).length ) return;
5362
5363                $$.$body.off('.search-close');
5364                $search.removeClass('is-open');
5365                $caption.text(caption);
5366            });
5367        }
5368    });
5369
5370});
5371
5372
5373
5374$(function() {
5375    var $body = $('body');
5376
5377    var now = new Date().toLocaleString();
5378    // const Swal = require('sweetalert2');
5379
5380    $('.horar').each(function() {
5381        var $horar = $(this),
5382            $list = $horar.find('.horar-list'),
5383            $count = $horar.find('.horar-head-count');
5384
5385        var lock;
5386
5387        function countRecalc(){
5388            $count.text($horar.find('.mod-horar-item').length ? $horar.find('.mod-horar-item').length : 0);
5389        }
5390        countRecalc();
5391
5392        $horar.on('click', 'a.delete', function(e){
5393            e.preventDefault();
5394
5395            Swal.fire({
5396                title: 'Удалить хорар?',
5397                text: "Ваш вопрос будет удален из базы без возможности восстановления",
5398                icon: 'question',
5399                showCancelButton: true,
5400                confirmButtonColor: '#d33',
5401                cancelButtonColor: '#3085d6',
5402                confirmButtonText: 'Да, удалить',
5403                cancelButtonText: 'Отмена',
5404            }).then((result) => {
5405                if (result.isConfirmed) {
5406
5407                    if(lock) return; lock = true;
5408                    var $button = $(this),
5409                        $item = $button.closest('.mod-horar-item');
5410
5411                    $item.addClass('is-loading');
5412
5413                    $.ajax({
5414                        url: '?horarAction=delete',
5415                        type: 'post',
5416                        data: {horarId: $item.data('id')},
5417                        dataType: 'json',
5418                        success: function(response){
5419                            if(response.deleted){
5420                                $list.find('.horar-form').remove();
5421                                $item.remove();
5422                                Swal.fire(
5423                                    'Удалено!',
5424                                    '',
5425                                    'success'
5426                                )
5427
5428                            }else if(response.success){
5429                                $item.html($(response.success).html());
5430                            }
5431
5432                            countRecalc();
5433
5434                        },
5435                        complete: function(){
5436                            $item.removeClass('is-loading');
5437                            lock = false;
5438                        }
5439                    });
5440
5441                }
5442            })
5443
5444        });
5445
5446
5447        $horar.on('click', 'a.edit', function(e){
5448            e.preventDefault();
5449            if(lock) return; lock = true;
5450            var $button = $(this),
5451                $item = $button.closest('.mod-horar-item');
5452
5453            $$.openHorarModal($(this).data('tab'), {closeOnOverlayClick: false, closeOnEsc: false}, true, $item);
5454            lock = false;
5455
5456
5457        });
5458
5459        $body.on('submit', '.modal-horar-choose form', function(e){
5460            e.preventDefault();
5461
5462            var $form = $(this),
5463                $horarId = $form.data('id'),
5464                $input_r = $form.find('input[type=text][name^=region]'),
5465                $input_id = $form.find('input[name^=region_id][value]'),
5466                userRegionId = $('#user_region').data('user-region-id'),
5467                form_data;
5468            $$.uniFormError($form);
5469
5470            if(lock) return;
5471            lock = true;
5472
5473            form_data = $form.serialize() + '&region_val=' + $input_r.val() + '&region_id=' + $input_id.val() + '&horarId=' + $horarId;
5474
5475            $.ajax({
5476                url: '?horarAction=add',
5477                data: form_data,
5478                dataType: 'json',
5479                type: 'post',
5480                success: function(response){
5481                    var element_err;
5482                    if(response.success){
5483                        var $horar = $(response.success);
5484                        $form.closest('.modal-box').slideUp();
5485                        $body.find('.arcticmodal-container').arcticmodal('close');
5486                        if($horarId){
5487                            $list.find("[data-id='" + $horarId + "']").replaceWith($horar);
5488                        }else{
5489                            $list.prepend($horar);
5490                        }
5491
5492                        countRecalc();
5493                    }else if(response.error){
5494                        $form.find("input[name^="+response.error[0]['name']+"][value]").attr( 'placeholder', response.error[0]['title']);
5495                    }
5496                },
5497                complete: function(){
5498                    lock = false;
5499                }
5500            });
5501
5502        });
5503    });
5504
5505    $$.openHorarModal = function(type, options, edit, item){
5506        var horarId = item ? item.data('id') : false;
5507        $$.openModal({
5508            url: '?horarAction=addEdit',
5509            data: {horarId: horarId},
5510            closeOnEsc: false,
5511            closeOnOverlayClick: false,
5512            afterOpen: function(modal, $modal, modalResponse){
5513
5514                $('[js-choose-region_horar]').chooseRegion();
5515
5516                $$.createCheckbox();
5517                $modal.on('change', 'input[name^=determine_time]', function(){
5518                    var $input = $(this),
5519                        $state_checkbox = $input.prop('checked');
5520                    $$.createCheckbox($state_checkbox);
5521                });
5522                if(!horarId){
5523                    $modal.find('input[name="date"]').val(now);
5524                }
5525
5526            },
5527            beforeClose: function(){
5528                $('.select-region-holder').remove();
5529            }
5530        });
5531    };
5532
5533    $('[js-horar-open]').on('click', function (e) {
5534        e.preventDefault();
5535        $$.openHorarModal($(this).data('tab'), {closeOnOverlayClick: false, closeOnEsc: false}, false, false);
5536    });
5537
5538});
5539
5540
5541$(function() {
5542    // $('.mod-horar_aspects_list').on('click', '.accordion',function() {
5543    //     console.log(222);
5544    // });
5545    $('.mod-horar_aspects_list').on('click', '.accordion',function() {
5546        $(this).toggleClass("active");
5547        var panel = $(this).closest('.accord-item-head').next('.accord-panel'),
5548            event_horar;
5549
5550        var $horarQuestion = panel.find('[js-horar]');
5551        if($horarQuestion.length){
5552            event_horar = 'event__horar_' + $horarQuestion.data('id');
5553            $.ajax({
5554                url: $$.urlPrefix + '/api/horaryQuestion/?horar_question',
5555                type: 'post',
5556                dataType: 'json',
5557                data: {id: $horarQuestion.data('id'), event_type: event_horar},
5558                success: function(data){
5559                    buildCircleInner(data[0]);
5560                }
5561            });
5562        }
5563
5564        if (panel.height() > 0) {
5565            panel.css('max-height', '0');
5566        } else {
5567            panel.css('max-height', panel.prop('scrollHeight')+800);
5568        }
5569    });
5570
5571    $('.mod-horar_aspects_list').on('click', '.private-visibilidad',function() {
5572        var $this = $(this),
5573            $this_accord = $this.closest('.accord-item-private'),
5574            $item = $this_accord.closest('.mod-horar-item'),
5575            $horar_visibil;
5576
5577        if(!$this.hasClass('visibilidad')){
5578            $horar_visibil = 1;
5579        }else{
5580            $horar_visibil = 0;
5581        }
5582
5583        $.ajax({
5584            url: '?horarAction=modify',
5585            type: 'post',
5586            data: {horarId: $item.data('id'), horar_visibil: $horar_visibil},
5587            dataType: 'json',
5588            success: function(response){
5589                if(response.modifyd){
5590                    if($horar_visibil == 0){
5591                        $this.removeClass('visibilidad').addClass('hide-visibilidad');
5592                    }else{
5593                        $this.addClass('visibilidad').removeClass('hide-visibilidad');
5594                    }
5595                }else if(response.success){
5596                    $item.html($(response.success).html());
5597                }
5598            },
5599        });
5600    });
5601
5602});
5603
5604function CopyTextHorar(zet) {
5605    var inp =document.createElement('input');
5606    document.body.appendChild(inp);
5607    inp.value =zet;
5608    inp.select();
5609    document.execCommand('copy',false);
5610    inp.remove();
5611}
5612
5613$(function(){
5614    var $horoscope = $('[js-horoscope]');
5615    var $modal = $horoscope.find('.horoscope-signs-modal');
5616    var $current = $horoscope.find('.horoscope-signs-current');
5617    var Tabs = Helper.createTabs({
5618        parent: $horoscope,
5619        tabs: $('[js-horoscope-tab]', $horoscope),
5620        panes: $('[js-horoscope-pane]', $horoscope)
5621    });
5622
5623    $horoscope.removeClass('is-open');
5624
5625	$modal.on('click', '[horoscope-sign]', function(){
5626		$.ajax({ url: $$.urlPrefix + '/news/?zodiac-change', data: {zodiac: $(this).attr('horoscope-sign')}, type: 'post'});
5627	});
5628
5629    $horoscope.off('.horoscope').on({
5630        'tabChange.horoscope': function (e) {
5631            $$.$body.off('.horoscope-close');
5632            $horoscope.removeClass('is-open');
5633        }
5634    });
5635
5636    $current.off('click').on('click', function (e) {
5637        if ( $horoscope.hasClass('is-open') ) return;
5638
5639        $horoscope.addClass('is-open');
5640
5641        setTimeout(function(){
5642            $$.$body.off('.horoscope-close').on('click.horoscope-close', function (e) {
5643                if ( $(e.target).closest($modal).length ) return;
5644
5645                $horoscope.removeClass('is-open');
5646                $$.$body.off('.horoscope-close');
5647            });
5648        }, 10)
5649    });
5650});
5651
5652$(function(){
5653    $('.information-tablo').each(function(){
5654        var $tablo = $(this);
5655        var $close = $tablo.find('.information-tablo__close');
5656        var $footer = $('.footer');
5657        var $window = $(window);
5658        var $document = $(document);
5659
5660        var scroll = function(){
5661            var footerHeight = $footer.height() + 100;
5662            var documentHeight = $document.height();
5663            var windowHeight = $window.height();
5664            var scrollTop = $document.scrollTop();
5665
5666            if(documentHeight - windowHeight - scrollTop < footerHeight){
5667                $tablo.addClass('is-close');
5668            }else{
5669                $tablo.removeClass('is-close');
5670            }
5671        };
5672
5673        Ya.share2($tablo.find('.ya-share2')[0], {
5674            content: {
5675                url: 'http://astrology.pro/'
5676            },
5677            theme: {
5678                services: 'vkontakte,facebook,odnoklassniki'
5679            },
5680            hooks: {
5681                onshare: function(name) {
5682                    $close.click();
5683
5684                    $.ajax({
5685                        url: '/api/shareSite/',
5686                        data: {provider: name},
5687                        dataType: 'json',
5688                        type: 'post'
5689                    });
5690                }
5691            }
5692        });
5693
5694        $close.on('click', function(e){
5695            e.preventDefault();
5696            $tablo.addClass('is-close');
5697            $window.off('.information-tablo');
5698        });
5699
5700        $window.on('scroll.information-tablo', scroll);
5701        scroll();
5702    });
5703});
5704$(function () {
5705    var $intro = $('.intro');
5706    if (!$intro.length)
5707        return;
5708    var $introPages = $('.intro-page');
5709    var $introButtons = $('.intro-buttons');
5710    var renderer = new PIXI.autoDetectRenderer($intro.width(), $intro.height(), { transparent: true }), stage = new PIXI.Container();
5711    $intro.append(renderer.view);
5712    var cometColors = [0xFFFFFF, 0xffcc00, 0x55acee, 0xCDD6F5, 0x8e59dd], colors = [0xe6e6e6, 0xf9d7a7, 0xed812b, 0x9f6d26, 0xdda858, 0xb1f9f8, 0x536fc3], signs = ['☿', '♀', '♂', '♃', '♄', '♅', '♆'], speeds = [40, 27, 25, 17, 14, 9, 5], sizes = [5, 7, 6, 20, 18, 14, 14], step = (Math.PI / 180) * .2;
5713    var objects = [], objectIterator = 0, objectLimit = 1000, centerPosition, centerCicrle, circleTexture, fpsText;
5714    function initialize() {
5715        centerCicrle = new PIXI.Graphics();
5716        stage.addChild(centerCicrle);
5717        var circleGraphics = new PIXI.Graphics();
5718        circleGraphics.beginFill(0xFFFFFF, 1);
5719        circleGraphics.drawCircle(0, 0, 10);
5720        circleGraphics.endFill();
5721        circleGraphics.filters = [new PIXI.filters.BlurFilter()];
5722        circleTexture = circleGraphics.generateTexture();
5723        generate(signs.length);
5724        fpsText = new PIXI.Text('', { font: '24px "Open Sans"', fill: 0xFFFFFF, align: 'left' });
5725        fpsText.x = 10;
5726        fpsText.y = 10;
5727        stage.addChild(fpsText);
5728        render();
5729        requestAnimationFrame(animate);
5730    }
5731    function generate(limit) {
5732        for (var l = 0; l < limit; l++) {
5733            if (objectIterator > objectLimit) {
5734                break;
5735            }
5736            var i = objectIterator;
5737            if (signs[i]) {
5738                var object = PIXI.Sprite.fromImage(i == 4 ? '/images/intro-planet-rings.png' : '/images/intro-planet.png');
5739                var sign = signs[i];
5740                var scale = sizes[i] * .035; //.2 + Math.random() * .2;
5741                object.tint = colors[i]; //0xFFFFFF;
5742                object.scale.x = scale;
5743                object.scale.y = scale;
5744                object.alpha = 1;
5745                object.orbit = {
5746                    offset: Math.random() * 100000,
5747                    speed: speeds[i] * .02,
5748                    position: { x: Math.random(), y: Math.random(), radius: Math.random() * .5 }
5749                };
5750                objects.push(object);
5751                object.projection = new PIXI.Text(sign, { font: '22px Verdana', fill: 0xFFFFFF });
5752                object.relation = new PIXI.Graphics();
5753                stage.addChild(object.relation);
5754                stage.addChild(object);
5755                stage.addChild(object.projection);
5756            }
5757            else {
5758                var isComet = i % 250 == 0;
5759                var object = isComet ? PIXI.Sprite.fromImage('/images/intro-comet.png') : new PIXI.Sprite(circleTexture);
5760                var scale = isComet ? .2 + Math.random() * .3 : .1 + Math.random() * .2;
5761                object.tint = isComet ? cometColors[Math.round(Math.random() * (cometColors.length - 1))] : 0xFFFFFF;
5762                object.scale.x = scale;
5763                object.scale.y = scale;
5764                object.orbit = {
5765                    offset: Math.random() * 100000,
5766                    speed: isComet ? .1 + Math.random() * .1 : .1 + Math.random() * .5,
5767                    position: { x: Math.random(), y: Math.random(), radius: Math.random() }
5768                };
5769                object.alpha = isComet ? 1 : .1;
5770                objects.push(object);
5771                if (isComet) {
5772                    var shadowsTotal = 100;
5773                    object.shadows = [];
5774                    object.scale.x *= 2;
5775                    object.scale.y *= 2;
5776                    for (var j = 1; j < shadowsTotal; j++) {
5777                        var shadow = new PIXI.Sprite(circleTexture);
5778                        shadow.tint = object.tint;
5779                        shadow.alpha = (1 - j / shadowsTotal) * .05;
5780                        shadow.scale.x = scale * (1 - j / shadowsTotal);
5781                        shadow.scale.y = scale * (1 - j / shadowsTotal);
5782                        object.shadows.push(shadow);
5783                        stage.addChild(shadow);
5784                    }
5785                }
5786                stage.addChild(object);
5787            }
5788            objectIterator++;
5789        }
5790    }
5791    var pause = false, count = 0, highFps = 0, lastTime = 0;
5792    var animate = function (time) {
5793        if (pause)
5794            return;
5795        var fps = +(1 / ((time - lastTime) * 0.001)).toFixed(0);
5796        //fpsText.text = "FPS: " + fps;
5797        if (objectIterator < objectLimit) {
5798            if (fps > 30) {
5799                highFps += fps;
5800            }
5801            else if (highFps > 0) {
5802                highFps -= 30 - fps;
5803            }
5804            if (highFps > 120) {
5805                highFps = 0;
5806                generate(100);
5807                render();
5808            }
5809        }
5810        if (count == 50 && objectIterator < 10) {
5811            animate = function () { };
5812        }
5813        count++;
5814        for (var i in objects) {
5815            var object = objects[i];
5816            var position = {
5817                x: object.orbit.x + Math.sin((object.projection ? step : -step) * (count + object.orbit.offset) * object.orbit.speed) * object.orbit.distance,
5818                y: object.orbit.y + Math.cos((object.projection ? step : -step) * (count + object.orbit.offset) * object.orbit.speed) * object.orbit.distance
5819            };
5820            object.x = position.x - object.width / 2;
5821            object.y = position.y - object.height / 2;
5822            if (object.projection) {
5823                var projection = move(centerPosition, angle(centerPosition, position), centerPosition.radius);
5824                var distance = distanceSquare(position, projection);
5825                object.projection.x = projection.x - object.projection.width / 2;
5826                object.projection.y = projection.y - object.projection.height / 2;
5827                object.relation.clear();
5828                if (distance < 200000) {
5829                    object.relation.lineStyle(2, object.projection.tint, (1 - distance / 200000) * .2);
5830                    object.relation.moveTo(position.x, position.y);
5831                    object.relation.lineTo(projection.x, projection.y);
5832                }
5833            }
5834            for (var j in object.shadows) {
5835                var shadow = object.shadows[j];
5836                shadow.x = object.orbit.x + Math.sin((object.projection ? step : -step) * (count + object.orbit.offset - j / object.orbit.speed / 3) * object.orbit.speed) * object.orbit.distance - shadow.width / 2;
5837                shadow.y = object.orbit.y + Math.cos((object.projection ? step : -step) * (count + object.orbit.offset - j / object.orbit.speed / 3) * object.orbit.speed) * object.orbit.distance - shadow.height / 2;
5838            }
5839        }
5840        renderer.render(stage);
5841        requestAnimationFrame(animate);
5842        lastTime = time;
5843    };
5844    function render() {
5845        centerPosition = {
5846            x: renderer.width / 2,
5847            y: renderer.height / 2,
5848            radius: renderer.width * .13
5849        };
5850        if (centerPosition.radius < 235) {
5851            centerPosition.radius = 235;
5852        }
5853        centerCicrle.clear();
5854        centerCicrle.lineStyle(1, 0xFFFFFF, .1);
5855        centerCicrle.drawCircle(centerPosition.x, centerPosition.y, centerPosition.radius);
5856        for (var i in objects) {
5857            var object = objects[i];
5858            if (object.shadows) {
5859                object.orbit.x = renderer.width * object.orbit.position.x;
5860                object.orbit.y = object.orbit.position.y > 0.5 ? renderer.height : 0;
5861                object.orbit.distance = (renderer.height / 2 + centerPosition.radius * 2);
5862                object.orbit.distance += object.orbit.position.radius * (renderer.height - object.orbit.distance);
5863            }
5864            else {
5865                object.orbit.x = object.orbit.position.x > 0.5 ? renderer.width : 0;
5866                object.orbit.y = renderer.height * object.orbit.position.y;
5867                object.orbit.distance = (renderer.width / 2 + centerPosition.radius * 2);
5868                object.orbit.distance += object.orbit.position.radius * (renderer.width - object.orbit.distance);
5869            }
5870        }
5871    }
5872    initialize();
5873    $$.window.resize(function () {
5874        renderer.resize($intro.width(), $intro.height());
5875        render();
5876    });
5877    function angle(start, end) {
5878        return Math.atan2(end.y - start.y, end.x - start.x);
5879    }
5880    function move(point, angle, distance) {
5881        return { x: point.x + Math.cos(angle) * distance, y: point.y + Math.sin(angle) * distance };
5882    }
5883    function distanceSquare(start, end) {
5884        return Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2);
5885    }
5886    // $('.intro-buttons [button]').on('click', function (e) {
5887    //     e.preventDefault();
5888    //     var $button = $(this);
5889    //
5890    //     $button.addClass('is-active').siblings('[button]').removeClass('is-active');
5891    //
5892    //     $$.scrollTo($introPages.hide().filter('[data-page='+$button.data('page')+']').show(), 300, 150, function(){
5893    //         $$.document.trigger('scroll');
5894    //     });
5895    //
5896    // });
5897    $('.intro-buttons [img]').on('click', function (e) {
5898        e.preventDefault();
5899        $$.scrollTo($introButtons, 350, 150, function () {
5900            $$.document.trigger('scroll');
5901        });
5902    });
5903    $$.document.on('scroll', function () {
5904        if ($$.document.scrollTop() > renderer.height * .75) {
5905            pause = true;
5906        }
5907        else {
5908            if (pause) {
5909                requestAnimationFrame(animate);
5910            }
5911            pause = false;
5912        }
5913    });
5914});
5915
5916$(function(){
5917
5918    // //Slider
5919    // $('.slider__container').slick({
5920    //     nextArrow: '<div class="slick__btn slick__prev"><img class="slick__prev-img" src="img/slider-left.svg" alt=""></div>',
5921    //     prevArrow: '<div class="slick__btn slick__next"><img class="slick__next-img" src="img/slider-right.svg" alt=""></div>',
5922    //     infinite: true,
5923    //     dots: true
5924    // });
5925
5926    $('.landing_sport_slider').owlCarousel({
5927        dragEndSpeed: 600,
5928        loop: true,
5929        items: 1,
5930        stagePadding: 0,
5931        margin: 33,
5932        autoHeight: false,
5933        mouseDrag: true,
5934        nav: true,
5935        pagination : true,
5936        autoplay: false
5937    });
5938
5939    // $('.subscription__button').on('click', function (e) {
5940    //     e.preventDefault();
5941    //     $$.scrollTo($('.subscription__button'), 350, 150, function(){
5942    //         $$.document.trigger('scroll');
5943    //     });
5944    // });
5945
5946    $(".subscription__button").click(function(e) { // ID откуда кливаем
5947        e.preventDefault();
5948        $('html, body').animate({
5949            scrollTop: $(".subscription__inner").offset().top-80  // класс объекта к которому приезжаем
5950        }, 1000); // Скорость прокрутки
5951    });
5952
5953});
5954
5955//Button loader
5956const subs_buttons = document.querySelectorAll('.subscription__button');
5957
5958if(subs_buttons.length > 0){
5959    for(let i = 0; i < subs_buttons.length; i++){
5960        const subs_button = subs_buttons[i];
5961        subs_button.addEventListener('click', function(e){
5962            e.preventDefault();
5963            subs_button.classList.add('active_btn');
5964        });
5965    }}
5966
5967$(function(){
5968
5969    $$.document.on('click', '[js-picture-action]', function(e){
5970        e.preventDefault();
5971
5972        var $elem = $(this);
5973
5974        $.fancybox.open([{
5975            'href' : $elem.data('url'),
5976        }]);
5977    });
5978
5979
5980}());
5981(function(){
5982
5983    'use strict';
5984
5985    var Manager = function($root){
5986        $root = $($root);
5987
5988        var $loader_sport = $('<div class="loader-sport">\n' +
5989        '  <div class="ball one"><div class="inner"></div></div>\n' +
5990        '  <div class="ball two"><div class="inner"></div></div>\n' +
5991        '  <div class="ball three"><div class="inner"></div></div>\n' +
5992        '  <div class="ball four"><div class="inner"></div></div>\n' +
5993        '  <div class="ball five"><div class="inner"></div></div>\n' +
5994        '  <div class="ball six"><div class="inner"></div></div>\n' +
5995        '</div>');
5996
5997        var manager = this,
5998            request,
5999            $filters = $root.find('[js-filter]'),
6000            $controls = $root.find('[js-control]'),
6001            $control = $root.find('.list-controls'),
6002            $result = $root.find('.list-result'),
6003            $modes = $controls.filter('.mod-mode').find('[button]'),
6004            $pagination = $root.find('.list-pagination'),
6005            $total = $controls.filter('.mod-total');
6006
6007        $root.data('listManager', this);
6008
6009        $.extend(this, {
6010            element: $root,
6011
6012            trigger: function(){
6013                $root.trigger.apply($root, arguments)
6014            },
6015
6016            on: function(){
6017                $root.on.apply($root, arguments)
6018            },
6019
6020            off: function(){
6021                $root.off.apply($root, arguments)
6022            },
6023
6024            action: function(action, options, caller){
6025                options = options || {};
6026                if(window[action]){
6027                    window[action].call(this, manager, options, caller);
6028                }
6029            },
6030
6031            initialize: function(){
6032                manager.install($root.data('settings'));
6033                $root.addClass('is-initialized');
6034
6035                $filters.each(function(){
6036                    var $filter = $(this),
6037                        $values = $filter.find('[js-filter-value]');
6038
6039                    var slider = document.getElementById('slider_range');
6040
6041                    var padding_min = document.getElementById('slider-value-min'),
6042                        padding_max = document.getElementById('slider-value-max');
6043
6044                    switch($filter.data('type')){
6045                        case 'list':
6046
6047                            $filter.find('.selectus-orig').on('change','[js-selectus]',function(e){
6048                                e.preventDefault();
6049                                manager.load();
6050                            });
6051
6052                            break;
6053                        case 'list_analytics':
6054                            $filter.on('click', '[js-service-analytics-a]', function(e){
6055                                e.preventDefault();
6056
6057                                var analytics_a = $(this).parents('[js-service-analytics-a]'),
6058                                    $this = $(this),
6059                                    checkbox = $this.find('input
6059:checkbox'),
6060                                    button = $filter.find('.list-button'),
6061                                    filter_offset = $filter.siblings('.mod-date_offset'),
6062                                    offset_status = 1;
6063
6064                                switch($filter.data('name')){
6065                                    case 'dropdownAspects':
6066
6067                                        if($this.data('value') == 'all'){
6068                                            if (checkbox.is(":checked")) {
6069                                                e.preventDefault();
6070                                                return false;
6071                                            }
6072                                        }
6073                                        // else{
6074                                        //     if ($this.is(':checked')) {
6075                                        //         $filter.find('.dropdown_content input:checkbox').not(this).prop('checked', false);
6076                                        //     }
6077                                        // }
6078
6079                                        // if($filter.find('input:checkbox:checked').length == 0){
6080                                        //     checkbox.each(function(){
6081                                        //         if($(this).parents('[js-service-analytics-a]').data('value') == 'all'){
6082                                        //             $(this).prop('checked', true);
6083                                        //         }
6084                                        //     });
6085                                        // }
6086
6087                                        if (checkbox.is(':checked')){
6088                                            checkbox.prop('checked', false);
6089                                        } else {
6090                                            checkbox.prop('checked', true);
6091                                            if($this.data('value') == 'all'){
6092                                                $filter.find('input:checkbox:checked').each(function(){
6093                                                    if($(this).parents('[js-service-analytics-a]').data('value') != 'all'){
6094                                                        // offset_status = 3;
6095                                                        filter_offset.find('input[name^=offset_dropdown_analytics]').attr('data-status', 1);
6096                                                        $(this).prop('checked', false);
6097                                                    }
6098                                                });
6099                                            }else{
6100                                                $filter.find('input:checkbox:checked').each(function(){
6101                                                    if($(this).parents('[js-service-analytics-a]').data('value') == 'all'){
6102                                                        // offset_status = 1;
6103                                                        $(this).prop('checked', false);
6104                                                    }
6105                                                });
6106                                            }
6107                                        }
6108
6109                                        var checked = [], $i = 0;
6110                                        $filter.find('input:checkbox:checked').each(function(){
6111                                            checked.push($(this).parents('[js-service-analytics-a]').data('value'));
6112                                            $i++;
6113                                        });
6114
6115                                        if($i == 0){
6116                                            checked.push('all');
6117                                            $filter.find('input:checkbox').each(function(){
6118                                                if($(this).parents('[js-service-analytics-a]').data('value') == 'all'){
6119                                                    $(this).prop('checked', true);
6120                                                }
6121                                            });
6122                                        }
6123
6124
6125
6126                                        // offset_status = i > 5 ? 3 : offset_status;
6127                                        // filter_offset.find('input[name^=offset_dropdown_analytics]').attr('data-status', offset_status);
6128                                        // var offset_val = filter_offset.find('input[name^=offset_dropdown_analytics]').val();
6129                                        //
6130                                        // filter_offset.find('.dropdown_content').find('a').each(function(){
6131                                        //     if(offset_status != 1){
6132                                        //         if($(this).data('status') != 1){
6133                                        //             $(this).css('display', 'none');
6134                                        //         }
6135                                        //     }else{
6136                                        //         $(this).css('display', 'block');
6137                                        //     }
6138                                        // });
6139
6140                                        $filter.find('.dropdown-analytics').val(checked);
6141                                        $filter.find('.dropdown-analytics').data('name', $(this).text().trim());
6142                                        manager.setOffsetData();
6143
6144                                        if(button.hasClass('button-arrow-down-rotate')){
6145                                            button.text('Поиск...')
6146                                        }else {
6147                                            button.text('Аспекты')
6148                                        }
6149
6150                                        break;
6151
6152                                    case 'dropdownLeague':
6153                                        $filter.find('.dropdown-analytics').val($(this).data('value'));
6154                                        $filter.find('.dropdown-analytics').data('name', $(this).text().trim());
6155                                        manager.setOffsetData();
6156                                        manager.load();
6157                                        break;
6158                                }
6159
6160                            });
6161
6162                            break;
6163                        case 'date_offset':
6164                            $filter.on('click', '[js-checkbox-offset]', function(e){
6165                                e.preventDefault();
6166
6167                                $filter.find('input[name=offset_dropdown_analytics]').val($(this).data('value'));
6168                                $filter.find('input[name=offset_dropdown_analytics]').data('name', $(this).text().trim());
6169
6170                                manager.setOffsetData();
6171                                manager.load();
6172                            });
6173                            $('input[name^=input_offset]').on('change', function(e){
6174                                e.preventDefault();
6175                                manager.setOffsetData();
6176                                manager.load();
6177                            });
6178                            break;
6179                        case 'one_date':
6180                            $("#datetimepicker1").on("dp.change", function (e) {
6181                                e.preventDefault();
6182
6183                                manager.setOffsetData();
6184                                manager.load();
6185                            });
6186
6187                            break;
6188                        case 'searchAuthor':
6189                            $values.on('click', function(e){
6190                                e.preventDefault();
6191                                var $value = $(this);
6192
6193                                if($value.hasClass('is-active')){
6194                                    return;
6195                                }
6196
6197                                $value.addClass('is-active').siblings('[js-filter-value]').removeClass('is-active');
6198                                manager.load();
6199                            });
6200
6201                            break;
6202                        case 'search':
6203
6204                            $filter.find('form').on('submit', function(e){
6205                                e.preventDefault();
6206                                manager.load();
6207                            });
6208
6209                            break;
6210                        case 'radio':
6211                            $values.on('click', function(e){
6212                                e.preventDefault();
6213                                var $value = $(this);
6214
6215                                if($value.hasClass('is-active')){
6216                                    return;
6217                                }
6218
6219                                $value.addClass('is-active').siblings('[js-filter-value]').removeClass('is-active');
6220                                manager.load();
6221                            });
6222                            break;
6223                        case 'sort':
6224                            $values.on('click', function(e){
6225                                e.preventDefault();
6226                                var $value = $(this);
6227
6228                                if($value.hasClass('is-active')){
6229                                    $value.attr('data-order', $value.attr('data-order') == 'asc' ? 'desc' : 'asc');
6230                                }else{
6231                                    $value.addClass('is-active').siblings('[js-filter-value]').removeClass('is-active');
6232                                }
6233
6234                                manager.load();
6235                            });
6236                            break;
6237                        case 'tags':
6238                            $values.on('click', function(e){
6239                                e.preventDefault();
6240                                var $value = $(this);
6241                                $value.toggleClass('is-active');
6242
6243
6244                                if($values.filter('.is-active').length){
6245                                    $filter.find('[js-filter-reset]').removeClass('is-active');
6246
6247                                }else{
6248                                    $filter.find('[js-filter-reset]').addClass('is-active');
6249                                }
6250
6251                                manager.load();
6252                            });
6253                            $filter.find('[js-filter-reset]').on('click', function(e){
6254                                e.preventDefault();
6255                                var $button = $(this);
6256                                if(!$button.hasClass('is-active')){
6257                                    $button.addClass('is-active');
6258                                    $filter.find('[js-filter-value]').removeClass('is-active');
6259                                    manager.load();
6260                                }
6261                            });
6262                            break;
6263                        case 'tags_ext':
6264
6265                            $filter.on('click', '[js-filter-value]', function(e){
6266                                e.preventDefault();
6267                                var $value = $(this), count_val;
6268                                $value.toggleClass('is-active');
6269
6270                                count_val = 0;
6271                                $filter.find('[js-filter-value].is-active').each(function(){
6272                                    count_val++ ;
6273                                });
6274
6275                                if(count_val >= 0){
6276                                    $filter.find('[js-filter-reset]').removeClass('is-active');
6277                                }else{
6278                                    $filter.find('[js-filter-reset]').addClass('is-active');
6279                                }
6280                                manager.setOffsetData();
6281                                manager.load();
6282                            });
6283
6284                            $filter.on('click', '[js-filter-reset]', function(e){
6285                                e.preventDefault();
6286
6287                                var $button = $(this);
6288                                if(!$button.hasClass('is-active')){
6289                                    $button.addClass('is-active');
6290                                    $filter.find('[js-filter-value]').removeClass('is-active');
6291                                    manager.setOffsetData();
6292                                    manager.load();
6293                                }
6294                            });
6295
6296                            break;
6297                        case 'range':
6298
6299                            var range_session = JSON.parse(sessionStorage.getItem($filter.data('name'))),
6300                                data_min_def = -3,
6301                                data_max_def = 3;
6302
6303                            if(range_session){
6304                                data_min_def = range_session['data_min'];
6305                                data_max_def = range_session['data_max'];
6306                            }
6307
6308                            noUiSlider.create(slider, {
6309                                start: [data_min_def, data_max_def],
6310                                connect: true,
6311                                range: {
6312                                    'min': -3,
6313                                    'max': 3
6314                                },
6315                            });
6316
6317                            var data_min = -3,
6318                                data_max = 3;
6319
6320                            slider.noUiSlider.on('update', function (values, handle) {
6321
6322                                var table_class = slider.dataset.class_table,
6323                                    table_range = $('.'+table_class+'');
6324                                if (handle) {
6325                                    padding_max.innerHTML = values[handle];
6326                                    data_max = Number(values[handle]);
6327                                } else {
6328                                    padding_min.innerHTML = values[handle];
6329                                    data_min = Number(values[handle]);
6330                                }
6331
6332                                sessionStorage.setItem($filter.data('name'), JSON.stringify({'data_min': data_min, 'data_max': data_max}));
6333                                manager.changeRangeTable(table_range, data_min, data_max);
6334                            });
6335                            break;
6336                    }
6337
6338                });
6339
6340                $controls.filter('.mod-extra').each(function(){
6341                    var $control = $(this),
6342                        $button = $control.find('.list-extra-button'),
6343                        $popup = $control.find('.list-extra'),
6344                        $reset = $control.find('.list-extra-reset');
6345
6346                    $button.on('click', function(e){
6347                        e.preventDefault();
6348                        $control.toggleClass('is-opened');
6349                        if($control.hasClass('is-opened')){
6350
6351                            $popup.css('margin-right', 0);
6352                            var $place = $control.closest('.list-control
6352s'),
6353                                placeOffset = $place.offset().left,
6354                                placeWidth = $place.outerWidth(),
6355                                popupOffset = $popup.offset().left,
6356                                popupWidth = $popup.outerWidth(),
6357                                offset = (popupOffset - placeOffset + popupWidth) - placeWidth;
6358
6359                            $popup.css('margin-right', offset);
6360
6361                            $$.document.on('mousedown.list-extra', function(e){
6362                                if(!$.contains($control[0], e.target)){
6363                                    $$.document.off('.list-extra');
6364                                    $control.removeClass('is-opened');
6365                                }
6366                            });
6367
6368                        }else{
6369                            $$.document.off('.list-extra');
6370                        }
6371
6372                    });
6373
6374
6375                    $control.on('click', '[js-filter-reset]', function(e){
6376                        e.preventDefault();
6377
6378                        $control.find('[js-filter-value]').removeClass('is-active');
6379                        $button.removeClass('is-active').click();
6380                        manager.setOffsetData();
6381                        manager.load();
6382                    });
6383
6384                    $reset.on('click', function(e){
6385                        e.preventDefault();
6386
6387                        $control.find('[js-filter-value]').removeClass('is-active');
6388                        $button.removeClass('is-active').click();
6389                        manager.load();
6390                    });
6391
6392                });
6393
6394                $controls.filter('.mod-list').each(function(){
6395                    var $control = $(this),
6396                        // $button = $control.find('.button-arrow-down'),
6397                        $button = $control.find('.list-button'),
6398                        $button_offset = $control.find('.list-extra-button__offset'),
6399                        $popup = $control.find('.dropdown_content'),
6400                        $reset = $control.find('.list-extra-reset');
6401
6402                        $button.on('click', function(e){
6403                            e.preventDefault();
6404                            if($(this).attr('id') != 'dropdownAspects'){
6405                                $control.toggleClass('is-opened');
6406                                if($control.hasClass('is-opened')){
6407                                    $control.removeClass('is-opened');
6408                                }else{
6409                                    $control.addClass('is-opened');
6410                                }
6411                            }else if($(this).attr('id') == 'dropdownAspects'){
6412                                if($button.hasClass('button-arrow-down-rotate')){
6413                                    manager.load();
6414                                }
6415                            }
6416                            $$.document.on('mousedown.dropdown_content', function(e){
6417                                if(!$.contains($control[0], e.target)){
6418                                    $control.removeClass('is-opened');
6419                                    $popup.removeClass('is-opened');
6420                                    $button.removeClass('button-arrow-down-rotate').addClass('button-arrow-down');
6421                                    $button.each(function(){
6422                                        var button = $(this);
6423                                        if(button.attr('id') == 'dropdownAspects'){
6424                                            if(button.hasClass('button-arrow-down-rotate')){
6425                                                button.text('Поиск...')
6426                                            }else {
6427                                                button.text('Аспекты')
6428                                            }
6429                                        }
6430                                    });
6431                                }
6432                            });
6433                        });
6434
6435
6436
6437                    $button_offset.on('click', function(e){
6438                        e.preventDefault();
6439                        $control.toggleClass('is-opened');
6440                        if($control.hasClass('is-opened')){
6441                            $popup.css('margin-right', 0);
6442                            $$.document.on('mousedown.dropdown_content', function(e){
6443                                if(!$.contains($control[0], e.target)){
6444                                    $$.document.off('.dropdown_content');
6445                                    $control.removeClass('is-opened');
6446                                    $popup.removeClass('is-opened');
6447
6448                                    $button_offset.toggleClass('list-extra-button__hide');
6449                                }
6450                            });
6451                        }else{
6452                            $$.document.off('.dropdown_content');
6453                        }
6454                    });
6455
6456                    $reset.on('click', function(e){
6457                        e.preventDefault();
6458                        $control.find('[js-filter-value]').removeClass('is-active');
6459                        $button.removeClass('is-active').click();
6460                        manager.load();
6461                    });
6462
6463
6464                });
6465
6466                $modes.on('click', function(e){
6467                    e.preventDefault();
6468
6469                    var $button = $(this);
6470
6471                    if($button.hasClass('is-active')){
6472                        return;
6473                    }
6474
6475                    $modes.removeClass('is-active');
6476                    $button.addClass('is-active');
6477                    manager.load();
6478                });
6479
6480                $pagination.find('.list-pagination-numbers').on('click', '.list-pagination-number', function(e){
6481                    e.preventDefault();
6482                    var $page = $(this);
6483                    if(!$page.hasClass('is-active')){
6484                        $page.addClass('is-active').siblings('.list-pagination-number').removeClass('is-active');
6485                        manager.load({page: $page.data('page')});
6486                    }
6487
6488                });
6489
6490                $pagination.find('.list-pagination-append-link').on('click', function(e){
6491                    e.preventDefault();
6492                    $(this).closest('.list-pagination-append').addClass('is-loading');
6493                    manager.load({page: manager.page + 1});
6494                });
6495
6496                $pagination.find('.list-pagination-limits select').on('change', function(){
6497                    manager.load({limit: $(this).val()});
6498                });
6499
6500                $result.on('click', '[js-list-tag]', function(e){
6501                    e.preventDefault();
6502                    $filters.filter('[data-type="tags"]')
6503                        .find('[js-filter-value]').removeClass('is-active')
6504                        .filter('[data-value='+$(this).attr('js-list-tag')+']').click();
6505                });
6506
6507                $result.add($controls).on('click', '[js-list-action]', function(e){
6508                    e.preventDefault();
6509
6510                    var $button = $(this),
6511                        action = $button.attr('js-list-action'),
6512                        options = $button.data('options');
6513
6514
6515                    manager.action(action, options, $button);
6516                });
6517
6518                var sidebar_constructor = $('.sidebar_constructor');
6519                if (sidebar_constructor.length > 0) {
6520                    var button_c = sidebar_constructor.find('.offset-button_add');
6521                    button_c.on('click', function (e) {
6522                        e.preventDefault();
6523
6524                        var $button = $(this),
6525                            action = $button.attr('js-list-action'),
6526                            options = $button.data('options');
6527
6528                        manager.action(action, options, $button);
6529
6530                    });
6531                };
6532
6533            },
6534
6535
6536            install: function(settings, $newItems){
6537                manager.id = settings.listManager;
6538                manager.parameters = $.extend({}, manager.parameters, settings.parameters || {});
6539                manager.url = settings.url || '';
6540                manager.keepDomain = settings.keepDomain;
6541
6542                if($newItems){
6543                    Helper.createTabs({
6544                        tabs: $newItems.find('[js-articles-item-tab]'),
6545                        panes: $newItems.find('[js-articles-item-pane]'),
6546                        speed: 0,
6547                        hash: false,
6548                        openFirst: false,
6549                        closeOpened: true
6550                    });
6551
6552                    $$.init.tips($newItems);
6553                }else{
6554                    Helper.createTabs({
6555                        tabs: $result.find('[js-articles-item-tab]'),
6556                        panes: $result.find('[js-articles-item-pane]'),
6557                        speed: 0,
6558                        hash: false,
6559                        openFirst: false,
6560                        closeOpened: true
6561                    });
6562                }
6563
6564
6565                if(settings.filters){
6566                    $filters.each(function(){
6567                        var $filter = $(this),
6568                            filterName = $filter.data('name'),
6569                            filterValue = settings.filters[filterName],
6570                            slider = document.getElementById('slider_range');
6571
6572                        switch($filter.data('type')){
6573                            case 'one_date':
6574                                // filter.find('.list-extra-button').text('11111111');
6575                                // $filter.find('span').text('Архив за ' + calendar_date);
6576                                break;
6577                            case 'searchAuthor':
6578                                $filter.find('[js-filter-value]').removeClass('is-active').filter('[data-value="'+filterValue+'"]').addClass('is-active');
6579                                break;
6580                            case 'radio':
6581                                $filter.find('[js-filter-value]').removeClass('is-active').filter('[data-value="'+filterValue+'"]').addClass('is-active');
6582                                break;
6583                            case 'sort':
6584                                filterValue = filterValue.split('|');
6585                                $filter.find('[js-filter-value]').removeClass('is-active').filter('[data-value="'+filterValue[0]+'"]').addClass('is-active').attr('data-order', filterValue[1]);
6586                                break;
6587                            case 'tags':
6588                                $filter.find('[js-filter-reset]').toggleClass('is-active', !filterValue);
6589                                $filter.find('[js-filter-value]').removeClass('is-active').filter(function(){return $.inArray(''+$(this).data('value'), filterValue) + 1;}).addClass('is-active');
6590                                break;
6591                            case 'tags_ext':
6592                                if(filterValue){
6593                                    $filter.find('[js-filter-value]').removeClass('is-active').filter(function(){return $.inArray(''+$(this).data('value'), filterValue['data']) + 1;}).addClass('is-active');
6594                                }else{
6595                                    $filter.find('[js-filter-reset]').toggleClass('is-active', !filterValue);
6596                                }
6597
6598                                break;
6599                            case 'range':
6600                                var table_class = slider.dataset.class_table,
6601                                    table_range = $('.'+table_class+'');
6602
6603                                var padding_min = document.getElementById('slider-value-min'),
6604                                    padding_max = document.getElementById('slider-value-max');
6605
6606                                manager.changeRangeTable(table_range, Number(padding_min.innerHTML), Number(padding_max.innerHTML));
6607
6608
6609                                break;
6610                        }
6611                    });
6612                }
6613
6614                $controls.filter('.mod-extra').each(function(){
6615                    var $control = $(this),
6616                        $button = $control.find('.list-extra-button'),
6617                        $reset = $control.find('.list-extra-filter.mod-reset');
6618
6619                    if(settings.extra && settings.extra[$control.data('id')]){
6620                        $button.addClass('is-active').find('span').attr('data-total', settings.extra[$control.data('id')]);
6621                        $reset.show();
6622                    }else{
6623                        $button.removeClass('is-active');
6624                        $reset.hide();
6625                    }
6626
6627                });
6628
6629                $modes.removeClass('is-active').filter('[data-mode="'+settings.mode+'"]').addClass('is-active');
6630
6631
6632                if($total.length){
6633                    $total.text(settings.totalMorph || '');
6634                    if(settings.total){
6635                        $total.closest('.list-controls').show();
6636                    }else{
6637                        if(!$total.siblings('.list-controls-col').length){
6638                            $total.closest('.list-controls').hide()
6639                        }
6640                    }
6641                }
6642
6643
6644
6645
6646                manager.page = settings.page;
6647                manager.limit = settings.limit;
6648
6649                $pagination.find('.list-pagination-numbers').each(function(){
6650                    var $control = $(this);
6651
6652                    if(settings.pagination == 'numbers' && settings.lastPage > 1){
6653                        $control.show();
6654                        $control.html(
6655                            settings.pages
6656                                .map(function(page){
6657                                    return '<a href="#" class="list-pagination-number ' + (page == settings.page ? 'is-active' : '') + '" data-page="' + page + '">' + page + '</a>';
6658                                })
6659                                .join('')
6660                        );
6661
6662                    }else{
6663                        $control.hide();
6664                    }
6665                });
6666
6667                $pagination.find('.list-pagination-append').each(function(){
6668                    var $control = $(this).removeClass('is-loading');
6669
6670                    if(settings.pagination == 'append' && settings.page < settings.lastPage){
6671                        $control.show();
6672
6673                    }else{
6674                        $control.hide();
6675                    }
6676                });
6677
6678                $pagination.find('.list-pagination-limits').each(function(){
6679                    var $control = $(this),
6680                        $select = $control.find('select');
6681
6682                    if(settings.limits){
6683                        $control.show();
6684                        $select.html(
6685                            settings.limits
6686                                .map(function(limit){
6687                                    return '<option value="'+ limit +'" '+(limit == settings.limit ? 'selected' : '')+'>' + limit + '</option>';
6688                                })
6689                                .join('')
6690                        );
6691
6692                    }else{
6693                        $control.hide();
6694                    }
6695                });
6696
6697                this.trigger('afterInstall');
6698
6699            },
6700
6701            load: function(options){
6702                if(request) request.abort();
6703                $root.addClass('is-loading');
6704
6705                options = options || {};
6706
6707                if(options.page){
6708                    manager.page = options.page;
6709                }else{
6710                    manager.page = 1;
6711                }
6712
6713                if(options.limit){
6714                    manager.limit = options.limit;
6715                }
6716
6717                request = $.ajax({
6718                    url: (manager.keepDomain ? '' : $$.urlPrefix) + ((manager.url && manager.url[0] == '/') ? manager.url : document.location.pathname + manager.url),
6719                    type: 'get',
6720                    dataType: 'json',
6721                    data: manager.buildQuery(),
6722                    xhrFields: {
6723                        withCredentials: true
6724                    },
6725                    crossDomain: true,
6726                    success: function(response){
6727                        var $newItems = $(response.result),
6728                            $newPlace = $(response.place),
6729                            $table = $result.find('.list-result-table'),
6730                            $resultBody = $result,
6731                            $controlBody = $control.find('.mod-dropdown');
6732
6733                        $result.attr('class', $result.attr('class').split(' ').filter(function(className){return className.indexOf('mod-')}).join(' ') + ' mod-' + response.settings.mode);
6734
6735                        if(response.settings.table && response.settings.total){
6736                            if(!$table.length){
6737                                if(response.settings.table === true){
6738                                    $table = $('<table class="list-result-table"><tbody class="list-result-table-body"></tbody></table>');
6739                                }else{
6740                                    $table = $('<table class="list-result-table"><thead class="list-result-table-head"><tr>'+response.settings.table+'</tr></thead><tbody class="list-result-table-body"></tbody></table>');
6741                                }
6742                                $result.empty().append($table);
6743                            }
6744
6745                            $resultBody = $table.find('.list-result-table-body');
6746
6747                        }else{
6748                            if($table){
6749                                $table.remove();
6750                            }
6751                        }
6752
6753                        if(response.settings.pagination == 'append' && options.page){
6754                            $resultBody.append($newItems);
6755                        }else{
6756
6757                            $filters.each(function(){
6758                                var $filter = $(this);
6759
6760                                switch($filter.data('name')){
6761                                    case 'dropdownLeague':
6762                                        var $filter_class = '.content-' + $filter.data('name'),
6763                                            $filter_class_dc = '.dropdown_content-' + $filter.data('name'),
6764                                            $filter_content_dc = $filter.find($filter_class_dc),
6765                                            $filter_content = $newPlace.find($filter_class);
6766
6767                                        $filter_content_dc.html($filter_content);
6768
6769                                        break;
6770                                }
6771
6772                            });
6773
6774                            $resultBody.html($newItems);
6775                            if(options.page || options.limit){
6776                                $$.scrollTo($result, 300, 300);
6777                            }
6778                        }
6779
6780                        manager.install(response.settings, $newItems);
6781                    },
6782                    beforeSend: function() {
6783                        $('.analytics-table').fadeTo(100,0.3);
6784                        $('.list-result.mod-list').append($loader_sport);
6785                    },
6786                    complete: function(){
6787                        $('.analytics-table').fadeTo(100, 1);
6788                        $('.loader-sport').remove();
6789                        $root.removeClass('is-loading');
6790                    }
6791                });
6792            },
6793
6794            setOffsetData: function(){
6795                var $date_m = $('input[name^=datetimepicker]').val(),
6796                    $datetime_default = $('input[name^=datetimepicker]').data('datetime_default'),
6797                    $date_offset = $('input[name^=offset_dropdown_analytics]').val(),
6798                    $msUTC,
6799                    $offset_backoffset_back_data,
6800                    $offset_back = false,
6801                    $offset_forward_data,
6802                    $offset_forward = false,
6803                    $offset_back_data;
6804
6805                if(!$date_m){
6806                    $datetime_default = $datetime_default.split('.');
6807                    $msUTC = Date.parse($datetime_default[2] + '-' + $datetime_default[1] + '-' + $datetime_default[0]);
6808                }else{
6809                    $date_m = $date_m.split('.');
6810                    $msUTC = Date.parse($date_m[2] + '-' + $date_m[1] + '-' + $date_m[0]);
6811                }
6812
6813                $msUTC = Number($msUTC.toString().slice(0,-3));
6814                $date_offset = Number($date_offset);
6815
6816                if($('#offset_back').prop('checked')){
6817                    $offset_back_data = $msUTC - $date_offset;
6818                    $offset_back = true;
6819                }else{
6820                    $offset_back_data = $msUTC;
6821                    $offset_back = false;
6822                }
6823
6824                if($('#offset_forward').prop('checked')){
6825                    $offset_forward_data = $msUTC + $date_offset + 86400;
6826                    $offset_forward = true;
6827                }else{
6828                    $offset_forward_data = $msUTC + 86400;
6829                    $offset_forward = false;
6830                }
6831
6832                if(!$offset_back && !$offset_forward){
6833                    $offset_back_data = $msUTC;
6834                    $offset_forward_data = $msUTC + $date_offset;
6835                }
6836
6837                $('input[name^=offset_back]').val($offset_back_data);
6838                $('input[name^=offset_forward]').val($offset_forward_data - 60);
6839
6840            },
6841
6842            changeRangeTable: function(table, data_min, data_max){
6843                table.each(function () {
6844                    $(this).find('th').each(function(){
6845                        var cell = $(this);
6846                        if(cell.hasClass('analytics-table-col__aspects')){
6847                            var asp_span = cell.find('span');
6848                            if(Math.abs(data_min) !== 3 || Math.abs(data_max)!== 3 ) {
6849                                asp_span.each(function(){
6850                                    var prec = $(this).data('prec');
6851                                    if (prec >= data_min && prec <= data_max) {
6852                                        $(this).addClass('analytics-aspects__mark');
6853                                    } else {
6854                                        $(this).removeClass('analytics-aspects__mark');
6855                                    }
6856                                });
6857                            }else{
6858                                asp_span.each(function(){
6859                                    $(this).removeClass('analytics-aspects__mark');
6860                                });
6861                            }
6862                        }
6863                    });
6864                })
6865            },
6866
6867            buildQuery: function(){
6868                var query = {filters: {}};
6869                $.extend(query, manager.parameters);
6870
6871                $filters.each(function(){
6872                    var $filter = $(this),
6873                        $value,
6874                        filterName = $filter.data('name'),
6875                        filterValue;
6876
6877                    switch($filter.data('type')){
6878                        case 'list':
6879                            var $element = $filter.find('select[name=list]').val();
6880                            filterValue = $element;
6881                            break;
6882                        case 'list_analytics':
6883                            // $element = [];
6884                            // $filter.find('[js-filter-value].is-active').each(function(){
6885                            //     $element.push($(this).data('value'));
6886                            // });
6887                            // filterValue = {"data" : $element, "filter_name" : $filter.data('name')};
6888
6889                            var $element = $filter.find('input[name^=dropdown_analytics]').val(),
6890                                $element_text =  $filter.find('input[name^=dropdown_analytics]').data('name');
6891                            if($element_text == ''){
6892                                $element_text = 'none';
6893                            }
6894                            filterValue = {"data" : $element, "name" : $element_text, "filter_name" : $filter.data('name')};
6895
6896                            break;
6897                        case 'one_date':
6898                            var $data_default = $filter.find('input[name=datetimepicker]').data('datetime_default'),
6899                                $data_val = $filter.find('input[name=datetimepicker]').val(),
6900                                $offset_back = $filter.find('input[name=offset_back]').val(),
6901                                $offset_forward = $filter.find('input[name=offset_forward]').val();
6902
6903                            filterValue = {"offset_back" : $offset_back ,
6904                                "offset_forward" : $offset_forward,
6905                                "datetime_default" : $data_val ? $data_val : $data_default,
6906                                "filter_name" : $filter.data('name')
6907                            };
6908
6909                            $.ajax({
6910                                url: '/api/astroChart/?league_request',
6911                                data: {filterValue: filterValue},
6912                                type: 'post',
6913                                dataType: 'json',
6914                                success: function(data){
6915                                }
6916                            });
6917                            break;
6918                        case 'date_offset':
6919                            var $element = $filter.find('input[name^=offset_dropdown_analytics]').val(),
6920                                $element_text =  $filter.find('input[name^=offset_dropdown_analytics]').data('name'),
6921                                $offset_back_chec = $filter.find('#offset_back').prop('checked'),
6922                                $offset_forward_chec = $filter.find('#offset_forward').prop('checked'),
6923                                $checked_an = 0;
6924
6925                            if($offset_back_chec && !$offset_forward_chec) {
6926                                $checked_an = 1;
6927                            }else if(!$offset_back_chec && $offset_forward_chec){
6928                                $checked_an = 2;
6929                            }else if($offset_back_chec && $offset_forward_chec){
6930                                $checked_an = 4;
6931                            }
6932
6933                            filterValue = {"data" : $element, "name" : $element_text, "filter_name" : $filter.data('name'), "input_offset" : $checked_an};
6934
6935                            break;
6936                        case 'searchAuthor':
6937                            filterValue = $filter.find('[js-filter-value].is-active').data('value');
6938                            break;
6939                        case 'search':
6940                            filterValue = $filter.find('input').val();
6941                            break;
6942                        case 'radio':
6943                            filterValue = $filter.find('[js-filter-value].is-active').data('value');
6944                            break;
6945                        case 'sort':
6946                            $value = $filter.find('[js-filter-value].is-active');
6947                            filterValue = $value.data('value') + '|' + $value.attr('data-order');
6948                            break;
6949                        case 'tags':
6950
6951                            filterValue = [];
6952                            $filter.find('[js-filter-value].is-active').each(function(){
6953                                filterValue.push($(this).data('value'));
6954                            });
6955
6956                            break;
6957                        case 'tags_ext':
6958
6959                            var filter_data = [];
6960                            $filter.find('[js-filter-value].is-active').each(function(){
6961                                filter_data.push($(this).data('value'));
6962                            });
6963                            $filter.find('[js-filter-reset].is-active').each(function(){
6964                                filter_data.push($(this).data('value'));
6965                            });
6966
6967                            filterValue = {"data" : filter_data, "filter_name" : $filter.data('name')};
6968
6969                            // if($filter.data('name').indexOf('aspects_') !== -1){
6970                            //     filterValue = {"data" : filter_data, "filter_name" : $filter.data('name')};
6971                            // }else{
6972                            //     filterValue = filter_data;
6973                            // }
6974
6975                            break;
6976                    }
6977
6978                    query.filters[filterName] = filterValue;
6979
6980                });
6981
6982                $modes.filter('.is-active').each(function(){
6983                    query.mode = $(this).data('mode');
6984                });
6985
6986                if(manager.page){
6987                    query.page = manager.page;
6988                }
6989
6990                if(manager.limit){
6991                    query.limit = manager.limit;
6992                }
6993
6994                query.listManager = manager.id;
6995
6996                return query;
6997            }
6998
6999        });
7000        manager.initialize();
7001
7002    };
7003
7004
7005    $(function(){
7006        $$.init.listManager = function(context){
7007            $('.list:not(.is-initialized)[data-settings]', context).each(function(){
7008                new Manager(this);
7009            });
7010        };
7011
7012        $$.init.listManager();
7013    });
7014
7015})();
7016
7017// (function (filterRange) {
7018//
7019//     filterRange.RangeList = function ($input) {
7020//         var $name = $input['name'],
7021//             range_value = $('.range-value__'+$name+'');
7022//             console.log($(this));
7023//             console.log($input['value']);
7024//
7025//
7026//         range_value.each(function(){
7027//             $(this).html($input['value']);
7028//         });
7029//     };
7030//
7031// }(window.filterRange = window.filterRange || {}));
7032
7033
7034(function(){
7035
7036    var routes = [
7037            {
7038                controller: 'IndexController',
7039                templateUrl: '?index',
7040                title: 'Диалоги',
7041                url: '/'
7042            },
7043            {
7044                controller: 'DialogController',
7045                templateUrl: '?dialog',
7046                title: 'Просмотр диалогов',
7047                url: '/dialog',
7048                resolve: {
7049                    dialog: function($http, $route, $rootScope){
7050                        var dialog_id = $route.current.params.dialog_id,
7051                            dialog;
7052
7053                        if(dialog_id){
7054                            if(dialog = mail.getDialog(dialog_id)){
7055                                return dialog;
7056                            }
7057
7058                            return $http({
7059                                method: 'GET',
7060                                url: '?dialog=' + dialog_id
7061                            }).then(function(response) {
7062                                return response.data;
7063
7064                            }, function(response) {
7065                                return {error: 'network'};
7066                            });
7067                        }
7068                    }
7069                },
7070                params: '/:dialog_id?'
7071            }
7072        ],
7073        browserTabs = duel.channel('mailChannel'),
7074        userId,
7075        $mail,
7076        listManager,
7077        mail = {};
7078
7079
7080    angular.module('mail', ['ngRoute', 'socket'])
7081
7082        .filter("sanitize", ['$sce', function($sce) {
7083            return function(htmlCode){
7084                return $sce.trustAsHtml(htmlCode);
7085            }
7086        }])
7087
7088        .run(function ($socket, $rootElement, $rootScope, $location, $timeout, $http, $q) {
7089            $mail = $($rootElement);
7090
7091            $mail.show();
7092
7093            $rootScope.dialogs = [];
7094            $rootScope.routes = routes;
7095            $rootScope.activeDialog = null;
7096            $rootScope.userId = userId = $('body').data('user-id');
7097
7098
7099            var readDialogRequest,
7100                readDialogAbort;
7101
7102            $.extend(mail, {
7103                readDialog: function(dialog){
7104                    (readDialogRequest && readDialogAbort.resolve());
7105                    (readDialogRequest = $http({
7106                        method: 'POST',
7107                        url: '?dialog=' + dialog.id + '&read',
7108                        timeout: (readDialogAbort = $q.defer()).promise
7109                    })).then(function(response) {
7110                        if(response.data.read_at){
7111                            dialog.members[userId].read_at = response.data.read_at;
7112                        }
7113                    });
7114
7115                },
7116
7117                getDialog: function(dialog_id){
7118                    var dialog = $rootScope.dialogs.filter(function(dialog){
7119                        return dialog.id == dialog_id;
7120                    });
7121
7122                    return dialog.length ? dialog[0] : null;
7123                },
7124
7125                openDialog: function(dialog){
7126                    $rootScope.dialogs.push(dialog);
7127                    socket.join('dialog:' + dialog.id);
7128                },
7129
7130                closeDialog: function(dialog_id){
7131                    $rootScope.dialogs = $rootScope.dialogs.filter(function(dialog){
7132                        return dialog.id != dialog_id;
7133                    });
7134                    socket.leave('dialog:' + dialog_id);
7135                    $location.path('/dialog');
7136                },
7137
7138                scrollToBottom: function(delay){
7139                    var $messagesContainer = $('.mail-messages', $rootElement);
7140
7141                    $timeout(function(){
7142                        $messagesContainer.stop().scrollTop($messagesContainer.get(0).scrollHeight);
7143                    }, delay || 10);
7144                },
7145
7146                isBottomScroll: function(){
7147                    var $messagesContainer = $('.mail-messages', $rootElement);
7148                    return $messagesContainer.get(0).scrollHeight - $messagesContainer.height() * 1.5 <= $messagesContainer.scrollTop();
7149                },
7150
7151                resizeWindow: function(){
7152                    $timeout(function(){
7153                        $('.mail-messages', $rootElement).height($.windowHeight() - 280 - $('.mail-header', $rootElement).outerHeight());
7154                    });
7155                }
7156
7157            });
7158
7159            $rootScope.shareData = function(dialog){
7160                $$.openModal({
7161                    url: $$.urlPrefix + '/api/shareData/',
7162                    data: {to: dialog.partner},
7163                    afterOpen: function(modal, $modal, modalResponse){
7164                        var chooseEvents = modalResponse.events.map(function(item){
7165                            return 'events[' + item + ']';
7166                        });
7167                        $modal.on('change', 'input[name^=events]', function(){
7168                            var $input = $(this);
7169                            if($input.prop('checked')){
7170                                chooseEvents.push($input.prop('name'));
7171                            }else{
7172                                chooseEvents = chooseEvents.filter(function(item){
7173                                    return item != $input.prop('name');
7174                                });
7175                            }
7176
7177                        });
7178
7179                        function checkRefresh(){
7180                            $modal.find('input[name^=events]').each(function(){
7181                                $(this).prop('checked', chooseEvents.indexOf($(this).prop('name')) >=0);
7182                            });
7183                        }
7184
7185                        $modal.find('.list').on('afterInstall', function(){
7186                            checkRefresh();
7187                        });
7188
7189                        checkRefresh();
7190
7191                        $modal.find('form').formHandle({
7192                            success: function(response){
7193                                $modal.arcticmodal('close');
7194                                $$.alert('Изменения сохранены');
7195                            }
7196                        });
7197                    }
7198                });
7199            };
7200
7201            var serviceRefresh = function(dialog, response){
7202                dialog.service = response.service;
7203                dialog.messages.push(response.message);
7204                if(mail.isBottomScroll()){
7205                    mail.scrollToBottom();
7206                }
7207            };
7208
7209            $rootScope.serviceAction = function(dialog, action){
7210                $http({
7211                    method: 'POST',
7212                    url: '?dialog=' + dialog.id + '&' + action
7213                }).then(function(response) {
7214                    if(response.data.error){
7215                        $$.alert(response.data.error['#']);
7216                    }else if(response.data.success){
7217                        serviceRefresh(dialog, response.data);
7218                        if('serviceWorkComplete' == action){
7219                            $rootScope.serviceReview(dialog);
7220                        }
7221                    }
7222                });
7223            };
7224
7225            $rootScope.serviceBill = function(dialog){
7226                $$.openModal({
7227                    url: '?dialog=' + dialog.id + '&serviceBillForm',
7228                    afterOpen: function(modal, $modal, modalResponse){
7229                        $modal.find('form').formHandle({
7230                            success: function(response){
7231                                $modal.arcticmodal('close');
7232                                $timeout(function(){
7233                                    serviceRefresh(dialog, response);
7234                                });
7235                            }
7236                        });
7237                    }
7238                });
7239            };
7240
7241            $rootScope.serviceBillPay = function(dialog){
7242                $$.payment(dialog.service.holder_id);
7243            };
7244
7245            $rootScope.serviceReview = function(dialog){
7246                $$.openModal({
7247                    url: '?dialog=' + dialog.id + '&serviceReviewForm',
7248                    afterOpen: function(modal, $modal, modalResponse){
7249                        $modal.find('form').formHandle({
7250                            success: function(response){
7251                                $modal.arcticmodal('close');
7252                                $timeout(function(){
7253                                    serviceRefresh(dialog, response);
7254                                });
7255                            }
7256                        });
7257                    }
7258                });
7259            };
7260
7261            $rootScope.attachFile = function(dialog){
7262
7263                var $input = $("<input type=\"file\">"),
7264                    total = 0,
7265                    loaded = 0,
7266                    startTimer;
7267
7268                $input.damnUploader({
7269                    url: "?dialog="+dialog.id+"&upload",
7270                    fieldName:  "file",
7271                    multiple: true,
7272                    dataType: 'json'
7273                })
7274                    .on('du.add', function(e) {
7275                        var ui = e.uploadItem,
7276                            message = {
7277                                user_id: userId,
7278                                file: {
7279                                    name: ui.file.name,
7280                                    progress: 0
7281                                }
7282                            },
7283                            invalid = false;
7284
7285                        /*
7286                        if(!ui.file.type.match(/^(image.*|video.*)$/g)){
7287                            message.file.error = 'Формат ' + ui.file.type + ' не поддерживается';
7288                            invalid = true;
7289                        }
7290                        */
7291
7292                        if(ui.file.size > 10485760){
7293                            message.file.error = 'Максимальный размер файла 10Мб';
7294                            invalid = true;
7295                        }
7296
7297                        $timeout(function(){
7298                            $rootScope.activeDialog.messages.push(message);
7299                            if(mail.isBottomScroll()){
7300                                mail.scrollToBottom();
7301                            }
7302                        });
7303
7304                        if(invalid){
7305                            return;
7306                        }
7307
7308                        ui.completeCallback = function(success, response) {
7309                            $timeout(function(){
7310                                if(response.success){
7311                                    $.extend(message, response.message);
7312                                }else{
7313                                    message.file.error = response.error['#'] || 'Ошибка загрузки';
7314                                }
7315
7316                                $timeout(function(){
7317                                    if(mail.isBottomScroll()){
7318                                        mail.scrollToBottom();
7319                                    }
7320                                });
7321
7322                                browserTabs.broadcast('dialog_message', dialog.id, message);
7323                            });
7324
7325
7326
7327                        };
7328
7329                        ui.progressCallback = function(progress) {
7330                            message.file.progress = progress;
7331
7332                            $timeout(function(){
7333                                if(mail.isBottomScroll()){
7334                                    mail.scrollToBottom();
7335                                }
7336                            });
7337                        };
7338
7339                        clearTimeout(startTimer);
7340                        startTimer = setTimeout(function(){
7341                            $input.duStart();
7342                        }, 100);
7343
7344                    })
7345                    .on('du.completed', function(e) {
7346                        $input.remove();
7347                    })
7348                    .click();
7349
7350
7351            };
7352
7353            $rootScope.closeDialog = mail.closeDialog;
7354
7355            $rootScope.$on('$routeChangeSuccess', function(event, next, current){
7356                $rootScope.$route = next.$$route;
7357                $rootScope.activeDialog = null;
7358                $$.window.off('.mail');
7359            });
7360
7361            $rootScope.$watch('dialogs', function(dialogs){
7362                var unread;
7363                dialogs.forEach(function(dialog){
7364                    unread = 0;
7365                    dialog.messages.forEach(function(message){
7366                        if(message.user_id != userId && message.created_at && message.created_at > dialog.members[userId].read_at){
7367                            unread++;
7368                        }
7369                    });
7370                    dialog.unread = unread;
7371                });
7372            }, true);
7373
7374            browserTabs.on('dialog_message', function(dialog_id, message){
7375                var dialog = mail.getDialog(dialog_id);
7376                if(dialog && message.user_id == userId){
7377                    dialog.messages.push(message);
7378                    if(mail.isBottomScroll()){
7379                        mail.scrollToBottom();
7380                    }
7381                }
7382            });
7383
7384            $socket.on('dialog_message', function(response){
7385                var dialog = mail.getDialog(response.dialog_id);
7386
7387                if(dialog && response.message.user_id != userId){
7388                    dialog.messages.push(response.message);
7389
7390                    if($rootScope.activeDialog === dialog){
7391                        if(mail.isBottomScroll()){
7392                            mail.scrollToBottom();
7393                        }
7394
7395                        if(window.isMaster()){
7396                            dialog.members[userId].read_at = response.message.created_at;
7397                            dialog.members[userId].content = response.message.content;
7398                            mail.readDialog(dialog);
7399                        }
7400
7401                    }
7402                }
7403            });
7404
7405            $socket.on('dialog_read', function(response){
7406                var dialog = mail.getDialog(response.dialog_id);
7407                if(dialog && response.read_at){
7408                    dialog.members[response.user_id].read_at = response.read_at;
7409                }
7410            });
7411
7412            $socket.on('dialog_service', function(response){
7413                var dialog = mail.getDialog(response.dialog_id);
7414                if(dialog && response.service){
7415                    dialog.service = response.service;
7416                }
7417            });
7418        })
7419
7420        .config(function($routeProvider){
7421
7422            routes.forEach(function(route){
7423                $routeProvider.when(route.url + (route.params || ''), route);
7424            });
7425
7426            $routeProvider.otherwise({redirectTo: routes[0].url});
7427        })
7428
7429        .controller('IndexController', function($rootElement){
7430            $(function(){
7431                $$.init.listManager($rootElement);
7432                listManager = $mail.find('.list').data('listManager');
7433            });
7434
7435            if(listManager){
7436                listManager.load();
7437            }
7438        })
7439
7440        .controller('DialogController', function(dialog, $rootElement, $rootScope, $scope, $routeParams, $socket, $http, $location, $timeout){
7441            if($routeParams.dialog_id){
7442                if(!dialog || dialog.error){
7443                    return mail.closeDialog($routeParams.dialog_id);
7444
7445                }else{
7446
7447                    if(!mail.getDialog(dialog.id)){
7448                        mail.openDialog(dialog);
7449                    }
7450                }
7451
7452            }else if($rootScope.dialogs.length){
7453                return $location.path('/dialog/' + $rootScope.dialogs[0].id);
7454
7455            }else{
7456                return $location.path('/');
7457            }
7458
7459            $rootScope.activeDialog = dialog;
7460
7461            if(dialog.messages){
7462                mail.readDialog(dialog);
7463            }
7464
7465            $$.scrollTo($mail, 300, 100);
7466            $mail.find('.mail-input textarea').focus();
7467
7468
7469            window.smilesController = {scope: $scope, timeout: $timeout};
7470            window.emojiController = {scope: $scope, timeout: $timeout};
7471
7472            $scope.attachSmile = function($scope){
7473                openSmiles($('.smiles-attach'));
7474            };
7475
7476            $scope.attachEmoji = function($scope){
7477                openEmoji($('.emoji-attach'));
7478            };
7479
7480            $scope.messageSend = function(){
7481                if(!$scope.text){
7482                    return;
7483                }
7484
7485                var message = {
7486                        user_id: userId,
7487                        content: $$.escapeHtml($scope.text)
7488                    };
7489
7490                dialog.messages.push(message);
7491
7492                if(mail.isBottomScroll()){
7493                    mail.scrollToBottom();
7494                }
7495
7496                $http({
7497                    method: 'POST',
7498                    url: '?dialog=' + dialog.id + '&messageSend',
7499                    data: {message: $scope.text}
7500                }).then(function(response) {
7501                    $.extend(message, response.data.message);
7502
7503                    $timeout(function(){
7504                        if(mail.isBottomScroll()){
7505                            mail.scrollToBottom();
7506                        }
7507                    });
7508
7509                    browserTabs.broadcast('dialog_message', dialog.id, message);
7510                });
7511
7512                $scope.text = '';
7513
7514            };
7515
7516
7517            $$.window.on('resize.mail', function(e){
7518                mail.resizeWindow();
7519                mail.scrollToBottom();
7520            });
7521
7522            mail.resizeWindow();
7523            mail.scrollToBottom(50);
7524
7525            $mail.find('.mail-input').off('.mail').on('keydown.mail', function(e){
7526                if(e.keyCode == 13){
7527                    $scope.messageSend();
7528                }
7529            });
7530        })
7531
7532        .controller('TabsController', function($rootScope){
7533
7534        })
7535    ;
7536
7537})();
7538
7539$(function(){
7540    $$.document.on('click', '[js-mail]', function(e){
7541        e.preventDefault();
7542        var $button = $(this);
7543        if($button.data('lock')) return;
7544
7545        if(!$$.isAuthenticated){
7546            return $$.openAuth();
7547        }
7548
7549        $button.data('lock', true);
7550
7551        $.ajax({
7552            url: $$.urlPrefix + '/api/mail/',
7553            type: 'post',
7554            data: {id: $button.attr('js-mail')},
7555            dataType: 'json',
7556            xhrFields: {
7557                withCredentials: true
7558            },
7559            crossDomain: true,
7560
7561            success: function(response){
7562                if(response.redirect){
7563                    document.location.href = response.redirect;
7564                }
7565            }
7566        });
7567    });
7568});
7569
7570$(function(){
7571    var $body = $('body');
7572
7573    $body.on('click', '[js-parsing_ephemeris]', function(e){
7574        e.preventDefault();
7575
7576        var $inputId = $('input[type=text][name^=match_id]');
7577        var date_start = $('#datetimepicker6').data('DateTimePicker').date();
7578        var date_end = $('#datetimepicker7').data('DateTimePicker').date();
7579
7580        if(date_start && date_end){
7581            parsung_date(date_start, date_end);
7582        }else if($inputId.val()){
7583            parsung_id($inputId);
7584        }
7585    });
7586
7587    $body.on('click', '[js-request_pres_horar]', function(e){
7588        e.preventDefault();
7589        var $message = $('.office-data-saved-horar');
7590        $message.text('GOOOOO!');
7591        $message.animate({opacity: 1}, 300);
7592
7593        var date_start = 0;
7594
7595        $.ajax({url: '/parsing/?request_pres_horar_start', type: 'POST', dataType: 'json', async: false,
7596            success: function(data){
7597                date_start = parseInt( data['dd_start'], 10 );
7598            }
7599        });
7600
7601        console.log(1231232);
7602
7603        var date_end = moment().endOf('day').unix();
7604
7605        var d = new Date()
7606        var n = d.getTimezoneOffset();
7607        var offset = Math.abs((n/60)*3600),
7608            dd_start = offset >= 0 ? date_start + offset : date_start - offset,
7609            dd_end = offset >= 0 ? date_end + offset : date_end - offset,
7610            ddd = Math.ceil((dd_end - dd_start)/7200);
7611
7612        var data1, data2, j = 1, x;
7613        while (dd_start < dd_end) {
7614            data1 = dd_start;
7615            dd_start = dd_start + 60 * 60 * 2;
7616            data2 = data1 + 3600 * 2;
7617
7618            $.ajax({url: '/parsing/?request_pres_horar', type: 'POST', dataType: 'json',
7619                data: {date_start: data1, date_end: data2},
7620                complete: function(){
7621                    x = Math.ceil(j*100/ddd);
7622                    $message.text(x + '%');
7623                    $message.animate({opacity: 1}, 300);
7624                    j++;
7625                },
7626                error: function(request, type, message){
7627                    $message.text('КОСЯК! Обратись к МЕГА-программисту!!!');
7628                    $message.animate({opacity: 1}, 300);
7629                }
7630            });
7631
7632        }
7633
7634    });
7635
7636    function parsung_id($inputId){
7637        var $message = $('.office-data-saved');
7638        $.ajax({url: '/parsing/?establish_ephemeris_match', type: 'post', dataType: 'json',
7639            data: {match_id: $inputId.val(), date_start: null, date_end: null},
7640            complete: function(){
7641                $message.text('МАТЧ 100% аспектами заполнен!');
7642                $message.animate({opacity: 1}, 300);
7643            },
7644            error: function(request, type, message){
7645                $message.text('КОСЯК! Обратись к МЕГА-программисту!!!');
7646            }
7647        });
7648    }
7649
7650    function parsung_date(date_start, date_end){
7651        var $message = $('.office-data-saved');
7652        date_start = date_start.startOf('day').unix();
7653        date_end = date_end.endOf('day').unix();
7654
7655        var d = new Date()
7656        var n = d.getTimezoneOffset();
7657        var offset = Math.abs((n/60)*3600),
7658            dd_start = offset >= 0 ? date_start + offset : date_start - offset,
7659            dd_end = offset >= 0 ? date_end + offset : date_end - offset,
7660            ddd = Math.ceil((dd_end - dd_start)/7200);
7661
7662        var data1, data2, j = 1, x;
7663        while (dd_start < dd_end) {
7664            data1 = dd_start;
7665            dd_start = dd_start + 60*60*2;
7666            data2 = data1 + 3600 * 2;
7667
7668            $.ajax({url: '/parsing/?establish_ephemeris_match', type: 'post', dataType: 'json',
7669                    data: {match_id: null, date_start: data1, date_end: data2},
7670                complete: function(){
7671                    x = Math.ceil(j*100/ddd);
7672                    $message.text(x + '%');
7673                    $message.animate({opacity: 1}, 300);
7674                    j++;
7675                },
7676                error: function(request, type, message){
7677                    $message.text('КОСЯК! Обратись к МЕГА-программисту!!!');
7678                }
7679            });
7680
7681        }
7682    }
7683
7684});
7685
7686$(function () {
7687    if($('#datetimepicker6').length){
7688        $('#datetimepicker6').datetimepicker({
7689            // defaultDate: new Date,
7690            useCurrent: false, //Important! See issue #1075,
7691            format: 'DD.MM.YYYY',
7692            locale: 'ru',
7693        });
7694        $('#datetimepicker7').datetimepicker({
7695            // defaultDate: new Date,
7696            useCurrent: false, //Important! See issue #1075,
7697            format: 'DD.MM.YYYY',
7698            locale: 'ru',
7699        });
7700        $("#datetimepicker6").on("dp.change", function (e) {
7701            $('#datetimepicker7').data("DateTimePicker").minDate(e.date);
7702        });
7703        $("#datetimepicker7").on("dp.change", function (e) {
7704            $('#datetimepicker6').data("DateTimePicker").maxDate(e.date);
7705        });
7706    }
7707
7708});
7709
7710
7711(function(){
7712
7713    function openPayment(holderId, options){
7714        if(!$$.isAuthenticated){
7715            $$.openAuth();
7716            return;
7717        }
7718
7719        options = options || {};
7720
7721        $$.openModal({
7722            url: $$.urlPrefix + '/payment/',
7723            data: {id: holderId},
7724            afterOpen: function(modal, $modal, modalResponse){
7725                var $types = $modal.find('.payment-types'),
7726                    $orderForm = $modal.find('.payment-order-form'),
7727                    $orderOptions = $modal.find('.payment-order-options'),
7728                    $paymentForm = $modal.find('.payment-form'),
7729                    $message = $modal.find('.payment-order-message'),
7730                    $bonus = $modal.find('.payment-order-bonus'),
7731                    $bonusText = $bonus.find('.payment-order-bonus-text'),
7732                    $bonusInput = $bonus.find('input'),
7733                    $prices = $modal.find('.choose-box-item'),
7734                    $submit = $modal.find('.payment-order-submit'),
7735                    $submitText = $submit.find('button'),
7736                    $priceInput = $modal.find('.payment-order-price-input');
7737
7738                var storage = {
7739                    bonus: modalResponse.bonus,
7740                    balance: modalResponse.balance,
7741                    prices: modalResponse.prices,
7742                    price: null,
7743                    priceInput: false
7744                };
7745
7746                if(storage.prices.value){
7747                    storage.price = storage.prices;
7748
7749                    if(storage.price.value == 'input'){
7750                        storage.price.value = options.price || 0;
7751                        storage.priceInput = true;
7752                    }
7753
7754                }else{
7755
7756                    $.each(storage.prices, function(i, price){
7757                        if(!storage.price){
7758                            storage.price = price;
7759                            $prices.filter('[data-id="'+i+'"]').addClass('is-active');
7760                        }
7761
7762                        if(options.price){
7763                            if(price.value == options.price){
7764                                storage.price = price;
7765                                $prices.filter('[data-id="'+i+'"]').addClass('is-active').siblings($prices).removeClass('is-active');
7766                            }
7767
7768                        }else{
7769                            return false;
7770                        }
7771
7772                    });
7773
7774                    $prices.on('click', function(e){
7775                        e.preventDefault();
7776
7777                        var $price = $(this);
7778
7779                        if($price.hasClass('is-active') && !storage.prices[$price.data('id')]){
7780                            return;
7781                        }
7782
7783                        storage.price = storage.prices[$price.data('id')];
7784
7785                        $price.addClass('is-active').siblings($prices).removeClass('is-active');
7786                        calc();
7787                    });
7788                }
7789
7790                if(options.bonusApply){
7791                    $bonusInput.prop('checked', true);
7792                }
7793
7794                if(storage.priceInput){
7795                    $priceInput.on('keyup', function(){
7796                        storage.price.value = +$priceInput.val() || 0;
7797                        calc();
7798                    });
7799                }
7800
7801                $bonusInput.on('change', function(){
7802                    calc();
7803                });
7804
7805                function calc(){
7806                    var bonusAvailable,
7807                        bonusApply = $bonusInput.prop('checked'),
7808                        price = storage.price.value,
7809                        balance;
7810
7811                    if(storage.priceInput){
7812                        if(price){
7813                            $orderOptions.show();
7814                        }else{
7815                            $orderOptions.hide();
7816                        }
7817                    }
7818
7819                    if(storage.price.bonusRate > 0 && storage.bonus > 0){
7820                        bonusAvailable = Math.ceil(storage.price.value * storage.price.bonusRate);
7821
7822                        if(bonusAvailable > storage.price.value){
7823                            bonusAvailable = storage.price.value;
7824                        }
7825
7826                        if(bonusAvailable > storage.bonus){
7827                            bonusAvailable = storage.bonus;
7828                        }
7829
7830                        if(bonusApply){
7831                            price -= bonusAvailable;
7832                        }
7833
7834                        $bonus.show();
7835                        $bonusText.html('Применить бонусы <span class="payment-order-bonus-value">'+bonusAvailable+'</span>&nbsp;<span class="ab">✪</span>&nbsp;&nbsp;(всего у вас '+storage.bonus+'&nbsp;<span class="ab">✪</span>)');
7836
7837                    }else{
7838                        $bonus.hide();
7839                        $bonusInput.prop('checked', false);
7840                    }
7841
7842                    balance = storage.balance - price;
7843
7844
7845                    if(storage.priceInput){
7846                        $types.show();
7847                        $message.hide();
7848                        $submitText.html('Пополнить баланс на <b>'+storage.price.value+'&nbsp;<rur>Р</rur></b>');
7849
7850                    }else if(bonusApply && bonusAvailable == storage.price.value){
7851                        $types.hide();
7852                        $message.html('Покупка будет осуществлена за счет бонусов.');
7853                        $submitText.html('Купить за бонусы');
7854
7855                    }else if(balance >= 0){
7856                        $types.hide();
7857                        // $message.html('На вашем балансе <b>'+storage.balance+'&nbsp;<rur>Р</rur></b>.<br>Требуемая сумма спишется с вашего баланса.');
7858                        $submitText.html('Купить за <b>'+(price)+'&nbsp;<rur>Р</rur></b>');
7859
7860                    }else{
7861                        $types.slideDown(300);
7862                        // $message.html('На вашем балансе <b>'+storage.balance+'&nbsp;<rur>Р</rur></b>.<br><b>Для покупки'+(bonusApply ? ', с учетом бонусов,' : '')+' требуется пополнить баланс.</b>');
7863                        // $submitText.html('Пополнить баланс на <b>'+Math.abs(balance)+'&nbsp;<rur>Р</rur></b> и купить');
7864                        $submitText.html('Купить за <b>'+(price)+'&nbsp;<rur>Р</rur></b>');
7865                    }
7866
7867                }
7868
7869                calc();
7870
7871                $orderForm.on('submit', function(e){
7872                    e.preventDefault();
7873                    $$.uniFormSubmit($(this), {
7874                        overlay: $modal,
7875                        data: {id: holderId, price: storage.price.value, bonus: $bonusInput.prop('checked') ? 1 : 0},
7876                        success: function(response){
7877                            if(response.paymentForm){
7878                                $paymentForm.html(response.paymentForm).find('form').submit();
7879                                $modal.arcticmodal('close');
7880                            }else if(response.type == 'consultation'){
7881                                $('[js-consultation-choose][data-type="free"]').eq(0).click();
7882                            }else if(response.redirect){
7883                                $modal.arcticmodal('close');
7884                                document.location.href = response.redirect;
7885                            }
7886                        }
7887                    })
7888                });
7889
7890            }
7891        });
7892
7893
7894    }
7895
7896    $(function(){
7897
7898        $$.payment = openPayment;
7899
7900        $$.init.payment = function(context){
7901            $('[js-payment]', context).on('click', function(e){
7902                e.preventDefault();
7903                openPayment($(this).attr('js-payment'));
7904            });
7905
7906        };
7907
7908        $$.init.payment();
7909
7910    });
7911
7912})();
7913$(function(){
7914	$('[js-open-modal-prediction-feed]').on('click', function(e){
7915		e.preventDefault();
7916		$$.openModal($('.modal-prediction-feed'));
7917	});
7918
7919	$('[js-prediction-vote]').on('submit', function(e){
7920		e.preventDefault();
7921
7922		if($$.isAuthenticated){
7923			var $form = $(this);
7924			$$.uniFormSubmit($form, {
7925				afterSuccess: function(data, $form){
7926					var $input = $form.find('input[value="'+data.variant_id+'"]').attr('disabled', 'disabled'),
7927						$textarea = $form.find('textarea[name="content"]')
7928					;
7929
7930					$input.closest('.prediction-guess-answer').addClass('mod-checked');
7931					$form.closest('.prediction-guess').addClass('mod-voted').attr('data-prediction-id', data.prediction_id).data('count-changes', data.count_changes);
7932					$textarea.attr('disabled', 'disabled');
7933
7934					$form.find('.prediction-guess-form-action.mod-vote').text('Изменить');
7935					$form.find('.prediction-guess-form-change-notice').html(data.notice);
7936
7937					if(!data.content){
7938						$form.find('.prediction-guess-form-cols.mod-content').hide();
7939					}
7940
7941					if(data.diff == 0) $form.find('.prediction-guess-form-action.mod-vote').remove();
7942				}
7943			});
7944		}else{
7945			$$.openAuth();
7946		}
7947	});
7948
7949	$('[js-prediction-cancel]').on('click', function(e){
7950		e.preventDefault();
7951		var $elem = $(this);
7952		$$.confirm('Отменить прогноз?', function(){
7953			$.ajax({ url: '?cancel', type: 'post', dataType: 'json',
7954				beforeSend: function(){
7955					$elem.closest('.prediction-guess').removeClass('mod-voted');
7956					$elem.closest('form').find('textarea[disabled], input[disabled]').removeAttr('disabled').end().find('.prediction-guess-form-cols.mod-content').show();
7957					$elem.closest('form').find('textarea').val('');
7958					$elem.closest('form').find('.prediction-guess-answer').removeClass('mod-checked');
7959					$elem.closest('form').find('.prediction-guess-answer input[type=radio]').prop('checked', false);
7960					$elem.closest('form').find('.prediction-guess-form-article').hide();
7961				}
7962			});
7963		});
7964	});
7965
7966	$('[js-prediction-variants]').on('click', function(e){
7967		e.preventDefault();
7968		var $elem = $(this);
7969		if($elem.closest('.prediction-guess').data('count-changes') == 3){
7970			$$.alert('Вы исчерпали попытки для изменения');
7971			return false;
7972		}
7973
7974		$elem.closest('.prediction-guess').removeClass('mod-voted');
7975		$elem.closest('form').find('textarea[disabled], input[disabled]').removeAttr('disabled').end().find('.prediction-guess-form-cols.mod-content').show();
7976		$elem.closest('form').find('.prediction-guess-answer.mod-checked').removeClass('mod-checked');
7977	});
7978
7979	$('[js-prediction-article]').on('click', function(e){
7980		var $elem = $(this),
7981			$container = $elem.closest('.prediction-guess')
7982		;
7983
7984		$$.openModal({
7985			url: $$.urlPrefix + '/office/library/?get',
7986			data: {id: $container.data('article-id'), prediction_id: $container.data('prediction-id')},
7987			beforeOpen: function(e, $modal){
7988
7989			},
7990			afterOpen: function(modal, $modal){
7991				$modal.closest('.modal-box').addClass('mod-article-editor');
7992
7993				$modal.find('select[name=type_id]').on('change', function(){
7994					if($(this).val() == 3){ //ID типа КУРС
7995						$modal.find('.office-library-lessons-list').show();
7996					}else{
7997						$modal.find('.office-library-lessons-list').hide();
7998					}
7999				}).trigger('change');
8000
8001				//Сохранить article
8002				$modal.find('[js-save-article]').on('click', function(){
8003					var $form = $(this).closest('[data-action]'),
8004						data = $form.find('input[type=text], input[type=radio], input[type=checkbox], input[name=article_id], input[name=prediction_id], select, textarea').serialize()
8005						;
8006
8007					$.ajax({ url: $form.data('action'), data: data, type: 'post', dataType: 'json',
8008						beforeSend: function(){
8009							$$.uniFormError($form);
8010						},
8011						success: function(data){
8012							if(data.error){
8013								$$.uniFormError($form, data.error);
8014							}else{
8015								$modal.arcticmodal('close');
8016								$elem.find('span').text('Изменить обоснование');
8017							}
8018						}
8019					});
8020				});
8021
8022
8023				$modal.find('[js-save-materials]').on('submit', function(e){
8024					e.preventDefault();
8025					var $form = $(this),
8026						$list = $form.closest('.office-materials').find('.office-materials-list')
8027						;
8028
8029					$form.ajaxSubmit({
8030						dataType: 'json',
8031						beforeSend: function(){
8032							$form.find('[button]').addClass('is-loading');
8033						},
8034						success: function(data){
8035							$form.find('[button]').removeClass('is-loading');
8036							$list.html(data.list);
8037						}
8038					});
8039
8040					return false;
8041
8042				});
8043
8044				$modal.find('[js-save-materials-input]').on('change', function(){
8045					console.log($(this).closest('form'));
8046					$(this).closest('form').trigger('submit');
8047				});
8048
8049				$modal.on('click', '[js-material-delete]', function(){
8050					var $elem = $(this),
8051						$item = $elem.closest('.office-materials-item')
8052						;
8053
8054					$.ajax({ url: '/office/library/?material-delete', data: {id: $item.data('id')}, dataType: 'json', type: 'post',
8055						beforeSend: function(){
8056							$item.hide(300, function(){ $item.remove() });
8057						},
8058						success: function(){
8059
8060						}
8061					});
8062				});
8063
8064			}
8065		});
8066	});
8067
8068
8069	$('[js-predictions-show-more]').on('click', function(e){
8070		e.preventDefault();
8071		var $elem = $(this);
8072		$elem.closest('.prediction-guesses').find('.mod-hidden').fadeIn();
8073		$elem.remove();
8074
8075	});
8076
8077	$('[js-open-event-items]').on('click', function(){
8078		$$.openModal($('.astro-items-modal'))
8079	});
8080
8081
8082	$('[js-smooth-scroll] .page-menu-link').on('click', function(e){
8083		e.preventDefault();
8084		var id = $(this).attr('href').substr(1);
8085
8086		$$.scrollTo($('#'+id), 500, 60, function(){
8087			location.hash = id;
8088		});
8089	});
8090
8091
8092});
8093
8094$(function(){
8095
8096	var $articles = $('.prediction');
8097	if($articles.length && document.location.hash.length > 1){
8098		var $element = $('#' + document.location.hash.substring(1));
8099		if($element.length){
8100			$$.scrollTo($element, 500, 118);
8101		}
8102	}
8103
8104});
8105
8106$(function(){
8107
8108	$('.prediction-guesses-item-comments-link').on('click', function(e){
8109		e.preventDefault();
8110		$(this).toggleClass('is-active').closest('.prediction-guesses-item').find('.prediction-guesses-item-comments').toggle();
8111	});
8112
8113	$('.prediction-guesses-item-votes-vote').each(function(){
8114		var lock = false;
8115
8116		var $button = $(this),
8117			$item = $button.closest('.prediction-guesses-item-votes'),
8118			$value = $item.find('.prediction-guesses-item-votes-value'),
8119			$negative = $item.find('.prediction-guesses-item-votes-vote.mod-negative'),
8120			$positive = $item.find('.prediction-guesses-item-votes-vote.mod-positive');
8121
8122		function recalculate(votes, vote){
8123			$item.addClass('is-voted');
8124			$value.text(votes).toggleClass('mod-positive', votes > 0).toggleClass('mod-negative', votes < 0);
8125			$negative.toggleClass('is-active', vote < 0);
8126			$positive.toggleClass('is-active', vote > 0);
8127		}
8128
8129		$button.on('click', function(e){
8130			e.preventDefault();
8131			if(lock) return; lock = true;
8132
8133			var vote = $button.hasClass('mod-positive') ? 1 : -1;
8134
8135			$item.addClass('is-loading');
8136
8137			recalculate(+$value.text() + vote, vote);
8138
8139			$.ajax({
8140				url: '?predictionVote',
8141				type: 'post',
8142				data: {predictionId: $item.data('id'), value: vote},
8143				dataType: 'json',
8144				success: function(response){
8145					if(response.success){
8146						recalculate(response.votes, response.vote);
8147					}
8148				},
8149				complete: function(){
8150					lock = false;
8151				}
8152			});
8153		});
8154	})
8155
8156});
8157$(function(){
8158    $('.promotions-list').owlCarousel({
8159        dragEndSpeed: 600,
8160        loop: true,
8161        items: 1,
8162        stagePadding: 0,
8163        margin: 0,
8164        autoHeight: false,
8165        mouseDrag: true,
8166        dots: true,
8167        nav: true,
8168        autoplay: false
8169    });
8170});
8171
8172$(function(){
8173    var $sections = $('.section');
8174
8175    var inview = function(instant){
8176        $sections.inViewport({partially: true, tolerance: true === instant ? $.windowHeight() / -6 : $.windowHeight() / -3}).each(function(){
8177            $(this).addClass('is-inview').triggerHandler('inview');
8178            if(true === instant) $(this).addClass('is-instant');
8179        });
8180        $sections = $sections.not('.is-inview');
8181
8182        if(!$sections.length){
8183            $$.document.off('.section-animate');
8184        }
8185    };
8186
8187    $$.document.on('scroll.section-animate', inview);
8188
8189    window.inview = inview;
8190});
8191$(function(){
8192
8193    $$.document.on('click', '[js-service-order]', function(e){
8194        e.preventDefault();
8195
8196        var $button = $(this),
8197            serviceId = $button.data('id');
8198
8199        if(!$$.isAuthenticated){
8200            return $$.openAuth();
8201        }
8202
8203        $$.openModal({
8204            url: $$.urlPrefix + '/services/?order',
8205            data: {id: serviceId},
8206            modules: ['astroEvent'],
8207            ajax: {
8208                xhrFields: {
8209                    withCredentials: true
8210                },
8211                crossDomain: true
8212            },
8213            afterOpen: function(modal, $modal, modalResponse){
8214                var $items = $modal.find('.services-mode-item'),
8215                    $dependency = $modal.find('.service-order-dependency'),
8216                    $mode = $modal.find('input[name=mode]'),
8217                    chooseMode,
8218                    chooseEvents = [];
8219
8220                $items.on('click', function(e){
8221                    e.preventDefault();
8222
8223                    var $item = $(this);
8224
8225                    if(!chooseMode){
8226                        $dependency.slideDown(300);
8227                    }
8228
8229                    chooseMode = $item.data('mode-id');
8230                    $mode.val(chooseMode);
8231                    $item.addClass('is-active').siblings($items).removeClass('is-active');
8232                });
8233
8234                $modal.on('change', 'input[name^=events]', function(){
8235                    var $input = $(this);
8236                    if($input.prop('checked')){
8237                        chooseEvents.push($input.prop('name'));
8238                    }else{
8239                        chooseEvents = chooseEvents.filter(function(item){
8240                            return item != $input.prop('name');
8241                        });
8242                    }
8243
8244                });
8245
8246                $modal.find('input[name^=events]').each(function(){
8247                    chooseEvents.push($(this).prop('checked', true).prop('name'));
8248                });
8249
8250                $modal.find('.list').on('afterInstall', function(){
8251                    $modal.find('input[name^=events]').each(function(){
8252                        $(this).prop('checked', chooseEvents.indexOf($(this).prop('name')) >=0);
8253                    });
8254                });
8255
8256                $modal.find('form').formHandle({
8257                    success: function(response){
8258                        $modal.arcticmodal('close');
8259                        $$.openModal($(response.content));
8260                    }
8261                });
8262            }
8263        });
8264    });
8265
8266});
8267$(function(){
8268
8269    //Залить аватар
8270    $$.uniFormHandle($('form[action="/office/settings/info/?avatar-save"]'), {
8271        beforeSubmit: function($form){
8272            $form.closest('.office-user-card-image').addClass('is-loading').addClass('no-photo');
8273        },
8274        afterSuccess: function(data, $form){
8275            $form.closest('.office-user-card-image').removeClass('is-loading').removeClass('no-photo').find('img').replaceWith(data.img);
8276            $('body').attr('data-has-avatar', 1);
8277        }
8278    });
8279
8280    $('form[action="/office/settings/info/?background-save"] input[type=file], form[action="/office/settings/info/?avatar-save"] input[type=file]').on('change', function(){
8281        if($(this).val()){
8282            $(this).closest('form').trigger('submit');
8283        }
8284    });
8285
8286
8287    //Удалить аватар
8288    $('[js-avatar-delete]').on('click', function(){
8289        var $elem = $(this);
8290        $$.confirm('Удалить аватар?', function(){
8291            $.ajax({url: '/office/settings/info/?avatar-delete', type: 'post', dataType: 'json',
8292                beforeSend: function(){
8293                    $elem.closest('.office-user-card-image').addClass('no-photo');
8294                },
8295                success: function(data){
8296                    $elem.closest('.office-user-card-image').find('img').replaceWith(data.img);
8297                    //console.log($elem.closest('.office-user-card-image').find('img'))
8298                    $('body').attr('data-has-avatar', 0);
8299                }
8300            });
8301        });
8302
8303    });
8304});
8305$(function(){
8306
8307    $('.slider-list').owlCarousel({
8308        loop: true,
8309        items: 1,
8310        stagePadding: 0,
8311        margin: 0,
8312        autoHeight: false,
8313        mouseDrag: false,
8314        dots: true,
8315        nav: true,
8316        autoplay: false
8317    });
8318
8319});
8320$(function(){
8321
8322    var $smiles,
8323        $context,
8324        request;
8325
8326    function loadSmiles(){
8327        if(request){
8328            return;
8329        }
8330        request = $.ajax({
8331            url: $$.urlPrefix + '/api/smiles/',
8332            type: 'get',
8333            cache: true,
8334            dataType: 'json',
8335            success: function(smiles){
8336                var body = '';
8337                body += '<div class="smiles">';
8338                smiles.forEach(function(smile){
8339                    body += '<a href="#" data-code="'+smile.code+'" class="smiles-item"><img src="'+smile.src+'" alt="" class="smile"></a>';
8340                });
8341                body += '</div>';
8342                $smiles = $(body);
8343                // keep the caret in the field while picking
8344                $smiles.on('mousedown', '.smiles-item', function(e){
8345                    e.preventDefault();
8346                });
8347                $smiles.on('click', '.smiles-item', function(e){
8348                    e.preventDefault();
8349                    attachSmile($(this).attr('data-code'));
8350                });
8351                // the panel grows as images load, so place it again
8352                $smiles.find('img').on('load', placeSmiles);
8353                $smiles.appendTo($('body')).hide();
8354                if($context){
8355                    openSmiles($context);
8356                }
8357            },
8358            error: function(){
8359                // let the next click retry instead of staying broken
8360                request = null;
8361            }
8362        });
8363    }
8364
8365    function placeSmiles(){
8366        if(!$smiles || !$context || !$smiles.is(':visible')){
8367            return;
8368        }
8369
8370        var contextOffset = $context.offset(),
8371            $window = $(window),
8372            top = contextOffset.top - $smiles.outerHeight() - 5,
8373            left = Math.min(contextOffset.left, $window.scrollLeft() + $window.width() - $smiles.outerWidth() - 10);
8374
8375        if(top < $window.scrollTop() + 5){
8376            top = contextOffset.top + $context.outerHeight() + 5;
8377        }
8378
8379        $smiles.css({
8380            top: top,
8381            left: Math.max(left, 10)
8382        });
8383    }
8384
8385    function closeSmiles(){
8386        if($smiles){
8387            $smiles.hide();
8388        }
8389        $context = null;
8390    }
8391
8392    function openSmiles($button){
8393        // a second click on the same button closes the panel
8394        if($smiles && $smiles.is(':visible') && $context && $context.is($button)){
8395            closeSmiles();
8396            return;
8397        }
8398
8399        $context = $button;
8400        if(!$smiles){
8401            loadSmiles();
8402            return;
8403        }
8404
8405        $smiles.show();
8406        placeSmiles();
8407    }
8408
8409    function insertAtCaret($input, code){
8410        var input = $input[0],
8411            value = $input.val(),
8412            start = typeof input.selectionStart === 'number' ? input.selectionStart : value.length,
8413            end = typeof input.selectionEnd === 'number' ? input.selectionEnd : value.length,
8414            before = value.slice(0, start),
8415            after = value.slice(end),
8416            text = (before && !/\s$/.test(before) ? ' ' : '') + code + (/^\s/.test(after) ? '' : ' ');
8417
8418        $input.val(before + text + after);
8419        if(input.setSelectionRange){
8420            input.setSelectionRange(before.length + text.length, before.length + text.length);
8421        }
8422        $input.trigger('focus').trigger('input');
8423    }
8424
8425    function attachSmile(code){
8426        if(!$context){
8427            return;
8428        }
8429
8430        var $input = $context.parent().find('input, textarea').eq(0);
8431        if($input.length){
8432
8433            if(window.smilesController){
8434                window.smilesController.timeout(function(){
8435                    if(!window.smilesController.scope.text){
8436                        window.smilesController.scope.text = '';
8437                    }
8438                    window.smilesController.scope.text += (window.smilesController.scope.text.match(/ $/) ? '' : ' ') + ':'+ code +':';
8439                });
8440            }else{
8441                insertAtCaret($input, ':'+ code +':');
8442            }
8443
8444        }
8445    }
8446
8447    $$.document.on('click', '[js-smiles]', function(){
8448        openSmiles($(this));
8449    });
8450
8451    // one shared "click outside" handler: the old $(document).one('click') added on every open
8452    // piled up and closed the panel right after the next open
8453    $$.document.on('click', function(e){
8454        if(!$smiles || !$smiles.is(':visible')){
8455            return;
8456        }
8457        var $target = $(e.target);
8458        if($target.closest('.smiles, [js-smiles]').length){
8459            return;
8460        }
8461        // the button sits inside <label class="form-input">, so the browser repeats the click on the textarea;
8462        // clicks in the field itself (also moving the caret) keep the panel open
8463        if($context && $target.is('input, textarea') && $target.closest($context.parent()).length){
8464            return;
8465        }
8466        closeSmiles();
8467    });
8468
8469    $$.document.on('keydown', function(e){
8470        if(e.keyCode === 27 && $smiles && $smiles.is(':visible')){
8471            closeSmiles();
8472        }
8473    });
8474
8475    $(window).on('resize', placeSmiles);
8476
8477    window.openSmiles = openSmiles;
8478
8479});
8480
8481
8482$(function(){
8483    $('.statistics').each(function(){
8484        var $statistics = $(this),
8485            $items = $statistics.find('.statistics-item'),
8486            $section = $statistics.closest('.section');
8487
8488
8489        $section.on('inview', function(){
8490            $items.each(function(i){
8491                setTimeout(function(){
8492                    $items.eq(i).addClass('do-animate').find('.statistics-item-number').numbergo({duration: 1900});
8493                }, 300 * i);
8494            });
8495        });
8496
8497
8498    });
8499});
8500$(function(){
8501
8502    inview(true);
8503});

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.