/**
 * Neuron Frame Work
 * for Neuron Soft application
 * www.neuron.com.pl
 * 'use strict';
 */


//***********************
// Likwidacja preloadera
//***********************
function remove_preoader(speed){
    $("#preloader #preloader_image").fadeOut();
    $("#preloader").delay(speed).fadeOut("slow",function(){$(this).remove();});

}

$(window).on('load',(function() {  remove_preoader(50); }));

////
var audioElement = document.createElement('audio');

var lang=new Array(270);
var lang_length=271;
lang[0]='Tak';
lang[1]='Nie';
lang[2]='OK';
lang[3]='Anuluj';
lang[4]='Odświerz';
lang[5]='Wyłączone';
lang[6]='Zmień';
lang[7]='Nazwa';
lang[8]='';
lang[9]='';
lang[10]='Połączenie z serwerem';
lang[11]='Brak połączenia z serwerem';
lang[12]='POŁĄCZENIE Z SERWEREM ZABLOKOWANE';
lang[13]='UTRACONO POŁĄCZENIE<br> Z SERWEREM';
lang[14]='zablokowano o';
lang[15]='Blokuj po utracie połączenia';
lang[16]='';
lang[17]='PIN: ( 0 to hasło)';
lang[18]='Logowanie';
lang[19]='Hasło';
lang[20]='Nieprawidłowe hasło';
lang[21]='Nie masz uprawnień';
lang[22]='Czas logout sec.';
lang[23]='Czas logout slow min.';
lang[24]='Logowanie PINem';
lang[25]='Tłumaczenie';
lang[26]='po zatwierdzeniu aplikacja zostanie przeładowana';



lang[37]='';
lang[38]='Czas odczytu';
lang[39]='Ekran';
lang[40]='Ustawienia';
lang[41]='Motyw';
lang[42]='jasny';
lang[43]='ciemny';
lang[44]='HUD';
lang[45]='HUD FX';

lang[50]='Czas';
lang[51]='Data';
lang[52]='od';
lang[53]='do';
lang[54]='';
lang[55]='';
lang[56]='';
lang[57]='';
lang[58]='';
lang[59]='';

var nth_body_pattern=   ['','../_fw/p2.png','../_fw/p_grid1b.png'];
var nth_body=           ['#095797', 'black',    'black',    'black'];
var nth_bg=             ['white',   '#3E3E3E',  '#132A3A',  'black'];

//var nth_div_bg=         ['#F9F9F9',   '#3E3E3E',  'black'];
//var nth_div_frame=      ['gray',  'black',    'white'];




//function th_divclass(d){     $(d).addClass( 'th_div_'+nApp.cfgi.theme_style   ) }




// Singleton nApp

var nApp= new NApp_constructor();


//// tools
function MakeScrollBox(dv){

    $( dv).addClass('scrollbox_wrapper').wrapInner( "<div class='scrollbox'  > </div>");
    var sb=  new IScroll( dv , {
        scrollX: true,
        mouseWheel: true,
        scrollbars: true,
        interactiveScrollbars:true,
        click: true
        ,preventDefaultException: {  tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|CHECKBOX)$/  }
    });
    setInterval ( function() {
        if ( sb.scrollerHeight==0 &&  $(dv).is(':visible') ){ sb.refresh();  }
    }, 1350 );
    return sb;
}

// akcje dla menu
function nAction(cmd,arg){
    switch (cmd){
        case 'a':       window.open(arg ,'_self');           break;
        case 'a_':      window.open(arg ,'_blank');          break;
        case 'call':    is_callback(arg);                    break;
        case 'left_box_toggle':   nApp.view.left_box_toggle() ;      break;
        case 'left_box_show':     nApp.view.left_box_slide(true) ;     break;
        case 'left_box_hide':     nApp.view.left_box_slide(false) ;    break;

        case 'right_box_toggle':  nApp.view.right_box_toggle() ;      break;
        case 'right_box_show':   nApp.view.right_box_slide(true)  ;      break;
        case 'right_box_hide':   nApp.view.right_box_slide(false) ;      break;
    }
}


//**************************************
//  nApp  + View + status bar + tool bar
//**************************************

/*
TODO
- select disable
- load set and lang from serwer
 */

