fx_debug=true;

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows())?true:false;
    }
};

var plugins=(function (){
return{
    plugins:[],
    eventlistener:[],
    is_mobile:isMobile.any(),
    window_height:320,
    body:false,
/////////////////Initialisation
    init:function(){
        this.is_mobile=isMobile.any();
        this.sections=[];
        this.sections = document.getElementsByClassName("section");
        if(!plugins.body) plugins.body=document.body;
        this.get_pluguins();
        
        if(fx_debug) console.log('plugins initialized');
    },
    get_pluguins:function(){
        var top=(window.pageYOffset || document.documentElement.scrollTop)  - (document.documentElement.clientTop || 0);
        var before=0;
        for (var i = 0; i < this.sections.length; i++) {
            this.get_section_data(i);
        }
        this.activate_plugins(this.parse_pluguins(document.body.getAttribute("defaultplugins")), i+1);
    },
    parse_pluguins:function(tmp_plugins){
        if(tmp_plugins){
            //if(fx_debug) console.log('Plugins to parse '+tmp_plugins);
            var plugins_arr=tmp_plugins.trim().split(' ')
            if(plugins_arr.length>0)
                return plugins_arr;
            else if(tmp_plugins.length>0)
                return [tmp_plugins.trim()];
        }else return [];
    },
    get_section_data:function(i){
        //Собираем все, что знаем о секции
        this.sections[i].plugins=this.parse_pluguins(this.sections[i].getAttribute("plugins"));
        this.sections[i].is_hidden=this.sections[i].getAttribute("data-hidden")=='true'?true:false;
        this.sections[i].id = this.sections[i].getAttribute("id");
        if(!this.sections[i].id||this.sections[i].id=='null'){
            this.sections[i].id='section_'+i;
            this.sections[i].setAttribute("id", this.sections[i].id);
        }
        this.activate_plugins(this.sections[i].plugins,i);

    },
    activate_plugins:function(tmp_plugins,i){
            for (var j = 0; j < tmp_plugins.length; j++) {
                if(tmp_plugins[j].length>1){
                    //if(fx_debug)  console.log('Is mobile: '+this.is_mobile+'; '+tmp_plugins[j]+': on mobile:  '+window[tmp_plugins[j]].on_mobile);
                    if(window[tmp_plugins[j]].on_mobile&&this.is_mobile||!this.is_mobile){
                        this.add_plugins(window[tmp_plugins[j]].event, tmp_plugins[j]);
                        window[tmp_plugins[j]].add(i);
                    }
                }
            }
            
    },
    call_scroll:function(){
        var top=(window.pageYOffset || document.documentElement.scrollTop)  - (document.documentElement.clientTop || 0);
        if(top<=0) top=0;
        this.check_viewport(top);
        this.call_all('scroll', top);
    },
    add_plugins:function(tevent, name){
        //if(fx_debug) console.log('add_plugins '+ tevent+' '+name);
        var keys=Object.keys(this.plugins);
        if(keys.indexOf(tevent)==-1) {
            this.plugins[tevent]=[];
            this.plugins[tevent][0]=name;
            if(!this.eventlistener[tevent])
                {
                    window.addEventListener( tevent, this.callback );
                    this.eventlistener[tevent]=true;
                }
        }
        else{
            if(this.plugins[tevent].indexOf(name)==-1){
                this.plugins[tevent][this.plugins[tevent].length]=name;
            }
        }
        //if(fx_debug) console.log(this.plugins);
    },
    main_menu:function(){
        console.log(1);
        //При вызове в #main_menu запишется информация о блоках из data-name
        var main_menu= $('#main_menu');
        if(main_menu)
            str='<ul class="main_menu">';
        for (var i = 0; i < this.sections.length; i++) {
            this.sections[i].name = this.sections[i].getAttribute("data-name");
            if(main_menu&&this.sections[i].name){
                str+='<li class="item"><a href="#'+this.sections[i].id+'">'+this.sections[i].name+'</a>';
            } 
        }
        if(main_menu){
            str+='</ul>'
            main_menu.html(str);
        }
    },
/////////////////Reset
    reset:function(){
        if(fx_debug) console.log('------------reset--------------');
        this.window_height=document.documentElement.clientHeight;

        for (var j in this.plugins) {
            for (var i = 0; i < this.plugins[j].length; i++) {
                if(window[this.plugins[j][i]])
                    window[this.plugins[j][i]].reset();
            }
        }
        this.heights();
        this.call_scroll();

    },
    heights:function(){
        var before=0;
        for (var i = 0; i < this.sections.length; i++) {
            before=this.calculate_visible_heights_inner(i, before);
        }
    },
    calculate_visible_heights_inner:function(i, before){
        this.sections[i].style.minHeight='0';//Сбрасываем, чтобы узнать новую высоту
        this.sections[i].height=this.sections[i].clientHeight;
        //this.sections[i].style.minHeight=this.sections[i].height+'px';
        this.sections[i].start=before;
        this.sections[i].end=before+this.sections[i].height;
        if(!this.sections[i].is_hidden){ 
            before+=this.sections[i].height; //Если не скрытая секция, то следующая ++
        }
        return before;
    },


/////////////////Events
    call_all:function(tevent, top){
        if(this.plugins[tevent])
            for (var i = 0; i < this.plugins[tevent].length; i++) {
                window[this.plugins[tevent][i]].onChange(top);
            }
    },
    check_viewport:function(top){
        //Узнаем, какие секции в поле видимости
        for (var i = 0; i < this.sections.length; i++) {
            this.check_viewport_section(i, top);
        }
    },
    check_viewport_section:function(i, top){

        this.sections[i].in_viewport=(this.sections[i].end>=top&&this.sections[i].start<=top+this.window_height)?true:false;
    

    },
    callback:function(event){


        if(event.type=='scroll'){
            var top=(window.pageYOffset || document.documentElement.scrollTop)  - (document.documentElement.clientTop || 0);
            if(top<=0) top=0;
            plugins.check_viewport(top);
            plugins.call_all(event.type, top)

        }   
        
    },

/////////////////Section manipulation
    hide_section:function(i){
        if(!this.sections[i].is_hidden){
            this.sections[i].is_hidden=true;
            this.set_visible_section(i);
        }
    },
    show_section:function(i){
        if(this.sections[i].is_hidden){
            this.sections[i].is_hidden=false;
            this.set_visible_section(i);
        }
    },
    toggle_section:function(i){
        this.sections[i].is_hidden=this.sections[i].is_hidden?false:true;
        this.set_visible_section(i);
    },
    set_visible_section:function(i){
        this.sections[i].is_hidden
        if(this.sections[i].is_hidden)
            this.sections[i].classList.add('section_hidden');
        else
            this.sections[i].classList.remove('section_hidden');

    },
/////////////////System functions
    findPos: function(obj){
         var posX = obj.offsetLeft;
         var posY = obj.offsetTop;
         while(obj.offsetParent){
            if(obj!=document.body){
               posX=posX+obj.offsetParent.offsetLeft;
               posY=posY+obj.offsetParent.offsetTop;
               obj=obj.offsetParent;
            }
            else break;

         }
            var posArray=[posX,posY]
            return posArray;         
    },

}
})();

