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


function numFC(nx) {
    var x = nx.toFixed(2).replace(/\.00$/, '');
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    return parts.join(".");
}

function numFCC(nx) {
    var x = nx.toFixed(0).replace(/\.00$/, '');
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    return parts.join(".");
}

function myprc(c,v){
    if (c==0){
        return 0;
    }else {
        return (v*100)/c;
    }
}

function IsNumeric(input)
{
    return (input - 0) == input && (''+input).trim().length > 0;
}

function specLowerCase(s){
    if ( IsNumeric(s) ) { return s } else {  return s.toLowerCase() }
}


function br2cr(s){
    var regex = /<br\s*[\/]?>/gi;
    return s.replace(regex, "\n");
}


// element ID istnieje
function id_exists(id){ if($(id).length != 0) { return true } }

// usowa # z nazwy ID
function  nohash(id){  return id.replace("#" , "" ) }

function detectmobile() {
    if( navigator.userAgent.match(/Android/i)
        || navigator.userAgent.match(/webOS/i)
        || navigator.userAgent.match(/iPhone/i)
        || navigator.userAgent.match(/iPad/i)
        || navigator.userAgent.match(/iPod/i)
        || navigator.userAgent.match(/BlackBerry/i)
        || navigator.userAgent.match(/Windows Phone/i)
    ){
        return true;
    }
    else {
        return false;
    }
}
// dodaje padding do div
function kf_div_wrap(dv,pad){   $( dv ).wrapInner( "<div style='padding:"+pad+"px'></div>" ); }
// dodaje przed div z parametrami
function kf_add_before( aParent, aID, aTitle, aBody ){
    $(aParent).prepend('<div id='+aID+' >'+aBody +'</div>');
    var r=$('#'+aID);
    r.attr('Title',aTitle);
    return r;
}

// dodaje za div z parametrami
function kf_add_after( aParent, aID, aTitle, aBody ){
    $(aParent).append('<div id='+aID+' >'+aBody +'</div>');
    var r=$('#'+aID);
    r.attr('Title',aTitle);
    return r;
}

// sprawdza czy zmienna jest funkcja, jesli tak uruchamia ja
function is_callback(acall){       if (   typeof acall == 'function' ) {  acall() }    }

var clickEvent = (function() {
    if ('ontouchstart' in document.documentElement === true)
        return 'touchstart';
    else
        return 'click';
})();

function BindClick(dv,acall){
    $(dv).on(clickEvent, function(e){e.stopPropagation(); e.preventDefault(); is_callback(acall);  return this;    });

}
function VisibleEvent( acall ){
    window.document.addEventListener("visibilitychange", function(e) {
        if (window.document.visibilityState=='visible'){ is_callback(acall);  }
    });

}

function test_data(html,count,num){
  var s='';
    for(var i = 0; i < count; i++){
        if (num){s=s+i+' '+html} else {  s=s+html }
    }
  return s
}
function elipsis (text, limit){
    if (text.length > limit)
        return text.substring(0,limit) + '...';
    else
        return text;
};


function playAudioFile(file, repeatCount) {
    var audioElement = new Audio(file);
    function playSound() {
        return new Promise(function(resolve) {
            audioElement.currentTime = 0;
            audioElement.play();
            audioElement.addEventListener('ended', resolve);
        });
    }
    function playMultipleTimes(times) {
        var promise = Promise.resolve();
        for (var i = 0; i < times; i++) {
            promise = promise.then(function() {
                return playSound();
            });
        }
    }
    playMultipleTimes(repeatCount);
}


//************************* HtmltToStr ***