function NAppCfgInfo_constructor(){

    var that=this;
    this.debug_mode=false;
    this.debug_mode_event_time=false;

    //app info
    this.theme_style=0;
    this.setStyle=function(nr){
        this.theme_style=nr;
        this.BodyColor=nth_body[nr];
        this.BodyPattern=nth_body_pattern[nr];
    };


    //timer get data
    this.rf_timer_use=false;       // timer data refresh on/off
    this.rf_timer_speed=100;       // interval
    this.rf_timer_lock=true;       // blokada po  x błędach
    this.rf_timer_xs=10;

    this.app_name='aplikacja';
    this.title='';
    this.app_desc='opis';
    this.help_url='';
    this.app_start='';

    this.lib_base_name='';     // nazwa biblioteki master
    this.lib_base_id=14;       // id biblioteki master
    this.lib_base_id_srv=333;  // id bibiioteki master (srv)
    this.host_version='0.0.0'; // nazwa i numer pid hosta ??
    this.tzone=0;

    this.footer_info='App for evrything  neuron.com.pl';

    this.set_pin=0;             //pin zab. ustawienia (srv)
    this.set_pin2=0;            //pin rezerwa ((srv)
    this.set_pin3=0;            //pin rezerwa ((srv)

    this.lang_use=false;        // lang y/n   from srv - potwierdza możliwość tłumaczenia
    this.lang_on=false;  // tlumacz = uwzględnia lokalne ustawienie
    this.lang_local_set=false;  // lang y/n   from local storage
    this.lang_always=false;     // ignoruj ustawienie lokalne (srv)
    this.lang_ls_view=false;     //
    this.lang_prefix='PL';        // prefix jezyka (srv)


    this.BodyColor = '#fff';    // kolor sekcji body
    this.BodyPattern = '';      // path do pliku graficznego tla, jeśli różny od ''
    this.padding = 5;           // margnes kontenera content, header i footer
    this.top_button = true;     // zal. obsluge przycisku scroll top
    this.top_button_styl = 0;   // styl przycisku scroll top ?
    this.select_disable=true;

    this.cfg_info_from_server=function(callback ){

        $.ajax({
            'url':"nfw_si",
            'dataType':'json',
            'type':"GET",
            success: function(idata) {
                that.host_version = idata['ver'];
                that.lib_base_id_srv =idata['cver'];
                that.tzone= idata['tzone'];
                that.set_pin=idata['p1'];
                that.set_pin2=idata['p2'];
                that.set_pin3=idata['p3'];

                that.lang_use = idata['l_use'];
                that.lang_always = idata['l_all'];
                that.lang_prefix=idata['l_px'];

                if (that.lang_always) {
                    that.lang_on = that.lang_use;

                }else {
                    that.lang_on = that.lang_use && that.lang_local_set;
                    that.lang_ls_view = true;
                }
                if(!that.lang_use){  that.lang_ls_view = false;}

                if(that.lang_on){

                    for (var j = 0; j < 260; ++j) {
                        //lang[j] =    idata['l_sl'].split('^')[j]
                        if(idata['l_sl'].split('^')[j] !=''){ lang[j] =    idata['l_sl'].split('^')[j]   }
                    };


                }



                is_callback(callback);
            },
            error: function(){     }
        });
    };

    this.create_info_box=function(){

        var sx='system: '+this.host_version+  '<br>';
        sx+='server/framework: '+this.lib_base_id_srv+'/'+this.lib_base_id+'<br>';

        sx+='aplikacja: '+this.app_name+'<br>';
        sx+='<div  style="font-size:10px; margin: 0px;padding-left:5px" >'+  this.app_desc +'</div>';
        sx+='lang: '+this.lang_prefix+'<hr class="smlhr">';


        sx+='<div  style="font-size:10px; margin: 0px" >zoom: '+ detectZoom.zoom()+' dev: '+ detectZoom.device()+'<br>';
        sx+='w.width: '+ $(window).width() +' w.height:  '+ $(window).height()+'</div><br>';
        //sx+='<div class="nk-small" id="stateinfo">'+  nApp.app_description +'</div>'
        sx+='<button id="lockbutton" class="btn btn-silver" > LOCK </button>   ';
        sx+='<button id="reloadbutton" class="btn btn-silver" > Reload </button>  ';
        sx+='<button id="fullsbutton" class="btn btn-silver" > Full screen </button>  ';
        //sx+='<button id="stinfobutton" class="btn btn-silver" > Server </button>';

        if (this.help_url!='') {
            sx += '<br><button id="hpinfobutton" class="btn btn-yellow"  style="width: 200px;margin-top:5px"  > POMOC </button>';
        }
        $('#kit_status_bar_info_box_i').html(sx);
        $('#lockbutton').click(function() {   nApp.rft_lock_message(false) ;   } );
        $('#fullsbutton').click(function() {   nApp.toggleFullScreen()   } );
        $('#reloadbutton').click(function() {   location.reload()   } );
        //$('#stinfobutton').click(function() {  } );
        $('#hpinfobutton').click(function() {window.open(that.help_url , '_blank');  } );
    };



    this.toolBar_big=false;
    this.toolBar_ico_default='mdi-chevron-right';
    this.info_box_use=true;


    this.lbox_width=280;
    this.lbox_height='95%';
    this.lbox_use_head=false;
    this.lbox_head_styl=0;
    this.lbox_use_over=true;


    this.rbox_width=300;
    this.rbox_height='200';
    this.rbox_use_over=true;


    this.icon_left ='mdi-arrow-left-bold';
    this.icon_right='mdi-arrow-right-bold';

    // layout
    this.view_width=1000; // baza dla
    this.view_height=0;   // view make

    this.dialog_max_width=100;
    this.content_height=0;  //ustawiane w make
    this.content_width=0;  //ustawiane w make

    this.l_mode=''; //
    this.l_d_mode=0;// 0-340; 1-590; 2-1200
    this.l_d_width=340;

    this.wwidth = $(window).width();
    this.wheight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    this.winfo_str ='dev size: '+ this.wwidth + ' x ' + this.wheight + ' zoom: ' + detectZoom.zoom() + ' dev: ' + detectZoom.device();

    this.tablet_width= [590,950,1270];
    this.tablet_height=[990,560,750];
    this.tablet_break1=650;
    this.tablet_break2=1200;
    this.tablet_mode=0;

    this.setvsizepar=function(vw,vh,mode,dmode,dwidth){
        this.view_width =vw;
        this.view_height = vh;
        this.l_mode=mode;
        this.l_d_mode=dmode;
        this.l_d_width=dwidth;
    };

    this.setVsize=function(cw){


        if (cw.toLowerCase() == 'ph'){
            this.setvsizepar(350,this.wheight,'ph',0,340);
        } else
        if (cw.toLowerCase() == 'tv'){
            this.setvsizepar(1860,1060,'tv',2,1200 );
        } else
        if (cw.toLowerCase() == 'dt'){
            this.setvsizepar(750,1100,'dt',2,1200 );
        } else
        if (cw.toLowerCase() == 'fhd'){
            this.setvsizepar(1900,960,'fhd',2,1200)
        } else
        if (cw.toLowerCase() == 'tap'){
            this.setvsizepar(790,1000,'tap',2,1000)
        } else
        if (cw.toLowerCase() == 'pos'){
            this.setvsizepar(1000,750,'pos',2,900)
        } else

        if (cw.toLowerCase() == 'ta'){ // adaptywne

            var nr= 0, dm= 1, dw= 560;
            if (this.wwidth >this.tablet_break1){nr=1;    }
            if (this.wwidth >this.tablet_break2){nr=2;  dm=2; dw=1200  }

            this.setvsizepar( this.tablet_width[nr] , this.tablet_height[nr] ,'ta',dm,dw);
            this.tablet_mode=nr;

        }

        this.dialog_max_width=this.view_width-20;
        //console.log(this.view_width+'  '+this.view_height+'  info:'+this.winfo_str)

    };



    // table content dept
    this.tab_ctx=[];
    this.tab_ctx_use=false;
    this.tab_ctx_crr=0;
    this.tab_ctx_mh=0;
    this.tab_ctx_add=function(id){
        this.tab_ctx.push(id);
        this.tab_ctx_use=true;
        var nr=this.tab_ctx.length - 1;
        var ob=$(this.tab_ctx[nr]);
        ob.addClass('kit_view_content_box');

        if (nr>0){  ob.hide()  }

        $('#kit_view_container').css({'height': ob.height() +200 });
        $(this.tab_ctx[nr]).resize( function(){
            if (that.view_height==0  ){
                var h= ob.height();

                $('#kit_view_content').css({'min-height': 100  });

            }
        } )
    };

    this.tab_ctx_go=function(nr){
        if (this.tab_ctx_crr!=nr){
         var d1='left';
         var d2='right';
         if (nr==0){ d1='right'; d2='left'  }
            $(this.tab_ctx[ this.tab_ctx_crr ]).toggle('slide', {direction: d1}, 'fast') ;
            $(this.tab_ctx[ nr ]).toggle('slide', {direction: d2}, 'fast', function(){    } ) ;
              this.tab_ctx_crr=nr;
        }
    };

    // local storage
    this.sprefix=window.location.pathname.split('/').pop().replace('.html', '')+'_';
    this.fromLS=function(key,df){
        if (localStorage.getItem( this.sprefix+ key) === null) {
            return df
        }  else {
            var ret = localStorage.getItem(this.sprefix+key);
            if (ret=='false'){ ret=false }
            if (ret=='true'){ ret=true }
            return ret;
        }
    };

    this.toLS=function(key,v){  localStorage.setItem(  this.sprefix+key,  v  );   };
}