//this.sections[i].id
//this.sections[i].height
//this.sections[i].name
//this.sections[i].start
//this.sections[i].end
//this.sections[i].is_hidden
//this.sections[i].in_viewport

//this.sections[i].before 
//this.body - элемент боди


//Плагин встраивается по умолчанию
var dasable_hover=(function (){
return{
    initialized:false,
    event:'scroll',
    before:0,
    now:0,
    on_mobile:false,
    interval:false,
    disabled1:false,
    init:function(){},
    add:function(){},
    reset:function(){},
    onChange:function(scrollY){            
        this.now=scrollY;
        if(this.before!=this.now){
            if(!this.disabled1) {
                //if(fx_debug) console.log('dasable_hover classList.add');
                this.disabled1=true;
                plugins.body.classList.add('disable-hover');
                this.interval=setInterval(function(){
                    dasable_hover.removedisablehover();
                }, 200);
            }
        }
    },
    removedisablehover:function(){
        //if(fx_debug) console.log('dasable_hover try deactivate interval');
        if(this.disabled1==true&&this.before==this.now){
            //if(fx_debug) console.log('dasable_hover ok! deactivated interval');
            plugins.body.classList.remove('disable-hover');
            clearInterval(this.interval);
            this.disabled1=false;
        }this.before=this.now;
    },
}
})();