var htmlts ={

    btn:function(idx,x,y,w,h,caption,bclass){
        return '<button id="'+idx+'" class="btn '+bclass+'" style="min-height:'+h+'px; position: absolute;top:'+y+'px; left:'+x+'px; width:'+w+'px"  >'+caption+'</button>';
    },
    btn_d:function(data,x,y,w,h,caption,bclass){
        return '<button    data-button="'+data+'" class="btn '+bclass+'" style="min-height:'+h+'px; position: absolute;top:'+y+'px; left:'+x+'px; width:'+w+'px"  >'+caption+'</button>';
    },

    btn_did:function(idx,data,x,y,w,h,caption,bclass){
        return '<button id="'+idx+'"   data-button="'+data+'" class="btn '+bclass+'" style="min-height:'+h+'px; position: absolute;top:'+y+'px; left:'+x+'px; width:'+w+'px"  >'+caption+'</button>';
    },


    btn_inline:function(idx,w,h,caption,bclass){
        return '<button id="'+idx+'" class="btn '+bclass+'" style="min-height:'+h+'px;  width:'+w+'px"  >'+caption+'</button>';
    },
    btn_inline_d:function(idx,w,h,caption,bclass,disable){
        if(disable){
            return '<button  class="btndisabled" style="min-height:' + h + 'px;  width:' + w + 'px"  >' + caption + '</button>';
        }else {
            return '<button id="' + idx + '" class="btn ' + bclass + '" style="min-height:' + h + 'px;  width:' + w + 'px"  >' + caption + '</button>';
        }
    },

    btn_inline_wdata:function(idx,data,w,h,caption,bclass){
        return '<button data-button="'+data+'" id="'+idx+'" class="btn '+bclass+'" style="min-height:'+h+'px;  width:'+w+'px"  >'+caption+'</button>';
    },

    btn_inline_wdata2:function(idx,data,data2,w,h,caption,bclass){
        return '<button data-button="'+data+'" data-button2="'+data2+'" id="'+idx+'" class="btn '+bclass+'" style="min-height:'+h+'px;  width:'+w+'px"  >'+caption+'</button>';
    },



    div_btn:function(data,x,y,w,h,bclass){
        return '<div    data-button="'+data+'" class="'+bclass+'" style="min-height:'+h+'px; position: absolute;top:'+y+'px; left:'+x+'px; width:'+w+'px; cursor: pointer"  ></div>';
    },

    div_ind:function(idx,x,y,w,h,color){
        return '<div  id="'+idx+'"  style="min-height:'+h+'px; position: absolute;top:'+y+'px; left:'+x+'px; min-width:'+w+'px; background-color:'+color+'"  ></div></div>';
    },

    spinner:function(id){ return '<input id="'+id+'" >' },

    input:function(id,width,cls){ return '<input autocomplete="off" id="'+id+'"  class="'+cls+'"  style="width: '+width+'px"    >' },

    select:function( id,options ){    return '<select id="'+id+'" style="height: 30px"  >'+options+' </select>';    },

    options:function(list){
        var arr=list.split(',');
        var s='';
        for (var i = 0; i < arr.length; i++) {    s+='<option>'+arr[i]+'</option>';   }
        return s;
    },
    options_l:function(arr){

        var s='';
        for (var i = 0; i < arr.length; i++) {    s+='<option>'+ lang[ arr[i] ]+'</option>';   }
        return s;
    },
    check:function(id, checked){
        var s='';
        if (checked==true ){s='checked="checked"'}
        return   '<input class="w3-check" type="checkbox" id="'+id+'" '+s+'>';

    },

    checkl:function(id,caption){
      return   '<input class="w3-check" type="checkbox" '+this._id(id)+' > <label>'+caption+'</label>';

    },
    checklxy:function(x,y,id,caption){
        return   '<input class="w3-check" type="checkbox" '+this._id(id)+' style=" position: absolute;top:'+y+'px; left:'+x+'px; "  > <label style=" position: absolute;top:'+(y+10)+'px; left:'+(x+30)+'px; " >'+caption+'</label>';

    },
    ico:function(size, ico,baseClass,id ){
        var s='',sc='';
        //if (id){ s='ID="'+id+'"'}
        s=this._id(id);
        sc=this._class(baseClass)
        if (size==''){size='iii'}
        return '<i '+s+' class="mdi '+size+' '+ico+' '+sc+'"></i>';
    },
    _id:function(id){
        var s='';
        if ( id!='' && id!=undefined ) { s= 'ID="'+id+'"' }

        return  s
    },
    _class:function(cl){
        var s='';
        if ( cl!='' && cl!=undefined ) { s= 'class="'+id+'"' }

        return  s
    },
   aaa:true

};

var htmlcmp={


    spinner:function (sp,avalue,amin,amax ){
    var $container=$(sp);
    return  $container.spinner(
        {
            numberFormat: "n",
            max: amax,
            min: amin
        }
    ).spinner( "value", avalue ).width(50).blur(function () {
        var value1 = $container.val();
        if (value1 < amin)   {    $container.val(amin);      }
        if(isNaN(value1))    {    $container.val(amin);      }
        if (value1 > amax)   {    $container.val(amax);      }
    })
   },

    getCheck:function(id){ return $(id).is(":checked")
    },
    setCheck:function(id,state){ $(id).prop( "checked", state )

    },

    getCombo:function(id){
          try{  return $(id)[0].selectedIndex     }catch (catchID) {  }
    },
    setCombo:function(id,val){
          try{   return $(id).get(0).selectedIndex = val  }catch (catchID) {  }
    },

    aaa:false
};



//****************************************************************************
//  JQUERY EXTEND i prototypy ob
//****************************************************************************


// umieszcza obiekt na wskazanych koordynatach
$.fn.pxyz= function(x,y,z){
    return this.each(function() {
        var xob=$(this);
        xob.css({  'position': 'absolute', 'left': x,  'top': y    });
        if (z){ xob.css( 'z-index',z  )  }
        return xob;
    });};