function Kit_view_constructor(){

    var that = this;
    this._lb='';
    this._rb='';
    this._tb='';
    this._tb_bcount=0;
    this._tb_scount=0;
    this._tb_height=30;
    this._tb_iclass='';
    this._bcount=0;

    this._elh=0;

    this._slb_overlay='';
    this._slb_overlay_set=false;

    this.Make=function(a){

        if ( nApp.cfgi.title==''  ){ nApp.cfgi.title=nApp.cfgi.app_name  }
        document.title= nApp.cfgi.title;
        if( nApp.cfgi.debug_mode  ){   document.title ='[D '+ktime.TimeStrNow()+'] '  + document.title  }

        //  tworzymy obszar VIEW
        var _th= '_'+nApp.cfgi.theme_style;

        this._lb=$('#kit_left_slide_box');
        this._rb=$('#kit_right_slide_box');

        this._lb.css('left',-1000).hide();
        this._rb.hide();

        var kv=$('#kit_view_container');
        kv.addClass('kit_view_container');
        kv.prepend( '<div id="fixed_space" style="min-height:30px;display: none;  " ></div>' );
        kv.css({'width':  nApp.cfgi.view_width  });


        if (nApp.cfgi.BodyPattern==''){
            $('body').css('background-color', nApp.cfgi.BodyColor);
            $('html').css('background-color', nApp.cfgi.BodyColor);
        } else {
           // $('html').css('background', 'url('+nApp.cfgi.BodyPattern+')' );
            $('body').css('background', 'url('+nApp.cfgi.BodyPattern+')' );
        }


        // content
        var kc=$('#kit_view_content');
        kc.addClass('kit_view_content').addClass('kit_view_content'+_th ) .addClass('xyarea') ;

        // status bar
        kv.prepend('<div id="kit_status_bar_container" class="w3-bar shadow-2  kit_status_bar" >1122333</div>');
        var sb=$('#kit_status_bar_container' );
        var s='';
        s+='<i class="mdi i24 mdi-crosshairs-gps" id="masericx"></i><div  style="display: inline; font-size: 16px; padding-left: 6px" >'+nApp.cfgi.app_name +'</div>';
        s+='<i class="mdi i24 mdi-settings kit_status_bar_btn pointer  w3-right " id="MasterSetup" ></i>';
        s+='<img id="status_bar_infoc" class="w3-right" style="padding-left: 10px; padding-right: 10px; padding-top: 3px"  src="../_fw/i_lg.png">';
        s+='<div class="w3-right kit_status_bar_ajax_status" id="status_bar_ajax">1,7/2,0s.</div>';
        s+='<img  class="w3-right" style="padding-top: 3px; padding-right: 5px; " src="../_fw/i_ajax-loader.gif" id="ajax_load_ico">';
        s+='';

        sb.html(s);
        this._elh= sb.outerHeight() +5;

        //infobox
        if (nApp.cfgi.info_box_use==true){
            $( ".kit_view_container" ).prepend( '<div class="info_box shadow-1"  id="kit_status_bar_info_box" ><div class="info_box_i" id="kit_status_bar_info_box_i"></div></div>' );
            var ibx=$('#kit_status_bar_info_box');
            var udi=$('#status_bar_infoc, #kit_status_bar_info_box');

            if (detectmobile()){
                udi.click( function(e){
                    e.stopPropagation();
                    e.preventDefault();
                    var yp = sb.height() +  $(window).scrollTop();
                    ibx.css({right: sb.offset().left, top: yp});
                    ibx.stop().slideToggle(20);
                }  )

            } else {

                udi.on('mouseenter mouseleave  ', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                    var yp = sb.height() + $(window).scrollTop();
                    ibx.css({right: sb.offset().left, top: yp});
                    ibx.stop().slideToggle(200);
                });
            }
        }

        // toolbar
        if (id_exists( '#kit_toolbar' )==true) {
            if (nApp.cfgi.toolBar_big){ this._tb_height=50; this._tb_iclass='i20'   }  else { this._tb_height=30; this._tb_iclass='i17' }
            this._tb=$('#kit_toolbar');
            this._tb.css('min-height', this._tb_height).addClass('nfw_toolbar_'+ nApp.cfgi.theme_style ) ;
            this._elh=this._elh+ this._tb.outerHeight() ;
        }

        // header
        if (id_exists( '#kit_view_header' )==true) {
        var kh=$('#kit_view_header');
        kh.addClass( 'kit_view_header kit_view_header'+_th );
            this._elh=this._elh+kh.outerHeight();

        }

        // footer
        if (id_exists( '#kit_view_footer' )==true) {
        var kf=$('#kit_view_footer');
        kf.addClass( 'kit_view_footer' );
        kf.find("#kit_view_footer_i").text( nApp.cfgi.footer_info );
        kf.find("#kit_view_footer_id").text( nApp.cfgi.lib_base_id_srv+'/'+nApp.cfgi.lib_base_id );

            this._elh=this._elh+kf.outerHeight();
        }

        // kalkulacja wysokosci

        if (nApp.cfgi.view_height !==0) {
            kv.css({'min-height': nApp.cfgi.view_height });
            kc.css({'min-height': nApp.cfgi.view_height -this._elh   });
        }
        nApp.cfgi.content_height = kc.innerHeight();
        nApp.cfgi.content_width = kc.innerWidth();

        // button scroll top
        if ( nApp.cfgi.top_button==true ){
            $('body').append('<div id="button_top" class="kit_button_top w3-btn w3-circle w3-black " ><i class="mdi i40 mdi-arrow-up-bold" ></i></div>') ;

            $(document).scroll(function () {     $('#button_top').toggle( $(document).scrollTop() > 100 )         });
            $("#button_top").click(function() {   $("html, body").animate({ scrollTop: 0 }, "fast");    return false;    });
        }
        // left box
        this._lb.addClass( 'kit_left_slide_box').addClass( 'kit_left_slide_box'+'_'+nApp.cfgi.theme_style ).css({'width':nApp.cfgi.lbox_width,'height':nApp.cfgi.lbox_height  });
        // right e box
        this._rb.addClass( 'kit_right_slide_box').addClass( 'kit_right_slide_box'+'_'+nApp.cfgi.theme_style ).css({'width':nApp.cfgi.rbox_width,'height':nApp.cfgi.rbox_height  });
    };

    this.left_box_toggle=function(){
        var that = this;
        var lx=parseFloat(this._lb.css('left'));
        if  ( lx<0) { this._lb.hide();  this._lb.css('left',0);  }

        this._lb.toggle("slide",{}, 200 , function(){
            that.left_box_ico_set();
        } );
    };
    this.left_box_visible=function(){ return this._lb.is(':visible') && parseFloat(this._lb.css('left'))==0  };
    this.left_box_slide=function(b_show){
        var that = this;
        if (b_show){ if (!that.left_box_visible() ){ that.left_box_toggle() }
        } else  {    if (that.left_box_visible() ){ that.left_box_toggle() }}
    };
    this.left_box_ico_set=function( ){
        var lbi=$('.lc_ico');
        if (!this.left_box_visible()){

            lbi.removeClass(nApp.cfgi.icon_left).addClass(nApp.cfgi.icon_right);
            if(nApp.cfgi.lbox_use_over){
            if(this._slb_overlay_set) {
                this._slb_overlay.detach();
                this._slb_overlay_set=false;
                $('.lc_ico').parent().css('z-index',60);
            }
            }

        }  else {

            lbi.removeClass(nApp.cfgi.icon_right).addClass(nApp.cfgi.icon_left);
            if(nApp.cfgi.lbox_use_over) {
                this._slb_overlay = _create_overlay('', 70);
                this._slb_overlay_set = true;
                lbi.parent().css('position', 'relative').css('z-index', 80);
            }
        }
    };

    this.right_box_visible=function(){ return this._rb.is(':visible')  };
    this.right_box_toggle=function(){
        var that = this;
        this._rb.toggle("slide",{ direction: "right" }, 200 , function(){   that.right_box_ico_set();  } );
    };
    this.right_box_slide=function(b_show){
        var that = this;
        if (b_show){ if (!that.right_box_visible() ){ that.right_box_toggle() }
        } else  {    if (that.right_box_visible() ){ that.right_box_toggle() }}
    };
    this.right_box_ico_set=function( ){
        var rbi=$('.rc_ico');
        if (!this.right_box_visible()){
            rbi.removeClass(nApp.cfgi.icon_right).addClass(nApp.cfgi.icon_left)
            if(this._slb_overlay_set) {
                this._slb_overlay.detach();
                this._slb_overlay_set=false };
                $('.rc_ico').parent().css('z-index',60);
        }
        else {
            rbi.removeClass(nApp.cfgi.icon_left).addClass(nApp.cfgi.icon_right);

            this._slb_overlay = _create_overlay('', 70);
            this._slb_overlay_set=true;
            rbi.parent().css('position','relative').css('z-index',80);
        }
    };

    this.ajax_icon_state= function(st){ if ( st ==false) { $("#ajax_load_ico").hide() } else ( $("#ajax_load_ico").show() ) };
    this.ajax_txt=function(c){ $('#status_bar_ajax').text(c);    };
    this.status_bar_color=function(color){
        if (color==''){color='#4C4C4C'}
        $( '#kit_status_bar_container').css('background-color',color)
    };

    // toolbar
    this.tb_addBtn=function(rght,cls,ico,caption,cmd,par){
        this._bcount++;
        var idx='tb_id'+this._bcount;
        var icox= nApp.cfgi.toolBar_ico_default ;
        if (ico!=''){icox=ico  }

        var s='<button   id="'+idx+'"  class="btn ';
        if (cls!=''){  s=s+cls }
        s=s+'"';
        if (rght) {  s=s+' style="float: right;"'} else { s=s+' style="float: left;"' }
        s=s+'>';
        s+=htmlts.ico( this._tb_iclass , icox )+' '+caption+' </button>';
        this._tb.append(s);

        var mo=$('#'+idx);
        mo.css('margin',0).css('min-height', this._tb_height );

        BindClick(mo, function (event){
            nAction(cmd,par)
        });

        if (ico='lc_ico'){ that.left_box_ico_set() }
        if (ico='rc_ico'){ that.right_box_ico_set() }

    };
    this.tb_addSeparator=function(width){
        this._tb.append('<div   style="display:inline-block; min-width:'+width+'px; float: left; min-height:'+this._tb_height+'px;" ></div>'  );
    };
    this.tb_addSeparatorR=function(width){
        this._tb.append('<div   style="display:inline-block; float: right; min-width:'+width+'px; min-height:'+this._tb_height+'px;" ></div>'  );
    };
    this.tb_addContainer=function(width,idx,ri){
        var s='float: left;';
        if (ri){s='float: right;'}
        this._tb.append('<div id="'+idx+'"  style="display:inline-block; '+s+' min-height:'+this._tb_height+'px; width:'+width+'px " >kontener</div>'  );
    }
}