var fix_on_top=(function (){
return{
    initialized:false,
    event:'scroll',
    on_mobile:false,

    ft:function(i){
        return plugins.sections[this.fix_elements[i]];
    },
    init:function(){
        this.fix_elements=[]; 
        this.fixed_before=0;

    },
    reset:function(){
        this.initialized=false; 
        if(fx_debug) console.log('fix.reset()');
    },


    add:function(i){
        if(fx_debug) console.log('fix add el '+i);
        if(!this.initialized){ 
            this.init();
            this.initialized=true;
        }
        this.fix_elements[this.fix_elements.length]=i;
        plugins.sections[i].is_fixed_on_top=plugins.sections[i].getAttribute("data-fixed_on_top")=='true'?true:false;
    },
    before:0,
    onChange:function(scrollY){
        scrolldown=(this.before<scrollY)?true:false; this.before=scrollY;
        fixed_before=0;
        for (var i = 0; i < this.fix_elements.length; i++) {
                var fi=this.fix_elements[i];
                var next=fi+1;
                var section=plugins.sections[fi];

                section.dynamic=(scrolldown&&scrollY>plugins.window_height+section.start)?section.dynamic+1:0;
                var fixed_hidden=(section.dynamic>30)?true:false;
                var fixed=(scrollY+fixed_before>section.start);
                section.fixed_top=fixed?((fixed_hidden)?('-'+section.height+'px'):(fixed_before+'px')):'auto';
                section.fixed_opacity=fixed?((fixed_hidden)?'0':'1'):'1';
                if(fixed){
                    if(!fixed_hidden){
                        fixed_before+=section.height;
                    }
                    section.fixed_margin=plugins.sections[i].is_fixed_on_top?0:section.height;
                    if(i>=1){
                        var before_index=this.fix_elements[i-1];
                        if(before_index==fi-1){
                            //Значит предыдущий тоже зафиксенный элемент. Задаем некст
                            section.fixed_margin+=plugins.sections[before_index].fixed_margin;
                            plugins.sections[before_index].fixed_margin=0;

                        }
                    }
                }else{
                    section.fixed_margin=0;
                }
            if(fi.fixed!=fixed){
                section.style.top=section.fixed_top
                if(fixed){
                    section.style.position='fixed';
                    section.classList.add('fixed');
                }else{
                    section.style.position=section.is_fixed_on_top?'fixed':'relative';
                    section.classList.remove('fixed');
                }
                fi.fixed=fixed;

            }
            if(fi.fixed_hidden!=fixed_hidden){
                section.style.top=section.fixed_top;
                section.style.opacity=section.fixed_opacity;
                fi.fixed_hidden=fixed_hidden;
            }
            plugins.sections[fi]=section;
        }

        for (var i = 0; i < this.fix_elements.length; i++) {
            var fi=this.fix_elements[i];
            var next=fi+1;
            if(next<plugins.sections.length){
                plugins.sections[next].style.marginTop=plugins.sections[fi].fixed_margin+'px';
            }

        }
    },
}
})();