// centruje obiekt wzgledem ekranu
jQuery.fn.center = function () {

    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
    return this;
};
jQuery.fn.centerTop = function (offset) {
    this.css("top", Math.max(0, offset + $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px");
    return this;
};


// ustala wymiary obiektu
jQuery.fn.setsize = function ( aWidth,aHeight) {
    this.width( aWidth ) ;
    this.height(aHeight) ;
    return this;
};


String.prototype.replaceAll = function (searchStr, replaceStr) {
    var str = this;

    searchStr = searchStr.replace (/[-\/\\^$*+?.()|[\]{}]/g,'\\$&');

    return str.replace (new RegExp (searchStr, 'gi'), replaceStr);
};


//****************************************************************************
//  Czas
//****************************************************************************

var ktime={
    TimeStr: function (aTime){
        var hours = aTime.getHours();
        var minutes = aTime.getMinutes();
        var seconds = aTime.getSeconds();
        return ( hours < 10 ? "0" : "" ) + hours + ':' + ( minutes < 10 ? "0" : "" ) + minutes + ':' + ( seconds < 10 ? "0" : "" ) + seconds;
    },
    DateStr: function(aDate){
        // return  (aDate.getDate() + '-' + (aDate.getMonth()+1) + '-' + aDate.getFullYear() );
        return ( aDate.getFullYear()+'-'+ (aDate.getMonth()+1 < 10 ? "0" : "" )+(aDate.getMonth()+1)+'-'+( aDate.getDate() < 10 ? "0" : "" )+aDate.getDate()    );
    },
    DateTimeStr: function(DT){
        return this.DateStr(DT)+'  '+this.TimeStr(DT);
    },
    TimeStrNow:function(){
        var nd=new Date();
        return this.TimeStr(nd);
    },
    dSecToSec: function(ds){
        var sec=Math.floor( ds / 10);
        var ssec= ds - sec *10;
        return sec+','+ssec;
    },
    SecToGMS:  function(sec_num) { // zamienia ilosc sekund na GG:MM:SS
        var hours   = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);
        if (hours   < 10) {hours   = "0"+hours;}
        if (minutes < 10) {minutes = "0"+minutes;}
        if (seconds < 10) {seconds = "0"+seconds;}
        var stime    = hours+':'+minutes+':'+seconds;
        return stime;
    },
    SecToDhms:function (seconds) {
    seconds = Number(seconds);
    if(seconds>0){
    var d = Math.floor(seconds / (3600*24));
    var h = Math.floor(seconds % (3600*24) / 3600);
    var m = Math.floor(seconds % 3600 / 60);
    var s = Math.floor(seconds % 60);
    var dDisplay = d > 0 ? d + (d == 1 ? "D " : "D ") : "";
    var hDisplay = h; if (h<10){ hDisplay = '0'+hDisplay  }
    var mDisplay = m ;if (m<10){ mDisplay = '0'+mDisplay  }
    var sDisplay = s ;if (s<10){ sDisplay = '0'+sDisplay  }

    return dDisplay + hDisplay +':'+ mDisplay +':'+ sDisplay;
    } else { return '-- -- --'  }
},

 TimeMS:function(sec){
     sec = Number(sec);
     var minutes = Math.floor(sec  / 60 );
     var seconds = sec -  (minutes * 60);

     if (minutes>120){ return this.SecToDhms(sec) }
     else{
     if (minutes>0) { return minutes+'m '+seconds+'s';  } else { return seconds+'s';}
     }

 },

    UnixStr:function  (timestamp)
    {
        var date = new Date(timestamp * 1000);
        var year = date.getUTCFullYear();
        var month = date.getUTCMonth() + 1;
        var day = date.getUTCDate();
        var hours = date.getUTCHours();
        var minutes = date.getUTCMinutes();
        var seconds = date.getUTCSeconds();

        month = (month < 10) ? '0' + month : month;
        day = (day < 10) ? '0' + day : day;
        hours = (hours < 10) ? '0' + hours : hours;
        minutes = (minutes < 10) ? '0' + minutes : minutes;
        seconds = (seconds < 10) ? '0' + seconds: seconds;

        return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes+':'+seconds;
    },

    UnixToDate:function(timestamp){
        var date = new Date(timestamp * 1000);
        var year = date.getUTCFullYear();
        var month = date.getUTCMonth();
        var day = date.getUTCDate();
        var hours = date.getUTCHours();
        var minutes = date.getUTCMinutes();
        var seconds = date.getUTCSeconds();
        return new Date( year,month, day,hours,minutes,seconds,0    )
    },

    SecBetwenn:function(dtfrom,dtto ){
        return parseInt( (dtto.getTime() - dtfrom.getTime()) / 1000);
    },

    SecFromNow:function(dt){
      var endDate   = new Date();
        return this.SecBetwenn(dt,endDate);
    },

    a:11

};

function  DTTimer_constructor(){
    this.t1=new Date();
    this.run=false;
    this.paused=false;
    this.paused_sec=0;

    this.start=function(){
        this.t1=new Date();
        this.run=true;
    };
    this.stop=function(){
        this.t1=new Date();
        this.run=false;
    };
    this.sec=function(){
        return ktime.SecFromNow(this.t1);
    };
    this.SecToGMS=function(){
     return   ktime.SecToGMS( ktime.SecFromNow(this.t1)  );
    };
    this.TimeMS=function(){
        //return this.run ? ktime.TimeMS( ktime.SecFromNow(this.t1)  ) : '----';

        if (this.run){
            if(!this.paused) {
                return ktime.TimeMS(ktime.SecFromNow(this.t1));
            }else{ return ktime.TimeMS( this.paused_sec) }
        } else { return '----'}

    };
    this.datetime_t1= function(){
        return this.run ?   ktime.DateTimeStr( this.t1 ) : '----';
    };
    this.time_t1= function(){
        return  this.run ? ktime.TimeStr( this.t1 ) : '----';
    };

    this.setsec=function(sx){
        var t = new Date();
        t.setSeconds(t.getSeconds() - sx);
        this.t1=t;
    }

    this.pause=function(){
      if(!this.paused) {
          this.paused_sec = this.sec();
          this.paused = true;
      }
    };
    this.resume=function(){
        if(this.paused) {
            this.setsec(this.paused_sec)
            this.paused = false;
        }
    };

    // metody dodatkowe
    this.idx=0;
    this.dtsec=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
    this.todtsec=function(){
        this.dtsec[this.idx]=this.sec();
        ++this.idx;
    }


}


//****************************************************************************
//  CANVAS
//****************************************************************************

function  Canvas_flash_constructor(){
    this.f1s=false;
    this.ffast=false;
    this.fslow=false;
    this.anim_count=0;
    this.loop8=0;
    this.loop10=0;
    this.loop4=0;
    this.loop4s=0;
    this.aloop=[0,0,0,0,0,0,0,0,0,0];
    this.fxas=[0,0,0,0,0,0,0,0,0,0,0,0];
    this.fxaf=[0,0,0,0,0,0,0,0,0,0,0,0];
    this.fxat=[0,10,7,0,4,2,1,8,3,3,10,1];
    this.fxa1=[0,0,0,0,0,0,0,0,0,0,0,0];
    this._lp=0;

    this.clock1s=function(){
        this.f1s = !this.f1s;

        this._lp++;
        if (this._lp==2) {
            this._lp=0;
            this.fslow = !this.fslow;
        }

        var i=11;
        this.fxas[0]=Math.floor((Math.random() * 10) );
        while (i--) {   this.fxas.unshift(this.fxas.pop());   }
    };

    this.fxa_trig=function(){
        var i=11;
        this.fxat[0]=Math.floor((Math.random() * 10) );
        while (i--) {   this.fxat.unshift(this.fxat.pop());   }
    };

    this.animeclock=function(){
        this.ffast=!this.ffast;
        if (this.anim_count > 0){ this.anim_count--}

        var i=11;
        this.fxaf[0]=Math.floor((Math.random() * 10) );
        while (i--) {   this.fxaf.unshift(this.fxaf.pop());   }


        for (var j = 0; j < 10 ; ++j) {
            if ( this.aloop[j] >0) { this.aloop[j]-- }
        }
        this.loop10++;
        if (this.loop10 ==10){ this.loop10=0 };
        this.loop8++;
        if (this.loop8>7 ){ this.loop8=0  }
        this.loop4++;
        if (this.loop4>4 ){ this.loop4=0;   }
        if (this.ffast){
            this.loop4s++;
            if (this.loop4s>4 ){ this.loop4s=0  }
        }

    };
    this.clock01s=function(){

    };

    this.aVal2=function( x ){
        if (this.anim_count > 0){
            var prc= x / 10;
            return prc * (10 - this.anim_count) ;

        }else{return x}
    };
    this.aRes=function(nr){
        this.aloop[nr]=10;
    };
    this.aVal=function( nr, x ){
       if (nr==0){ return x  }

        if (this.aloop[nr] > 0){
            var prc= x / 10;
            return prc * (10 - this.aloop[nr]) ;

        }else{return x}
    }
}

var canvas_flash= new Canvas_flash_constructor();


function canvas_in_div(div,w,h,color){
    $('<canvas>').attr({  id: nohash( div)+'_cv'  }).css({
        width: w + 'px',
        height: h + 'px'
    }).appendTo(div);

    var cvv = document.getElementById(nohash(div)+'_cv');
    cvv.width=w;
    cvv.height=h;

    if (typeof color !== 'undefined') {
        $(div).css('background',color  )
    }

    return nohash(div)+'_cv';
}


function Canvas_css_constructor (styl){

    this.styl=styl;
    this.hud=styl==2;
    this._fc=['#34395e','#FBFBFB','#F0FEFE' ];  // font color   #FBFBFB
    this._fcoff=['gray','silver','silver' ];    // font color off
    this._fcmax=['#880015','#B4E051','#FFDF71' ];    // font wyrozniony
    this._bg=['#F9FAFC','#292929','#222222' ];  //background  #003F5F #2D3D88   #222222
    this._bl=['silver','#969696','#385769'];    // border line color

    this._wbg=['white','#3E3E3E','black' ];     //wizard background


    this._ac=['#E88A00','#FFF200','#FFF200'];    // akcent kolor
    this._bw=['black','white','white'];    // akcent kolor
    this._shadow=['blue','#FFFF4A','white'];    // akcent kolor
    this._slight=['#E4E4E4','#666666','#666666'];    // akcent kolor

    this._bgc2=['#D8DDEB','#4E4E4E','#223540'];
    this._bgc1=['#F1F3F8','#3B3B3B','#292929'];

    this._chc2=['#AAAAAA','#DFDFDF','#DFDFDF'];
    this._chc1=['#626262','#9A9A9A','#9A9A9A'];

    this._ry=['red','yellow','yellow'];
    this._green=['#059A14','lime','lime'];

    this._barc=['#00B900','#B5E61D','#B5E61D'];

    this.fc=function(){ return this._fc[styl] };
    this.fcoff=function(){ return this._fcoff[styl] };
    this.fcmax=function(){ return this._fcmax[styl] };
    this.bg=function(){ return this._bg[styl] };
    this.bl=function(){ return this._bl[styl] };


    this.wbg=function(){ return this._wbg[styl] };

    this.ac=function(){ return this._ac[styl] };
    this.bw=function(){ return this._bw[styl] };
    this.shadow=function(){ return this._shadow[styl] };
    this.slight=function(){ return this._slight[styl] };

    this.bgc1=function(){ return this._bgc1[styl] };
    this.bgc2=function(){ return this._bgc2[styl] };

    this.chc1=function(){ return this._chc1[styl] };
    this.chc2=function(){ return this._chc2[styl] };


    this.ry=function(){ return this._ry[styl] };
    this.green=function(){ return this._green[styl] };
    this.barc=function(){ return this._barc[styl] };
}


//***************  elementy graficzne ************************

// sterujące
Canvas_tool_constructor.prototype.setRect= function(x,y,w,h){  this.xx=x; this.yy=y; this.ww=w; this.hh=h;  };
Canvas_tool_constructor.prototype.alpha=function(a){  this.cv. globalAlpha = a  };
Canvas_tool_constructor.prototype.len=function(txt){     return this.cv.measureText(txt).width; };
Canvas_tool_constructor.prototype.degToRad=function(degree) {
    var factor = Math.PI/180;
    return degree*factor;
};
Canvas_tool_constructor.prototype.setBlur=function(color,depth,x,y){
    this.cv.shadowBlur = depth;
    this.cv.shadowColor =  color ;
    this.cv.shadowOffsetY=y;
    this.cv.shadowOffsetX=x;
};
Canvas_tool_constructor.prototype.resetBlur=function(){
    this.cv.shadowBlur = 0;
    this.cv.shadowOffsetY=0;
    this.cv.shadowOffsetX=0;
};

// figury i linie
Canvas_tool_constructor.prototype.frame=function(x,y,w,h,lw,color,colorf){
    this.cv.beginPath();
    this.strokeStyle(color,lw);
    this.cv.rect(x+0.5,y+0.5, w,h  );
    if (typeof colorf !== 'undefined') {
        if(colorf=='' ){ colorf=color };
        this.cv.fillStyle=colorf;
        this.cv.fill();
    }
    this.cv.stroke();
    this.xx=x; this.yy=y; this.ww=w; this.hh=h;
};

Canvas_tool_constructor.prototype.frame_rect=function(delta,lw,color,colorf){

    this.frame( this.xx-delta, this.yy-delta, this.ww+(2*delta), this.hh+(2*delta),lw,color,colorf)

};

Canvas_tool_constructor.prototype.box=function (x,y,w,h,color,alpha){
    if (typeof alpha !== 'undefined') {
        this.alpha(alpha)
    }
    this.cv.beginPath();
    this.cv.fillStyle = color;
    //this.cv.setLineDash([6]);
    this.cv.fillRect(x,y,w,h);
    this.xx=x; this.yy=y; this.ww=w; this.hh=h;
    //this.cv.closePath();
    if (typeof alpha !== 'undefined') {
        this.alpha(1)
    }
};

Canvas_tool_constructor.prototype.roundRect=function( x, y, width, height, radius,fill) {
    radius = {tl: radius, tr: radius, br: radius, bl: radius};


    this.cv.beginPath();
    this.cv.moveTo(x + radius.tl, y);
    this.cv.lineTo(x + width - radius.tr, y);
    this.cv.quadraticCurveTo(x + width, y, x + width, y + radius.tr);
    this.cv.lineTo(x + width, y + height - radius.br);
    this.cv.quadraticCurveTo(x + width, y + height, x + width - radius.br, y + height);
    this.cv.lineTo(x + radius.bl, y + height);
    this.cv.quadraticCurveTo(x, y + height, x, y + height - radius.bl);
    this.cv.lineTo(x, y + radius.tl);
    this.cv.quadraticCurveTo(x, y, x + radius.tl, y);
    this.cv.closePath();
    this.cv.stroke()
    if (fill) { this.cv.fill()}else{   }
};


Canvas_tool_constructor.prototype.circle=function(x,y,r,fcolor,lcolor,lwidth  ){
    this.cv.beginPath();
    this.cv.arc(x, y, r, 0, 2 * Math.PI, false);
    this.cv.fillStyle = fcolor;
    this.cv.fill();
    if (lwidth!=0){
     this.cv.lineWidth = lwidth;
     this.cv.strokeStyle = lcolor;
     this.cv.stroke();
    }
};

Canvas_tool_constructor.prototype.circle_l=function(x,y,r,color,lwidth  ){
    this.cv.beginPath();
    this.cv.arc(x, y, r, 0, 2 * Math.PI, false);
        this.cv.lineWidth = lwidth;
        this.cv.strokeStyle = color;
        this.cv.stroke();
};


Canvas_tool_constructor.prototype.lineH= function(x1, x2, y, lw, color) {
    this.cv.beginPath();
    this.strokeStyle(color,lw);
    this.cv.moveTo(x1+0.5, y+0.5);
    this.cv.lineTo(x2+0.5, y+0.5);
    this.cv.stroke();
};

Canvas_tool_constructor.prototype.lineV= function(x, y1, y2, lw, color) {
    this.cv.beginPath();
    this.strokeStyle(color,lw);
    this.cv.moveTo(x+0.5, y1+0.5);
    this.cv.lineTo(x+0.5, y2+0.5);
    this.cv.stroke();
};

Canvas_tool_constructor.prototype.pointXY=function(x,y,w,color,styl){
    var ax=x-(w/2);
    var ay=y-(w/2);
    this.box(ax,ay,w,w,color);
};
Canvas_tool_constructor.prototype.linkH=function(x1, x2, y, lw,w, color){
    this.lineH(x1,x2,y,lw,color);
    this.pointXY(x1,y,w,color,0);
    this.pointXY(x2,y,w,color,0);
};

Canvas_tool_constructor.prototype.romb=function(x,y,w,h,color){
    this.cv.beginPath();
    this.cv.fillStyle = color;
    this.cv.moveTo(x + w*0.3, y);
    this.cv.lineTo(x, y + h);
    this.cv.lineTo(x + w*0.7, y + h);
    this.cv.lineTo(x + w, y);
    this.cv.lineTo(x + w*0.3, y);
    this.cv.closePath();
    this.cv.fill()
};

Canvas_tool_constructor.prototype.romb_line=function(x,y,w,h,s,p, color){
    for (var j = 0; j < p ; ++j) {
        this.romb(x+(j*(w+s)),y,w ,h,color);
    }
};

// text

Canvas_tool_constructor.prototype.sFont=   function (size,color,bold){
    var s='';
    if (bold==true) {s=+'bold ' }
    s=+size+'px Arial';
    if (this.cv.font !=s){this.cv.font =s} //"  14px  Arial";
    if(this.cv.fillStyle !=color){   this.cv.fillStyle = color }
    this.cv.textBaseline = "top";
};

Canvas_tool_constructor.prototype.text= function(x,y,txt){  this.cv.fillText(txt,x,y); };
Canvas_tool_constructor.prototype.dtext=function(x,y,fs,fc,txt,align){
    this.sFont(fs,fc);
    if (align!=null){ this.cv.textAlign = align   }
    this.text(x,y,txt);
    if (align!=null){ this.cv.textAlign = 'start' }
};
Canvas_tool_constructor.prototype.dtextMw=function(x,y,fs,fc,txt,max){
    this.sFont(fs,fc);
    this.cv.fillText(txt,x,y,max);

};


Canvas_tool_constructor.prototype.textPar= function(x,y,ind,parname,parvalue,fs,fcp,fcv){
    this.sFont(fs,fcp);
    this.cv.fillText(parname,x,y);
    this.sFont(fs,fcv);
    this.cv.fillText(parvalue,x+ind,y);
};

Canvas_tool_constructor.prototype.textIco= function(x,y,txt,ico,fs,fc,fic){

    this.drawIco(x,y,ico,fs,fic);
    this.sFont(fs,fc);
    this.cv.fillText(txt,x+fs+4, y+(0.1*fs));

    this.xx=x+fs+4; this.yy=y+(0.1*fs);

};

Canvas_tool_constructor.prototype.number_float=function(x,y,num,fs1,fs2,color,ptxt,atxt){
    var n1=num % 1;
    var n2=num - n1;
    var s1=ptxt+n2+'.';
    var s2= parseFloat(Math.round(num %1 * 100) / 100).toFixed(2).substring(2, 4);
    this.sFont(fs1,color);
    this.cv.textBaseline = "alphabetic";
    this.text(x,y+fs1,s1);
    var l=this.len(s1);
    this.sFont(fs2,color);
    this.cv.textBaseline = "alphabetic";
    this.text(x+l,y+fs1,s2+atxt);
      this.cv.textBaseline = "top";
};

// elementy wykresow

function __sizeprccalc(base, prc){
    if (prc>100){prc=100}
    return (base/100)*prc;
}

Canvas_tool_constructor.prototype.barCircle=function(x,y,r,lw,prc,color,bgcolor){
    if (prc>100){prc=100}
    var p= (359/100)*prc;
    this.cv.lineCap = 'round';

    if (bgcolor != null){
        this.cv.beginPath();
        this.cv.lineWidth = lw;
        this.cv.strokeStyle = bgcolor;
        this.cv.fillStyle=bgcolor;
        this.cv.arc(x, y, r, this.degToRad(270), this.degToRad((  359 ) - 90));
        this.cv.stroke();
    }

    if (prc!=0)
    {
        this.cv.beginPath();
        this.cv.lineWidth = lw;
        this.cv.strokeStyle = color;
        this.cv.fillStyle=color;
        this.cv.arc(x, y, r, this.degToRad(270), this.degToRad((  p ) - 90));
        this.cv.stroke();

    }

    this.cv.lineCap = 'butt';
};

Canvas_tool_constructor.prototype.barV=function (x,y,w,h,prc,color){
    var p= __sizeprccalc(h,prc);
    if (p>1){   this.box(x,y+(h-p),w,p,color); }
    else { this.box(x,y+h-1,w,1,'#000000');  }
    return h-p;
};

Canvas_tool_constructor.prototype.barH=function (x,y,w,h,prc,colorback,color,frame){
    if (prc>100){prc=100}
    var p= (w/100)*prc;

    if (frame){
    this.box(x,y,w,h,'#000');
    this.box(x+1,y+1,w-2,h-2,colorback);
    this.box(x+1,y+1,p-2,h-2 ,color);
    } else {
        this.box(x,y,w,h,colorback);
        this.box(x,y,p,h ,color);
    }
};

Canvas_tool_constructor.prototype.barHPL=function (x,y,w,h,prc,colorback,color,fs,fcolor){

    this.barH(x,y,w,h,prc,colorback,color);
    this.sFont(fs,fcolor,false);
    var dprc = parseFloat( prc).toFixed(1);
    this.text(x+w+5,y,dprc +'%')
};

Canvas_tool_constructor.prototype.barHT=function (x,y,w,h,prc,txt,color,fs,fcolor){
    var p= __sizeprccalc(w,prc);
    this.box(x,y,p,h ,color);
    this.frame(x,y,p,h,1,'silver');
    this.sFont(fs,fcolor,false);
    this.text(x+p+5,y,txt)
};


Canvas_tool_constructor.prototype.barVB=function (x,y,w,h,prc,bcolor,color){
    var p= __sizeprccalc(h,prc);
    if (p>1){
        this.box(x,y+(h-p),w,p,'#000000');
        this.box(x+1,y+(h-p)+1,w-2,p-2,color); }
    else { this.box(x,y+h-1,w,1,'#000000');  }
    return h-p;
};

Canvas_tool_constructor.prototype.barVMark=function(x,y,w,h,bw,prc,color,bcolor,lcolor,lh,lex,test){
    var p= __sizeprccalc(h,prc);
    if(test){ this.frame(x,y,w,h,1,'yellow'); }

    this.frame(x+(w-bw),y,bw,h,0,bcolor,bcolor);
    this.frame(x+(w-bw),y+(h-p),bw,p,0,color,color);

    var x2=x+ ( w-(1.5 * bw));
    var hy=y + h - p;
    this.lineH(x, x2, y+h ,lh,lcolor  );
    this.lineH(x2, x+ w+lex, hy ,lh,lcolor  );
    this.lineV(x2,hy,y+h,lh,lcolor);

    this.xx=x+w+lex; this.yy=hy;

};


// HUD Simple
Canvas_tool_constructor.prototype.hudfxmch=function(nr,x, y, lw,lo, lr, color ){
    for (var j = 0; j < 11 ; ++j) {
        var v=canvas_flash.fxas[j];
        if (nr==1){v=canvas_flash.fxaf[j]; }
        if (nr==2){v=canvas_flash.fxat[j]; }
        v=v*lr;
       this.lineH(x , x+v  ,y +(j*lo),lw,color )
    }

};

Canvas_tool_constructor.prototype.hud_corners=function(x, y, w, h, l, lw, color,style,anim){
    this.cv.beginPath();
    this.strokeStyle(color,lw,'square');

    if (style==0) {
        l= this.cf.aVal( anim, l )
        this.line(x, y, x + l, y);
        this.line(x, y, x, y + l);
        this.line(x + w - l, y, x + w, y);
        this.line(x + w, y, x + w, y + l);
        this.line(x, y + h - l, x, y + h);
        this.line(x, y + h, x + l, y + h);
        this.line(x + w - l, y + h, x + w, y + h);
        this.line(x + w, y + h, x + w, y + h - l);

    } else if (style==1){
        l= this.cf.aVal( anim, l )
        this.line(x + w - l, y, x + w, y);
        this.line(x + w, y, x + w, y + l);
        this.line(x, y + h - l, x, y + h);
        this.line(x, y + h, x + l, y + h);

    }else if (style==2) {
        w= this.cf.aVal( anim, w )
       this.line(x, y, x + l, y);
        this.line(x, y, x, y + h);
        this.line(x + w - l, y, x + w, y);
        this.line(x, y + h - l, x, y + h);
        this.line(x, y + h, x + l, y + h);
        this.line(x + w - l, y + h, x + w, y + h);
        this.line(x + w, y + h, x + w, y + h - h);
    }

    this.cv.stroke();
    this.xx=x; this.yy=y; this.ww=w; this.hh=h;
};

Canvas_tool_constructor.prototype.hud_corners_rect=function(delta,l,lw,color,style,anim){

    this.hud_corners(  this.xx-delta, this.yy-delta, this.ww+(2*delta), this.hh+(2*delta), l,lw,color ,style,anim   )

};

Canvas_tool_constructor.prototype.drawHexagon=function(x,y,size){
    this.strokeStyle('silver', 1);
    this.cv.beginPath();
    this.cv.moveTo(x + size * Math.cos(0), y + size * Math.sin(0));

    for (var side=0; side < 7; side++) {
        this.cv.lineTo(x + size * Math.cos(side * 2 * Math.PI / 6), y + size * Math.sin(side * 2 * Math.PI / 6));
    }

    this.cv.stroke();
};


Canvas_tool_constructor.prototype.hex_grid= function(x, y, width, height,radius) {

/*
    var alpha = 1;
    var color 		=  '#1e1e1e';
    var lineWidth  	= 1;
    this.strokeStyle('silver', 1);
    this.cv.fillStyle='lime'

    //length of line
    var r = radius;
    var part = 60;
    var hexSize = r*Math.sqrt(3);
    var yHexSize = r*Math.sqrt(2.25);
    var xHexes = width / hexSize;
    var yHexes = height / yHexSize;

    this.cv.beginPath();

    for (xGrid=0;xGrid<=xHexes;xGrid++){
        for (yGrid=0;yGrid<=yHexes;yGrid++){
            if (yGrid % 2 == 0) {
                //even row
                shiftX = hexSize/2;
            }
            else {
                //odd row
                shiftX=0;
            }
            this.drawHexagon(xGrid*hexSize+shiftX,yGrid*yHexSize,radius)
            for (i=0;i<=6;i++) {
                //var a = i * part - 90;
                var a = i * 60 - 90;
                x = r * Math.cos(a * Math.PI / 180)+xGrid*hexSize+shiftX;
                y = r * Math.sin(a * Math.PI / 180)+yGrid*yHexSize;

                if (i == 0) {
                  //  this.cv.moveTo(x,y);

                }
                else {
                   // this.cv.lineTo(x,y);
                }
            }
        }
    }
    //this.cv.fill();
    this.cv.stroke();
*/

};



// spec
Canvas_tool_constructor.prototype.grid= function(xStep, yStep, x, y, width, height) {
    xStep = xStep       || 50;
    yStep = yStep       || 50;
    x = x               || 0;
    y = y               || 0;
    width = width       || this.getWidth();
    height = height     || this.getHeight();
    this.cv.beginPath();
    for (var lineX = xStep; lineX < width; lineX += xStep) {
        for (var lineY = yStep; lineY < height; lineY += yStep) {
            this.line(lineX, 0, lineX, height);
            this.line(0, lineY, width, lineY);
        }
    }
    this.cv.stroke();
};

Canvas_tool_constructor.prototype.bar_fx_progress=function(x, y, w, h, color, bgcolor){
    var wx=(w/8)-(w/32);
    for (var j = 0; j < 8; ++j) {  this.box(x+ (j*(w/8)) ,y,wx,h,bgcolor )  }
    this.box(x+ (this.cf.loop8  *(w/8)) ,y,wx,h,color )
};


Canvas_tool_constructor.prototype.drawIco=function(x,y,code,size,color){    //code w formacie '\uf188'
    var fx=this.cv.font;
    this.cv.font = size+'px Material Design Icons';
    var ss=code;
    this.cv.fillStyle = color;
    this.cv.textBaseline = "top";
    this.text(x,y,ss);
    this.cv.font=fx;
    this.xx=x; this.yy=y;

};


Canvas_tool_constructor.prototype.drawIcoEx=function (x,y,ico,size,color,nr){
    var sx=size;
    if (nr==0){sx=size/8;  }
    if (nr==1){sx=size/4;  }
    if (nr==2){sx=size/2;  }

    var ax=x-(sx/2)+(size/2);
    var ay=y-(sx/2)+(size/2);

    this.drawIco(ax, ay, ico, sx, color );
};

Canvas_tool_constructor.prototype.drawIcoBox=function (x,y,ico,size,color,bcolor,fcolor){
    this.frame(x,y,size,size,1,fcolor,bcolor);
    this.drawIco(x+2,y+2,ico,size-2,color);
};




function Canvas_tool_constructor(canvas) {
    var that = this;
    this.cvv = document.getElementById(canvas);
    this.cv = this.cvv.getContext('2d');
    this.cf=canvas_flash;
    this.xx=0;
    this.yy=0;
    this.hh=0;
    this.ww=0;

    this.testc=0;
    this.mouse = {
        x: 0,
        y: 0,
        clicked: false,
        down: false
    };


    this.initEvent=function(){

        this.cv.canvas.addEventListener("mousemove", function(e) {
            that.mouse.x = e.offsetX;
            that.mouse.y = e.offsetY;
            that.clicked = (e.which == 1 && !that.mouse.down);
            that.mouse.down = (e.which == 1);
        });
        this.cv.canvas.addEventListener("mousedown", function(e) {
            that.mouse.clicked = !that.mouse.down;
            that.mouse.down = true;
        });

        this.cv.canvas.addEventListener("mouseup", function(e) {
            that.mouse.down = false;
            that.mouse.clicked = false;
        });
    };


    this.getWidth=function(){ return this.cv.canvas.width  };
    this.getHeight=function(){ return this.cv.canvas.height  };
    this.setWidth=function(w){ that.cvv.width=w   };
    this.setHeight=function(h){

        $('#'+canvas).css('height',h+'px' );
        that.cv.canvas.height=h;
           };

    this.clear=function(test,black){

        this.cv.clearRect(0, 0, this.cv.canvas.width+1, this.cv.canvas.height+1);
        if (test==true){

            var clight1='#E8E8E8';
            var clight2='gray';
            if (black){
                clight1='#5F5F5F';
                clight2='#AAAAAA';
            }

            this.strokeStyle(clight1,1)
            this.grid(10,10,0,0,this.cv.canvas.width, this.cv.canvas.height)
        this.strokeStyle(clight2,1)
        this.grid(100,100,0,0,this.cv.canvas.width, this.cv.canvas.height)   }
    };

    this.strokeStyle= function(color, lineWidth, lineCap) {
        this.cv.strokeStyle = color;
        if (lineWidth != null) {this.cv.lineWidth = lineWidth;   }
        if (lineCap != null) {this.cv.lineCap = lineCap;     }
    };

    //linie
    this.line= function(x1, y1, x2, y2) {
        this.cv.moveTo(x1+0.5, y1+0.5);
        this.cv.lineTo(x2+0.5, y2+0.5);
    };

    this.strokeLine= function(x1, y1, x2, y2) {
        this.cv.beginPath();
        this.line(x1, y1, x2, y2);
        this.cv.stroke();
    };



}