function NApp_constructor(){

    var that = this;
    this.timer_run=false;
    this._tim_count=0;
    this._tim_count_s=0;
    this._tim04_count=0;

    this._rft_mode=0; // 0- not use; 1-normal; 2-fast test; 3- slow test; 4-lock
    this._rft_interval=20;
    this._rft_old_blow=false;
    this._rft_timer_count=0;
    this._rft_error_count=0;
    this._rft_fast_test_count=0;
    this._rft_first_error=false;
    this._rft_first_connect=false;
    this._rtf_after_error_lock =4;

    this.log=function( s,dt  ){
       if (nApp.cfgi.debug_mode){
        var sx=s;
        if(dt){ s=ktime.TimeStrNow()+'>>'+s  }
        console.log(s)
       }
    };

    this.goEvent=function(nr,arg){
        $.event.trigger('napptriger' ,[nr,arg]);
        if (nr>90){  that.log('goEvent:'+nr, nApp.cfgi.debug_mode_event_time )}


    }; //rozsyla powiadomienia do innych modulow
    /*
    Komunikaty systemowe
     1 - 60/500ms Canvas  arg: licznik 0-9
     2 - 100ms system  arg: licznik 0-9
     9 - blow
     10 - refresh timer
     11 - data_ok
     // komunikaty aplikacji > 100
     */

    this.BindEvent= function(  call, bc ){ //linkuje powiadomienia
        var s='';
        if (bc!==undefined){ s='.'+bc }
        $( document).on ( 'napptriger'+s , call );
    };

    this.unBindEvent=function(bc){
        $(document).unbind("napptriger."+bc );
    };

    this.cfgi= new NAppCfgInfo_constructor();
    this.view= new Kit_view_constructor() ;
    this.auth= new NApp_auth_constructor();

    this._ajax_blow=function(){
        $.ajax({
            'url':"test_blow",
            'dataType':'text',
            'type':"GET",
            data: '',
            success: function() {
                that._rft_old_blow =true;
                that.goEvent(9,0);
                that.goEvent(10,0);

            },
            error: function(){   }

        });
    };
    this._rft_data_refresh=function(){
        if ( that._rft_old_blow  ==true) {    that.goEvent(10,0);  }
        else {  //BLOW
            that._ajax_blow();
        }
    };

    this._rft_recalc=function(){
        if ( that._rft_mode==1 ){  that._rft_interval= nApp.cfgi.rf_timer_speed*  10  ;}
    };

    this._rft_errdisplay=function(aserr){
        if(aserr){
            if ( this._rft_first_error ==false  ){
                this._rft_first_error=true;
                this._rft_first_connect=false;
                kit_note_ex (  'ERROR !!!!!!! ','',4,5 );
                nApp.view.status_bar_color('red')
            }
        }else{
            if (  this._rft_first_connect==false  ){
                this._rft_first_connect=true;
                kit_note_ex( 'CONNECT', '',4,4 );
                nApp.view.status_bar_color('')
            }
        }
    };

    this._rft_error=function(){

        //kit_note('terr '+that._rft_mode)

        that._rft_old_blow=false;

        if ( that._rft_mode==1 ){
               that._rft_mode=2;
               that._rft_interval=40;

        }else if(that._rft_mode==2 ){
            that._rft_fast_test_count++;
            that._rft_interval=30;
            if ( that._rft_fast_test_count>3 ){
                that._rft_mode=3;
                that._rft_interval=300;
                that._rft_errdisplay(true);
            }
        }else if(that._rft_mode==3 ){
            that._rft_fast_test_count=0;
            if (this.cfgi.rf_timer_lock ){
                that._rft_error_count++;
                if (this._rft_error_count > this._rtf_after_error_lock) {
                    //that._rft_mode=4;
                    this.rft_lock_message(true);
                }else    that._rft_mode=2;

            } else    that._rft_mode=2;
        }

    };

    this._rft_dok=function(){
        that._rft_interval=30;
        that._rft_first_error=false;
        that._rft_mode=1;
        that._rft_errdisplay(false);
        that._rft_error_count=0;
    };

    this._rft_status_info=function(){
        var sx=['','','F ','S ','L '];
           if ( nApp.cfgi.rf_timer_use ) {
                 nApp.view.ajax_txt(sx[this._rft_mode]+ ktime.dSecToSec(this._rft_timer_count) + '/' + this._rft_interval/10 + 's.');
        } else { nApp.view.ajax_txt('manual'); }
    };
    this.rft_lock_message=function(as_error){

        if ( that._rft_mode!=4 ){
            var btitle='LOCK';
            var bbody='<h4>'+lang[12]+'</h4> ';
            if (as_error==true){
                btitle='ERROR';
                bbody='<h4>'+lang[13]+'</h4><br><br>'+lang[14]+'  '+ktime.TimeStrNow();
            }
            that._rft_mode=4;

            kit_dialog_alarm(400,260,btitle,bbody,
                function(){
                    that._rft_dok();
                },'Połącz'
            );
        }
    };

    this.timerstart=function(){

        // timer dla CANVAS

        var fast=nApp.cfgi.theme_style==2;
        var incrementPeriod = 200;
        var lastTime;
        if (fast){ incrementPeriod=60 }

        function _timedCountLoop(){
            var now = Date.now;
            var delta = now - lastTime;
            lastTime = now;
            that._tim_count++;
            if (that._tim_count==9){   that._tim_count=0;   }
            canvas_flash.animeclock();
            that.goEvent(1,that._tim_count);
            setTimeout(function(){  _timedCountLoop()  }, incrementPeriod);
        }

        $.ajaxSetup({
            timeout: 5000
        });


        // systemowy timer 0,1 sec
        if (nApp.cfgi.rf_timer_use) { this._rft_mode=1    }
        setInterval(function(){
            that._tim_count_s++;
            if (that._tim_count_s==9){   that._tim_count_s=0; canvas_flash.clock1s();  }
            that.goEvent(2,that._tim_count_s);

            if (nApp.cfgi.rf_timer_use) {    // Timer data refresh

              if (that._rft_mode!=4){
               that._rft_recalc();
               that._rft_timer_count++;
               if (  that._rft_timer_count >  that._rft_interval ){
                   that._rft_timer_count =0;
                   that._rft_data_refresh();
               }
              }
               that._rft_status_info();
           }//end rt

        }, 100);
        _timedCountLoop();

        this.timer_run=true;
    };
    this.core_rtimer_reset=function(){
        that.goEvent(10,0);
        that._rft_timer_count=0;
    };
    this.core_rtimer_reset_ne=function(){
        that._rft_timer_count=0;
    };

    this.AjaxHandle=function(){
        $(document).ajaxStart(function() {
            $("#ajax_load_ico").show();
        });

        $(document).ajaxStop(function() {
            $("#ajax_load_ico").hide();
        });

        $( document ).ajaxSuccess(function( event, request, settings ) {
            that._rft_dok();
            that.goEvent(11,0);
            //console.log('ajaxh');
        });
        $( document ).ajaxError(function( event, request, settings ) {
            that._rft_error();
            if (!nApp.cfgi.rf_timer_use) { that._rft_errdisplay(true)  }
        });
    };


    this.toggleFullScreen=function() {
        var doc = window.document;
        var docEl = doc.documentElement;
        var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
        var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
        if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
            requestFullScreen.call(docEl);
        }
        else { cancelFullScreen.call(doc);   }
    };

}