var onscreen=(function (){
return{
    initialized:false,
    event:'scroll',
    on_mobile:false,
    is_lotty:false,
    fix_elements:[],
    ft:function(index_el){
        return plugins.sections[this.fix_elements[index_el]['index']];
    },
    init:function(){this.fix_elements=[]; },
    reset:function(){},
    add:function(index_el){
        var j=this.fix_elements.length;//new fixed index
        this.fix_elements[j]={};
        this.fix_elements[j].index=index_el;
        // this.ft(j).style.overflow='hidden';
        this.ft(j).classList.add('canonscreen');

    },
    dynamic:0,
    before:0,
    onChange:function(scrollY){
        for (var i = 0; i < this.fix_elements.length; i++) {
            var onscreen=plugins.sections[this.fix_elements[i].index].in_viewport;
            if(this.fix_elements[i]['onscreen']!=onscreen){    
                if(onscreen){
                    this.ft(i).classList.add('onscreen');
                }
                else{
                    this.ft(i).classList.remove('onscreen');
                }
            }
        }
    },
}
})();
var Overlay=overlay=(function (){
return{
    initialized:false,
    event:'none',
    on_mobile:true,
    is_lotty:false,
    overlays:[],
    ft:function(index_el){
        return plugins.sections[this.overlays[index_el]['index']];
    },
    init:function(){
        console.log(this.initialized);
        if(!this.initialized){
            this.overlays=[];
            // this.overlay=$('#overlay');
            // this.body=$('body');

            this.initialized=true;
            console.log('123');
        }
    },
    reset:function(){},
    add:function(index_el){
        var j=this.overlays.length;//new fixed index
        
        this.overlays[j]={};
        this.overlays[j].index=index_el;

        this.ft(j).classList.add('overlay_section');
        this.overlays[j].id=this.ft(j).id;
        this.overlays[j].opened=this.ft(j).getAttribute("data-opened");
        if(this.overlays[j].opened)
            this.open(this.overlays[j].id);

        //this.create_close(this.ft(j));
        if(window.location.toString().split("#")[1]==this.overlays[j].id)
            this.open(this.overlays[j].id);

        
    },

    create_overlay:function(){
        this.overlay_section = document.createElement('div');
        this.overlay_section.classList.add('light');
        this.overlay_section.classList.add('section');
        this.overlay_section.classList.add('overlay_section');
        this.overlay_section.id='main_overlay';
        this.overlay_section.setAttribute("plugins",'overlay');

        //this.create_close(this.overlay_section);

        this.overlay_content = document.createElement('div');
        this.overlay_content.classList.add('content');

        this.overlay_section.appendChild(this.overlay_content);
        document.body.appendChild(this.overlay_section);
            
    },
    create_close:function(el){
        var close = document.createElement('div');
        close.classList.add('close_button');
        close.classList.add('icon');
        close.classList.add('icon-close');
        close.addEventListener( 'click', function ( event ) {
            overlay.close();
        });
        el.appendChild(close);
    },
    dynamic:0,
    before:0,
    open:function($el_id){
        this.close();
        for (var i = 0; i < this.overlays.length; i++) {
            if(this.overlays[i].id==$el_id){
                this.ft(i).classList.add('overlay_opened');
                document.body.classList.add('overlay_opened');
                this.overlays[i].opened=true;
                window.location.hash = this.overlays[i].id;
            }
        }

    },
    close:function(){
        for (var i = 0; i < this.overlays.length; i++) {
            if(this.overlays[i]['opened']){
                this.ft(i).classList.remove('overlay_opened');
                document.body.classList.remove('overlay_opened');
                this.overlays[i].opened=false;
            }
        }
        window.location.hash = '';
    },
    openonly:function(header, text){
        this.overlay_content.innerHTML='<h1>'+header+'</h1>'+text;
        this.open('main_overlay');
    },

    /////////////////////////////////////////////////////////////OLD
    getViewportHeight:function() {
      return ((document.compatMode || this.isIE) && !this.isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : plugins.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
    },
    getDocumentHeight:function() {
      return Math.max(document.compatMode != 'CSS1Compat' ? plugins.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight());
    },

    // open: function(overlay, status) {
    // Overlay.section('Подождите немного, пожалуйста', Overlay.spinner); 
    // this.overlay.addClass('opened');
    // this.body.addClass('overlay');

    //     localStorage.setItem('overlay', overlay);
    //     $.ajax({
    //       method: "POST",
    //       url: "/?overlay="+overlay,
    //       data: {'status':status},
    //     }).done(function( resp ) { 
    //         Overlay.afterajax(resp);
    //     });
       
        
    // },
    openform: function(overlay, formid) {
    var data=$('#'+formid).serialize();
    Overlay.section('Подождите немного, пожалуйста', Overlay.spinner); 
    this.body.addClass('overlay');
        localStorage.setItem('overlay', overlay);
        $.ajax({
          method: "POST",
          url: "/?overlay="+overlay,
          data: data,
        }).done(function( resp ) { 
            Overlay.afterajax(resp);
        });
       
        
    }, 
    openarr: function(overlay, arr) {
    console.log('hi');
    Overlay.section('Подождите немного, пожалуйста', Overlay.spinner); 
    this.body.addClass('overlay');
    
        if(localStorage.getItem('overlay')=='post'){
            overlay='nextpost';
            localStorage.setItem('overlay', 'post');
        }else 
            localStorage.setItem('overlay', overlay);
        $.ajax({
          method: "POST",
          url: "/?overlay="+overlay,
          data: arr,
        }).done(function( resp ) { 
            Overlay.afterajax(resp);
        });
       
        
    },
    opensilent: function(overlay, status) {

        localStorage.setItem('overlay', overlay);
        $.ajax({
          method: "POST",
          url: "/?overlay="+overlay,
          data: {'status':status},
        }).done(function( resp ) { 
            this.body.addClass('overlay');
            Overlay.afterajax(resp);
        });
        
        
    },

    closebtn:'<div class="floatright  border round animation hrotate90 icon icon-close close"  onclick="Overlay.close()"></div>',
    spinner:'<div class="floatcenter icon icon-spinner"></div>',
    section:function(header, text){
        Overlay.overlay.html( '<div   class="content light" onclick="event.stopPropagation();window.event.cancelBubble = true;"><div class="block ">'+Overlay.closebtn+
             '<h1>'+header+'</h1>'+text+
             '</div></div>');
    },

    action: function(arr) {
        Overlay.section('Подождите немного, пожалуйста', Overlay.spinner);
        overlay=localStorage.getItem('overlay');
        $.ajax({
          method: "POST",
          url: "/?overlay="+overlay,
          data: arr,
        }).done(function( resp ) { 
            Overlay.afterajax(resp);
        });
    },
    afterajax: function(resp) {
       var obj = jQuery.parseJSON( resp );
            Overlay.section(obj.header,obj.text);

            if(obj.script)
                $.getScript(obj.script);
            overlay=localStorage.getItem('overlay');
            //if(overlay=='login') grecaptcha.reset();
    },
    hiddenaction: function(overlay, arr) {
        $.ajax({
          method: "POST",
          url: "/?overlay="+overlay,
          data: arr,
        });
    },
    // close: function() {
    //     localStorage.setItem('overlay', '');
    //     this.overlay.removeClass('opened'); 
    //     this.body.removeClass('overlay');
    // },
}
})();
// var overlay;
//Overlay.create_overlay();

var paralax=(function (){
return{
    event:'scroll',
    initialized:false,
    on_mobile:false,

    init:function(){
        this.paralax_elements=[];
    },
    reset:function(){
        this.initialized=false;   
    },
    add:function(index){
        console.log('add')
        if(!this.initialized){ 
            this.init();
            this.initialized=true;
        }
        var j=this.paralax_elements.length;
            this.paralax_elements[j]={};
            this.paralax_elements[j].index=index;
            if(this.paralax_elements[j].media=plugins.sections[index].getElementsByClassName("media"))
                if(this.paralax_elements[j].media.length>0){
                    this.paralax_elements[j].is_media=true;
                    console.log('media')
                    for (var mi = this.paralax_elements[j].media.length - 1; mi >= 0; mi--) {
                        media=this.paralax_elements[j].media[mi];
                        var height=media.clientHeight;

                        var parent=media.parentElement;
                        console.log(height);
                        parent.style.height=height+'px';
                        parent.style.overflow='hidden';
                        parent.style.position='relative';
                        media.style.position='absolute';
                        media.style.top='0';
                    }
                }
        //plugins.sections[this.paralax_elements[j].index].style.backgroundSize='cover';
    },

    paralax_function:function(i, top){
        var koef=plugins.sections[this.paralax_elements[i].index].getAttribute("data-paralax_k")||0.25;
        var yPos=Math.round((top-plugins.sections[this.paralax_elements[i].index].start)*koef);

        if(this.paralax_elements[i].is_media){
            for (var j = this.paralax_elements[i].media.length - 1; j >= 0; j--) {
                this.paralax_elements[i].media[j].style.transform='translateY('+yPos + 'px)';
            }
        }
        //plugins.sections[this.paralax_elements[i]['index']].style.backgroundPosition='50% '+yPos + 'px';  
            
    },
    onChange:function(top){

        for (var i = 0; i < this.paralax_elements.length; i++) {

            if(plugins.sections[this.paralax_elements[i].index].in_viewport){
                this.paralax_function(i, top);
                console.log(plugins.sections[this.paralax_elements[i].index].in_viewport);
            }
        };  
    },
}
})();

var fastscroll=(function (){
return{
    event:'scroll',
    on_mobile:true,
    findPos: function(obj){
         var posX = obj.offsetLeft;
         var posY = obj.offsetTop;
         while(obj.offsetParent){
            if(obj!=plugins.body){
               posX=posX+obj.offsetParent.offsetLeft;
               posY=posY+obj.offsetParent.offsetTop;
               obj=obj.offsetParent;
            }
            else break;

         }
            var posArray=[posX,posY]
            return posArray;         
    },
    init:function(){
        this.paralax_elements=[];

    },

    reset:function(){
        this.initialized=false;   
    },
    add:function(index){

        if(!this.initialized){ 
            this.init();
            this.initialized=true;
        }

        var pos=this.findPos(plugins.sections[index]);
        var index_el=this.paralax_elements.length;
            this.paralax_elements[index_el]={};
            this.paralax_elements[index_el].start=pos[1];
            this.paralax_elements[index_el].page=1;
            this.paralax_elements[index_el].index=index;
            this.paralax_elements[index_el].height=plugins.sections[index].clientHeight;
            this.onChange(window.scrollY);
    },
    onChange:function(scrollY){
        

            
        for (var i = 0; i < this.paralax_elements.length; i++) {
            if(scrollY>this.paralax_elements[i]['start']&&scrollY<this.paralax_elements[i]['start']+this.paralax_elements[i]['height']){
                if(this.lastscrolly<scrollY){
                    if(this.paralax_elements[i]['height']>plugins.window_height){
                        $to=this.paralax_elements[i]['start']+plugins.window_height*this.paralax_elements[i]['page'];
                        this.paralax_elements[i]['page']++;
                    }else{
                        $to=this.paralax_elements[i]['height']+this.paralax_elements[i]['start'];
                    } 
                }else{
                    if(this.paralax_elements[i]['height']>plugins.window_height){
                        $to=this.paralax_elements[i]['start']-plugins.window_height*this.paralax_elements[i]['page'];
                        this.paralax_elements[i]['page']--;
                    }else{
                        $to=this.paralax_elements[i]['start'];
                    }   
                }
                window.scroll(0,$to);
            }
        };  
        this.lastscrolly=scrollY;
    },
}
})();
var up=(function (){
return{
    event:'scroll',
    on_mobile:false,
    init:function(){
        
    },

    reset:function(){
        
    },
    add:function(index){
        
        if(!this.initialized){ 
            this.init();
            this.initialized=true;
        }
        this.i=index;
    },
    onChange:function(scrollY){
        if(this.i){
            
            if(plugins.window_height<scrollY){
                
                if(!this.shown){
                    if(fx_debug) console.log('up');
                    plugins.sections[this.i].classList.add('show_bottom');

                    this.shown=true;
                }
            }
            else{ 
                if(this.shown){
                    plugins.sections[this.i].classList.remove('show_bottom');
                    this.shown=false;
                }
            }
        }
    },
}
})();

var reader=(function (){
return{
    event:'scroll',
    on_mobile:false,

    getDocumentHeight:function() {
      return Math.max(document.compatMode != 'CSS1Compat' ? plugins.body.scrollHeight : document.documentElement.scrollHeight, this.getViewportHeight());
    },

    getViewportHeight:function() {
      return ((document.compatMode || this.isIE) && !this.isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : plugins.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
    },

    init:function(){
        this.ua = navigator.userAgent.toLowerCase();
        this.isOpera= (this.ua.indexOf('opera')  > -1);
        this.isIE= (!this.isOpera && this.ua.indexOf('msie') > -1);
        this.body_height=this.getDocumentHeight();
        this.reader=document.getElementById('reader');
        this.bottom=document.getElementById('inside_section_5').clientHeight;
        this.onChange(window.scrollY);
        
    },
    reset:function(){
        
    },
    add:function(index){
        
        if(!this.initialized){ 
            this.init();
            this.initialized=true;
        }
    },
    onChange:function(scrollY){
        this.reader.style.width=(((scrollY)/(this.body_height-this.bottom-plugins.window_height))*100)+'%';
    },
}
})();
var other_module=(function (){
return{
    event:'scroll',

    init:function(){

    },
    reset:function(){
        
    },
    add:function(){
        
    },
    on_change:function(){
        
    },
}
})();

var Login = (function () { 
    return {
        forget: function(e) {
            if(e) if(e.keyCode != 13&&e.which != 13) return false;

            var login=$('#forget_email').val();
            if(!login) $('#forget_email').parent().parent().addClass('error');
            else Overlay.action({login21:login, drop_pass:1, status:2});
        },
        register: function(e) {
            if(e) if(e.keyCode != 13&&e.which != 13) return false;

            var login=$('#register_email').val(),
                pass1=$('#register_pass1').val(),
                pass2=$('#register_pass2').val(),
                email_me=($("#register_sendme").attr("checked") == 'checked'),
                agry=($("#register_apply").attr("checked") == 'checked');
            var errortext='';
            if(!login){
                $('#register_email').parent().parent().addClass('error');
                errortext='Введите логин';
            }
            else if(!pass1){
                $('#register_pass1').parent().parent().addClass('error');
                errortext='Введите пароль';
            }else if(!pass2){
                $('#register_pass2').parent().parent().addClass('error');
                errortext='Повторите пароль';
            }else if(pass1!=pass2){
                $('#pass2').parent().parent().addClass('error');
                errortext='Пароли не совпадают';
            }else if(agry){
                $('#register_apply').parent().parent().addClass('error');
                errortext='Надо принять условия';
            }else
                Overlay.action({login21:login, pas1:pass1, pas2:pass2, register_now_me:1, agry:1, post_mail:(email_me?1:0),status:1});
            $('#messenger').html(errortext);
        },

        change_pass: function(e) {
            if(e) if(e.keyCode != 13&&e.which != 13) return false;

            var oldpass=$('#oldpass'),
                newpass=$('#newpass'),
                newpass2=$('#newpass2'),
                errortext='';

            if(!oldpass.val()){
                oldpass.parent().parent().addClass('error');
                errortext='Введите старый пароль';
            }
            else if(!newpass.val()){
                newpass.parent().parent().addClass('error');
                errortext='Введите новый пароль';
            }else if(!newpass2.val()){
                newpass2.parent().parent().addClass('error');
                errortext='Повторите пароль';
            }else if(newpass.val()!=newpass2.val()){
                newpass2.parent().parent().addClass('error');
                newpass.parent().parent().addClass('error');
                errortext='Пароли не совпадают';
            }else
                Overlay.action({oldpass: oldpass.val(), newpass: newpass.val(), newpass2: newpass2.val(), status:1});

            $('#messenger').html(errortext);
        },
        callback: function(e) {
            if(e) if(e.keyCode != 13&&e.which != 13) return false;

            var callback_phone=$('#callback_phone'),
            callback_name=$('#callback_name'),
                errortext='';

            if(!callback_phone.val()){
                callback_phone.parent().parent().addClass('error');
                errortext='Введите телефон';
            }else if(!callback_name.val()){
                callback_name.parent().parent().addClass('error');
                errortext='Введите ваше имя';
            }
            else
                Overlay.action({callback_name: callback_name.val(), callback_phone: callback_phone.val(), status:1});

            $('#messenger').html(errortext);
        },
        login: function(e) {
            if(e) if(e.keyCode != 13&&e.which != 13) return false;

            var login=$('#login_email').val(), pass=$('#login_pass').val();
            if(!login) $('#login_email').parent().parent().addClass('error');
            else if(!pass) $('#login_pass').parent().parent().addClass('error');
            else Overlay.action({login21:login, pass:pass});
        },
        logout: function() {
            Overlay.action({logout:1});
        },

    }
})();

var tabs = (function () { 
  return {  

    // Действие: открыть вкладку
    open: function(el) {
        var _this = $(el); 
        _this.parent().parent().children('.tab').removeClass('tab-current').children('.tab-content').hide();
        _this.parent().toggleClass('tab-current').children('.tab-content').show();
        window.scroll(0,_this.offset().top-fix_on_top.fixed_before);
        event.preventDefault();
        window.dispatchEvent(new Event('resize'));
        return false;
    },

    init: function(moduleName, unicName) {
        var li = $('.tabs').children('.tab');
        li.each(function(index, el) {
            if ($(el).hasClass('tab-current')) {
                $(el).children('.tab-content').show();
            } else {
                $(el).children('.tab-content').hide();
            }
        });
        window.dispatchEvent(new Event('resize'));
    }

}})();



var already_liked=false;
function like(id){
    ymaps.suggest('мыт').then(function (items) {
    console.log(items);
});
    if(!already_liked){
        $.ajax({
          method: "POST",
          url: "/?overlay=like&id_liked_page="+id,
        }).done(function( resp ) { 
            var obj = jQuery.parseJSON( resp );
            if(obj.error=='yes') {
                $('#stat_like').html(+$('#stat_like2').html()-1);
                $('#stat_like2').html(+$('#stat_like2').html()-1); 
            }
            $('#share').html(obj.text);       
            $('#share').addClass('opened'); 

        }); 
        $('#stat_like').html(+$('#stat_like').html()+1);
        $('#stat_like2').html(+$('#stat_like2').html()+1); 

        already_liked=true;
    }
}



// var photo = document.getElementById("#bx2"); //or use jQuery's $("#photo")
// TweenLite.from(photo, 1.5, {width:100});
// var lastScrollTop = 0;
// $(window).scroll(function(){
// var scrollPosition = $(this).scrollTop();
// if ( scrollPosition > lastScrollTop ){
//    TweenLite.to('#bx2',0.5,{y:"0",ease:Quad.easeInOut},0.25);
// } else {
//    TweenLite.to('#bx2',0.5,{y:"+=50",ease:Quad.easeInOut},0.25);
// }
// lastScrollTop = scrollPosition;
// });
function star(_this, id, i){
                $.ajax({
                method: "POST",
                url: "/",
                data: {
                    'addstars':i,
                    'addstars_id':id,

                },
            }).done(function( resp ) { 
                $(_this).parent().parent().html(resp);
            });

}


function format(){
    var str="";
    for (var i = selected.length - 1; i >= 0; i--) {
      str+=((selected[i]['selected'])?'<div class="row"><div class="label" >'+selected[i]['name']+' - <span class="price">'+selected[i]['price']+' руб.</span ></div></div>':'');
    }
    var price=result.html();
    var srok=srokhidden.val();
    var month=Math.floor(srok/31)+1;
    if(month>6) month=6
    str+='<h2>Итог: '+price+' руб, '+month+' мес</h2>';
    return str;
}
function validateform(_this){
    $(_this).parent().parent().find('.required').removeClass('error').each(function(i, element) {

    var _el = $(element);
    var input=_el.find('input');

    if (input.val()=='') {
        _el.addClass('alert');
        if (event.preventDefault) {event.preventDefault();} else {event.returnValue = false;}
    }
    });
}

function plugins_onload(){
    plugins.init();
    console.log('onload_reset');
    plugins.reset();
    tabs.init();
    // Overlay.init();
    window.addEventListener("resize", plugins_resize);
    window.addEventListener('orientationchange', plugins_orientation_reset);
    window.removeEventListener("load",plugins_onload,false); //no longer needed
}
need_to_resize=true;
function plugins_resize(){
    if(need_to_resize){
        console.log('plugins_resize_reset');
        plugins.reset();
    }
}

portret_orientation=true;
function plugins_orientation_reset()
{
    new_orienation=(screen.height > screen.width);
    if(portret_orientation!=new_orienation){
        portret_orientation=new_orienation;
        console.log('plugins_plugins_orientation_reset');
        plugins.reset();
        need_to_resize=false;
    }
}

window.addEventListener("load", plugins_onload, false);

function change_textarea(e) {
  var input = e.target;
  var hiddenClone=input.parentNode.children[1];
  var textAreaOriginalHeight = input.offsetHeight;
  var newValue = input.value + '\n';
  newValue=newValue.replace(/\n/g, '<br>');
  hiddenClone.innerHTML = newValue;
  var hiddenCloneHeight = hiddenClone.offsetHeight;
  input.style.height = hiddenCloneHeight+ "px";
}