//****************************************************************************
//  AUTORYZACJA
//****************************************************************************


function NApp_auth_constructor() {
    var that = this;
    this.is_auth=false;
        this.lstorage=true;
        this.use_timer=false;
        this.id=0;
        this.sid=0;
        this.user='';
        this.key=0;
        this.use_pin=true;
        this.uprs='00000000000000000000000000000000';
        this.pprofil=-1;
        this.pprofil_s=true;

        this.log_time=20;
        this.log_time2=200;
        this.long_time=false;
        this._timer='';
        this._timerc=0;

        this.auth_call=function(uid){};


    this.make_user_panel=function(){
      var s='<button id="nfw-user-btn" class="btn btn-red btnc" style="background: #4caf50;margin:1px;width:50px;height:48px;"><i class="mdi i24 mdi-lock-outline"></i></button>';
        s+='<div id="nfw-user-display" class="user_display">-- --</div>';
        s+='<div id="nfw-user-timer" class="user_timer">-- --</div>';

      $('#nfw-user-container').css('background-color','black').css('position','relative').html(s);

    };

    this.init=function(){  // metoda inicjuje pole wołana w init frameworku MES
        if (!this.use_timer) {$('#nfw-user-timer').hide()}
        this.btn_off();

        $('#nfw-user-btn').click(  function(){
            if(that.id!=0){that.logout( ); that.auth_call(0)   }else{ that.long_time=true;  that.login( function(){ that.auth_call(1) }  ) }
        });


        if(this.lstorage){

        if (sessionStorage.getItem("au_id") !== null) {

            that.is_auth=true;
            that.id =    sessionStorage.getItem('au_id');
            that.user =  sessionStorage.getItem('au_user');
            that.key=    sessionStorage.getItem('au_key');
            that.pprofil=sessionStorage.getItem('au_prof');
            that.uprs =  sessionStorage.getItem('au_uprs');
            that.btn_on();
        } else {
            that.is_auth=false;
            that.user='';
            that.id=0;
            that.uprs='00000000000000000000000000000000';
            that.pprofil=-1;
        }
        }
        if (this.use_timer) { this.timer_start() }
        this.display();


    };

    this.display=function(){
        var u='-- --';
        if (this.user!=''){u=this.user }
        $('#nfw-user-display').html(  u ) ;
        $('#nfw-user-timer').html(  ktime.TimeMS( this._timerc )) ;
    };
    this.nop=function(){ kit_note(lang[21]) };
    this.btn_on=function(){
        $('#nfw-user-btn').html('<i class="mdi i24 mdi-lock-open-outline"   >').css('background','red').css('border-color','black');
        if (this.use_timer) { $('#nfw-user-timer').show() }
    };
    this.btn_off=function(){
        $('#nfw-user-btn').html('<i class="mdi i24 mdi-lock-outline"   >').css('background','#4caf50').css('border-color','black');
        $('#nfw-user-timer').hide();

    };

    this.logout=function(){
        sessionStorage.clear();
        this.is_auth=false;
        this.user='';
        this.id=0;
        this.uprs='00000000000000000000000000000000';
        this.pprofil=-1;
        this.long_time=false;
        this.btn_off();
        this.display();
        $('#nfw-user-timer').html(  ktime.TimeMS( '-- --' )) ;

    };


    this.loginU=function(nrup,call_ok){
      this.login( function(){
          if(that.get_perm(nrup)){ is_callback(call_ok);  } else { that.nop() }
      })
    };


    this.login=function(callback_ok){
        var that=this;
        if (this.is_auth){
          //  if (this.long_time){that._timerc= that.log_time2} else { that._timerc= that.log_time}
            is_callback(callback_ok);
        } else   {

            kit_dialog_passwordEx2(this.use_pin ,lang[19],
                function(psx){

                    var sdata={};
                    sdata['token']= window.btoa( psx  );

                    $.ajax({  'url':"nfw_login_a",  'dataType':'json', 'type':"GET",
                        data: JSON.stringify( sdata ),
                        success: function(jdata) {
                            that.id=jdata['id'];
                            if (that.id==0){
                                that.logout();
                                kit_note_ex(lang[20],lang[21],1,5 )
                            }
                            else {
                                that.is_auth=true;
                                that.user = jdata['user'];
                                that.key= jdata['key'];
                                that.pprofil=jdata['prof'];
                                that.uprs =jdata['uprs'];
                                if(that.lstorage) {
                                    sessionStorage.setItem('au_id', that.id);
                                    sessionStorage.setItem('au_user', that.user);
                                    sessionStorage.setItem('au_key', that.key);
                                    sessionStorage.setItem('au_prof', that.pprofil);
                                    sessionStorage.setItem('au_uprs', that.uprs);
                                }
                                that.display();
                                that.btn_on();
                                that.timer_go();
                                is_callback(callback_ok);
                            }
                            //nApp.core_data_ok();
                        },
                        error: function(){  that.logout();    }     });
                }
            )
        }
    };

    this.timer_go=function(){
        if(this.long_time){ that._timerc= that.log_time2;  } else {that._timerc= that.log_time; }
        this.long_time=false;
    };
    this.timer_start=function(){
        var that=this;
        this._timer = setInterval(function(){
            if ( $( ".mes_auth_marker" ).length ) {} else {
                if (that._timerc>0) {
                    that._timerc -= 1;
                    if(that._timerc ==0) { that.logout();  }
                    that.display();
                }
            }
        },1000 )
    };

    this.get_perm=function( nr){
        var b=that.uprs.charAt(nr)=='1';
        if ( this.pprofil==0 || this.pprofil==1  ){ b=true }
        if (this.id==0){ b=false }
        return b;
    }

}


// DATATABLE

function dataTableContainerCreate( dv,prop,styl,clist ){
    var tid=nohash(dv)+'_dt';

    //container
    if (styl==''){ styl='cell-border stripe '  }
    var s='<table id="'+nohash(tid)+'" class="'+styl+'" style="width:100%"><thead><tr>';
    for (var i=0; i < clist.length; i++) {   s += '<th>' + clist[i] + '</th>';     }
    s+='</tr> </thead> </table>';
    $(dv).html( s );

    // default property
    var prop_def={
        "language":{
            "search": "Szukaj:",
            "lengthMenu": "_MENU_ na stronę",
            "emptyTable":     "brak danych",
            "zeroRecords": "brak danych",
            "info": " _START_ do _END_ z _TOTAL_ rekordów",
            "infoEmpty": "brak danych",
            "infoFiltered": "",
            "paginate": {
                "first":      "First",
                "last":       "Prev",
                "next":       "Next",
                "previous":   "Prev."
            }
        },

        "lengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]]
    };

    var ob= $('#'+tid).DataTable(  jQuery.extend(prop_def,prop)  );
    return ob;
}


function nfw_ajax(url,sdata,call){
    $.ajax({
        'url':url,
        'dataType':'json',
        'type':"GET",
        data: JSON.stringify( sdata ),
        success: function(jdata) {
            call(jdata)
        },
        error: function(request, status, error){ kit_note('err '+request)    }
    });

}


//*********************
//  metody serwera STD
//*********************

function nfw_get_dict( typ,symbol,nazwa, callback ){

    function _ret(p1,p2){
        dm.aFree();
        is_callback( callback(  p1,  p2   ) )
    }


    function _gdata(){
        var sdata={};
        sdata['p1']= typ ;
        sdata['p2']= 0;
        nfw_ajax('nfw_getdict2',sdata, function(jdata) {
                var s='',sd='';
                $.each(jdata , function (i, item) {
                    s+='<tr>';
                    sd=(symbol)? sd='<b>['+jdata[i].r2+']</b> '+jdata[i].r1 : jdata[i].r1;
                    s+=dst.td(sd);
                    s+=dst.td(htmlts.btn_inline_wdata(jdata[i].r0,sd ,46,30,'OK','btn-blue dictcl'));
                    s+='</tr>';
                });
                dst.load(s);
                $('.dictcl').on( 'click touchstart', function (e) {
                    e.stopPropagation(); e.preventDefault();
                    _ret($(this).attr('data-button'),$(this).attr('id') )
                } );
            });
    }

    function _gdata2(){
        var sdata={};
        sdata['p1']= typ ;
        sdata['p2']= 0;
        $.ajax({
            'url':"nfw_getdict2",
            'dataType':'json',
            'type':"GET",
            data: JSON.stringify( sdata ),
            success: function(jdata) {
                var s='',sd='';
                $.each(jdata , function (i, item) {
                    s+='<tr>';
                    sd=(symbol)? sd='<b>['+jdata[i].r2+']</b> '+jdata[i].r1 : jdata[i].r1;
                    s+=dst.td(sd);
                    s+=dst.td(htmlts.btn_inline_wdata(jdata[i].r0,sd ,46,30,'OK','btn-blue dictcl'));
                    s+='</tr>';
                });
                dst.load(s);
                $('.dictcl').on( 'click touchstart', function (e) {
                    e.stopPropagation(); e.preventDefault();
                    _ret($(this).attr('data-button'),$(this).attr('id') )
                } );
            },
            error: function(){     }
        });
    }

    var dm = new Kit_dialog_constructor( 350, 500  ,1,0,true,true);
    dm.sall(nazwa,'<div id="dic_table"></div>',false);
    var dst = new Dataset_table_constructor('#dic_table',nApp.cfgi.theme_style);
    dst.colname=['nazwa','id'];
    dst.colwidth=[280,60];
    dst.height= 330;
    dst.make();
    _gdata()

}


function nfw_fotobase_to_img(img,id,callback){
    var url='../_fw/ni_image.png ';
    if(id!=0){ url='nfw_fotobase?idf='+id;}
    $(img).attr('src', url).load(function(){ is_callback(callback) ; $(img).off('load')  });
    $(img ).css( "cursor", "zoom-in" )
}

function nfw_fotobase_zoom(img,w,h){
    $(img).off().click( function(){

        var dm = new Kit_dialog_constructor( w, h  ,1,0,true,true);
        dm.draw();
        dm.addHeader('view');
        var s='<div id="view1234container" style="width: 100%;height:'+(h-100)+'px;overflow-y: auto;overflow-x: auto " >';
        s+='<img src="" id="view1234" style="width:auto;height:auto;display: block; "></div>';
        dm.content(s,false  );
        dm.showDialog(0);
        $('#view1234').attr('src', $(img).attr('src'));



    }  )
}

