<?php
session_start();
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/components/check.php";
include_once($path);

?>


<!DOCTYPE html>
<html lang="en">
<head>

<?php

$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/components/header.php";
include_once($path);

?>
<style>
	.item-elem {
	   width: 100px;
	   display: inline-block;
	}
	.val-elem {
	   width: 60px;
	   display: inline-block;
	   
	}
	.val-elem-special {
	   width: 150px;
	   display: inline-block;
	   
	}
	.row-elem {
		height: 25px;
	}
    .left{ display:inline-block;width:40%;color: rgba(255, 255, 255, 0.8);padding-top:3px; }
    .right{ margin-left:17px;display:inline-block;width:33%;height:20px;color: rgba(255, 255, 255, 0.8);padding-top:3px; }
    .center{ display:inline-block;width:15%;color: rgba(255, 255, 255, 0.8);text-align:center;padding-top:5px; }
    
	.center-special {
		 display:inline-block;width:55%;color: rgba(255, 255, 255, 0.8);text-align:center;padding-top:5px;
	}
	
    .ps> .ps__scrollbar-x-rail, .ps> .ps__scrollbar-y-rail{
	   
	    opacity: 0.6;
	}
	
	.momentum-scroll {
		   -webkit-overflow-scrolling: touch; /* Lets it scroll lazy */
	}
	
	.scroll-pane
	{
	    width: 100%;
	    height: 200px;
	    overflow: auto;
	}
	.scroll-pane p
	{
	    margin: 5px 0;
	}

 .navbar-collapse::-webkit-scrollbar {
    width: 20px;
}
.navbar-collapse::-webkit-scrollbar-track {
    background-color: lightgray;
}
.navbar-collapse::-webkit-scrollbar-thumb {
    background-color: lightblue;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
			

<script>
	var graphs_lines = {};
	var id_graphs = 0;
	var t_env_sensor = [];
	var MAX_GRAPH_SIZE = 2000;
	var global_init = 0;
	function createLine( id, datas, name, color ) {
		var labels1 = [];
		for( var x = 0; x < 1000; x++ ) {
			labels1.push( "" );
		}
		MAX_GRAPH_SIZE = labels1.length;
		//
		

    const custom_canvas_background_color = {
      id: 'custom_canvas_background_color',
      beforeDraw: (chart, args, options) => {
        const {
          ctx,
          chartArea: { top, right, bottom, left, width, height },
          scales: { x, y },
        } = chart;
        ctx.save();
        ctx.globalCompositeOperation = 'destination-over';
        ctx.fillStyle = '#E5E5E5';
        ctx.fillRect(left, top, width, height);
        ctx.restore();
      },
    };
    	var data = {
    			labels : labels1,
    			datasets : [
    				{
    			        fill: false,
    			        label: 'Signal',
    			        fill: false,
    			        borderColor: color,
    					data : datas
    				}
    			]
    		}
    	  var ctx = document.getElementById(id).getContext("2d");
    
    	  var f =  new Chart(ctx , {
    		    type: "line",
    	  	scaleOverlay : false,
    	  	scaleOverride : false,	
    	  	scaleSteps : 1,
    	  	scaleStepWidth : 1,
    	  	scaleStartValue : 0,
    		data: data,
    	  	scaleLineWidth : 1,
    	  	 plugins: [custom_canvas_background_color],
    	  	scaleShowLabels : false,
    	  	scaleLabel : "<%=value%>",
    	  	scaleFontFamily : "'Lato'",	
    	  	scaleFontSize : 12,	
    	  	scaleFontStyle : "800",
    	  	scaleFontColor : "rgba(0,0,0,0)",	
    
    	  	scaleShowGridLines : false,
    	  	responsive: true,
    	  	scaleGridLineColor : "rgba(0,0,0,0)",
    	  	scaleGridLineWidth : 1,	
    
    	  	bezierCurve : true,
    
    	  	pointDot : false,
    	  	pointDotRadius : 5,
    	  	pointDotStrokeWidth : 1,
    
    	  	datasetStroke : false,
    	  	datasetStrokeWidth : 1,
    	  	datasetFill : false,
    
    	  	animation : true,
    	  	animationEasing : "easeOutQuart",
    	  	onAnimationComplete : null,
    	  	scaleShowLabels : false,
    	    options: {
    	        scales:
    	        {
    	            yAxes: [{
    	                display: false,
    	                gridLines: {
    	                    display: true,
    	                    drawBorder: false,
    	                }
    	               
    	            }],
    	            xAxes: [{
    	            	 display: false,
    	                ticks: {
    	                    fontColor:['green','red','blue','yellow','green','red'],
    	                    callback: function(value, index, values) {
    	                    if(index === 3) {
    	                      return '**'+value+'**';
    	                    } 
    	                    else {
    	                        return value;
    	                        }
    	                    }
    	                },
    	            }]
    	        }, 
    				legend: {
    					display: false
    				},
                    elements: {
                        point:{
                            radius: 0
                        }
                    },
                    chartArea: {
                        backgroundColor: 'rgba(0,0,0,0)'
                    }
    				
    	    }
    
    
    	  });
    	  graphs_lines[ id ] = f;
	  
	}

    google.charts.load('current', {'packages':['timeline']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart( name, interval_start, interval_length ) {
		return;
		  $( "#example3.1" ).empty();
		  var datas = [];

		  datas.append( ['Activity', 'Start Time', 'End Time'] );

		  for( var x = 0; x <arr.length; x++ ) {
		      
		        var l = [name,
		         			new Date(interval_start),
		         			new Date(interval_start + interval_length)];
			    datas.append( l );
		  }

	    }

        function saveDone() {
        	showInfoMsg( "Teplota uložená", 2);
        	        	
        }
	
		function sendData( id ) {
			var dats = $("#manual-temp-" + id).val();
						
			if ( dats.indexOf( "," ) != -1 ) {
				dats = dats.replace( ".", "," );
			}
			var timestamp = Date.now()/1000;
			createNewCommands( "task", { "task_name": "GetData", "params": {"query": "INSERT INTO public.\"TestCoin\"( \"val\", \"timestamp\", \"type\", \"coin_id\"    ) VALUES( '" + dats + "', "+ timestamp +", 0, " + id + " )" } }, saveDone );
			showInfoMsg( "Ukladá sa teplota...", 2);
        	 
		}
	
		function createGraphTable( data ) {
			var dataset = [data];

			var options = {
					id_div_container: "visavail_container",
					id_div_graph: "visavail_graph",
					
					icon: {
						class_has_data: 'fas fa-fw fa-check',
						class_has_no_data: 'fas fa-fw fa-exclamation-circle'
					},
					zoom:{
						enabled:true,
					},
					responsive:{
						enabled:true,
					},
					tooltip: {
						date_plus_time: true
					},
					date_in_utc: true,
				};
				
			var chart = visavail.generate(options, dataset)
		}
		var time = 0;
		var time_c = 0;
		
		function fir( TAPS2, b2, TAPS3, b3 ) {
			this.MUL = 1;
			this.TAPS = TAPS2;
			this.x_ptr = 0;
			this.b = b2;
			this.x_old = [];
			
			this.MUL1 = 1;
			this.TAPS1 = TAPS3;
			this.x_ptr1 = 0;
			this.b1 = b3;
			this.x_old1 = [];
			
		}
		
		var animation_array = [];
		var unique_data_array = [];
		
		var fir_array = [];
		
		function proc( dat ) {
			dat = dat.replace( "{", "[" );
			dat = dat.replace( "}", "]" );
			dat = JSON.parse( dat );
			return dat;
		}
				var x_old = [];
		var xxx = 0;
		var MUL = 1;
		var TAPS = 61;
		var x_ptr = 0;
		var b = [0.000618368,0.000572584,0.000537290,0.000493559,0.000417653,0.000281911,0.000055909,-0.000292177,-0.000794032,-0.001479582,-0.002375343,-0.003502828,-0.004877095,-0.006505488,-0.008386658,-0.010509900,-0.012854871,-0.015391685,-0.018081417,-0.020877005,-0.023724505,-0.026564681,-0.029334855,-0.031970950,-0.034409643,-0.036590557,-0.038458375,-0.039964814,-0.041070364,-0.041745724,0.957381204,-0.041745724,-0.041070364,-0.039964814,-0.038458375,-0.036590557,-0.034409643,-0.031970950,-0.029334855,-0.026564681,-0.023724505,-0.020877005,-0.018081417,-0.015391685,-0.012854871,-0.010509900,-0.008386658,-0.006505488,-0.004877095,-0.003502828,-0.002375343,-0.001479582,-0.000794032,-0.000292177,0.000055909,0.000281911,0.000417653,0.000493559,0.000537290,0.000572584,0.000618368];
		
		var MUL1 = 1;
		var TAPS1 = 5;
		var x_ptr1= 0;
		var b1 = [0.030970446,0.238558616,0.460941877,0.238558616,0.030970446];
		var x_old1 = [];	
		
		function animationStep() {
			for ( tracker_id in animation_array ) {
				
				if ( animation_array[ tracker_id ].length != 0 ) {
					
					t = 500;
					
					for ( var x= 0; x < t; x++ ) {
						if (  animation_array[ tracker_id ].length == 0 )
							continue;
						
						var data  = animation_array[ tracker_id ].shift();
						var red1 = [];
						var green1 = [];
						var ir1 = [];
						var total = [];				
						
						data["ekg"] = ( data["ekg"] );
						data["breath"] = ( data["breath"] );
						
						
						for ( var y=0; y <  data["ekg"].length; y++ ) {
							total[ y ] =  data["ekg"][ y ];
							red1[ y ] =  data["ekg"][ y ];
							green1[ y ] =  data["breath"][ y ];

							fir_array[ tracker_id ].x_old[fir_array[ tracker_id ].x_ptr] = total[ y ] * MUL;
							
							total[ y ] = 0;
							
							  for (var i = 0; i < fir_array[tracker_id].TAPS; i++)
							  {
							    var index;
							    
							    if (i <= fir_array[ tracker_id ].x_ptr)  
							      index = fir_array[ tracker_id ].x_ptr - i;
							    else
							      index = fir_array[ tracker_id ].TAPS + fir_array[tracker_id].x_ptr - i;
							    total[ y ]  += (fir_array[tracker_id].x_old[index] * fir_array[tracker_id].b[i]) / (fir_array[tracker_id].MUL * fir_array[tracker_id].MUL);
								
							  }
							  
							  fir_array[tracker_id].x_ptr = (fir_array[tracker_id].x_ptr + 1) % TAPS;
							  
							  
							  
							  fir_array[tracker_id].x_old1[fir_array[tracker_id].x_ptr1] = total[ y ] * MUL;
							  total[ y ] = 0;
							  for (var i = 0; i < fir_array[tracker_id].TAPS1; i++)
							  {
							    var index1;
							    
							    if (i <= fir_array[tracker_id].x_ptr1)  
							    	index1 = fir_array[tracker_id].x_ptr1 - i;
							    else
							    	index1 = fir_array[tracker_id].TAPS1 + fir_array[tracker_id].x_ptr1 - i;
							    total[ y ]  += (fir_array[tracker_id].x_old1[index1] * fir_array[tracker_id].b1[i]) / (fir_array[tracker_id].MUL * fir_array[tracker_id].MUL);
								
							  }
							  total[ y ] = total[ y ] * (-1);
							  fir_array[tracker_id].x_ptr1 = (fir_array[tracker_id].x_ptr1 + 1) % TAPS1;
							  
						}
						
	    				char = graphs_lines[ "ekg-line-" + tracker_id ];
	    				char2 = graphs_lines[ "breath-line-" + tracker_id ];
	    				
	    				addData1( char, red1, red1 );
	    				addData1( char2, green1, green1 );
	    				
	    				if ( data["time"] - time > 1 ) {
	    					$("#sample-r-"+ data[ "coin_id" ]).html( ( time_c / ( data["time"] - time )  ));
	    					time_c = 0;
	    					time = data["time"];
	    				}
	    				
					}
				}
			}
		}
		
		function updateHRDisplay( id, hr, rr, spo2, resp, stress ) {
			var element_id_hr = "hr-$ID$";
			element_id_hr = element_id_hr.replace( "$ID$", id );
			
			$("#" + element_id_hr).html( hr );
			
			var element_id_spo2 = "spo2-$ID$";
			element_id_spo2 = element_id_spo2.replace( "$ID$", id );
			
			if ( parseFloat( spo2/10 ) > 99.4 )
				spo2 = 99.4;
			else
				spo2 = spo2 / 10;
			$("#" + element_id_spo2).html( spo2 );
			
			var element_id_rr = "rr-$ID$";
			element_id_rr = element_id_rr.replace( "$ID$", id );
			
			$("#" + element_id_rr).html( rr/25 );

			var element_id_resp = "resp-$ID$";
			element_id_resp = element_id_resp.replace( "$ID$", id );
			
			$("#" + element_id_resp).html( resp );
			
			var element_id_stress = "stress-$ID$";
			element_id_stress = element_id_stress.replace( "$ID$", id );
			
			$("#" + element_id_stress).html( stress );
		}
		
		function setTempLevel( ids, temp ) {
			$("#" + ids).html( temp );
		}
		
		function handleMsgs( type, device_type, data, coin_id, time ) {
			
			
			setLastMsg( coin_id, time );
			
			if ( device_type == 1 ) {
				if ( type == 0 ) {
					
					animation_array[ coin_id ].push( data );
					
					if ( unique_data_array[coin_id ] < data["u_n"] ) {
						unique_data_array[coin_id] = data["u_n"];
						
					}else{
						
					}
					
				}
				
				if ( type == 9 ) {
				}
				
				if ( type == 2 ) {
					setBatteryLevel( "bat-" + coin_id  + "-level", data["battery"]*24, 0 );
				}
				
				if ( type == 7 ) {
					var t = data["temp"];
					var t1 = data["temp1"];
					
					$( "#temp-" + coin_id ).html( parseInt( t*100 ) /100 );
					$( "#temp1-" + coin_id ).html( parseInt( t1*100 ) /100 );
					
				}
				
				if ( type == 8 ) {
				}
				
				if ( type == 10 ) {
				}
			} 
			
		}
		
		function liveUpdate() {

			this.handleLive = function( data ) {
			
				
				if ( global_init == 0 )
					return 0;
				if ( data["device_type"] != 1 )
					return;
	    		if ( data["coin_id"] in active_devices ) {
	    			active_devices[ data["coin_id"] ]["time"] = new Date().getTime();
	    			active_devices[ data["coin_id"] ]["type"] = 1;
	    		}
				
	    		if ( data["coin_id"] in unique_data_array )  {
	    			
	    		}else{
					unique_data_array[ data["coin_id"] ] = 0;
	    		}

				if ( data["coin_id"] in animation_array )  {
    			}else{

					animation_array[ data["coin_id"] ] = [];
					fir_array[ data["coin_id"] ] = new fir( TAPS, b, TAPS1, b1 );
					
					

					
    				
    			}
				
				setSignalLevel( "snr-" + data["coin_id"]  + "-level", data[ "snr" ], 0 );
				
				for ( msg in data["data"] ) {
					if ( "type" in data["data"][msg] ) {
					}else{
						continue;
					}
					handleMsgs( data["data"][msg]["type"], data["device_type"], data["data"][msg], data["coin_id"], data["time"]  );
				}
				
				
			}

		}
		
		function liveUpdate1() {

			this.handleLive = function( data ) {
			}

		}
		var focused = true;

	    
    	window.onfocus = function() {
    		if ( focused == false ) {
    			clearInterval( global_socket_wrapper.interval );
    			global_socket_wrapper.interval = setInterval( global_socket_wrapper.step, 20 );
    		}
    	    focused = true;
    	};
    	window.onblur = function() {

    		if ( focused == true ) {
    			clearInterval( global_socket_wrapper.interval );
    			global_socket_wrapper.interval = setInterval( global_socket_wrapper.step, 2000 );
    		}

    		focused = false;
        	
    	};
		setInterval( check, 100 );
        var page_vis = true;
        function check() {
        	if ( document.hidden == true && page_vis == true ) {
        		clearInterval( global_socket_wrapper.interval );
        		clearTimeout( ff );
        		page_vis = false;
        	}
        	if ( document.hidden == false && page_vis == false  ) {
        		//updateCoinTable();
        		global_socket_wrapper.interval = setInterval( global_socket_wrapper.step, 20 );
        		page_vis = true;
        	}
        	
			
        }
		
		var datasource = 0;
		var data_table = 0;
		var global_tables = {};
		var id_settings_table = {};
		
		function createNewTableDataSet( data ) {
			var d =	( data );
			global_tables[ "global_main_table" ].processData( d["result"] );
			for (const x of d["result"] ) {
				id_settings_table[ x[ 0 ] ] = x[ 11 ]; 
					
			}

			try{
				$("#loaderf").hide();
			}catch(err){
				
			}
		}
		var ff;
        
		var ekg_table = [];
		var allowed_arr = [ 14, 5, 34, 16, 41, 10, 32, 20 ];
		
		function createElementCoinV1( device_id, temp_env, temp, ir_led, r_led, temp_dev, snr, bat, temp1, type, latest_time, names ) {
			
			var elem = ekg_element;
			var msg_time = latest_time;
            //<canvas id="ekg-IDS" ></canvas>
	        elem = elem.replaceAll( "IDS", device_id );
	        elem = elem.replaceAll( "CONFS", 1 );
	        elem = elem.replaceAll( "NAMES", names );

	        var calc_t_dev = parseInt( temp_dev*100 )/100
	        var calc_t_env = parseInt( temp_env*100 )/100
	        
	        if ( calc_t_env > 2000 )
	        	calc_t_env = "-";
	        
	        if ( calc_t_dev > 2000 )
	        	calc_t_dev = "-";
	        	
	        coin_table.push( device_id );
	        
	        if ( Number.isNaN( calc_t_dev ) == 0 ) {
    	        elem = elem.replaceAll( "$TEMP$", calc_t_dev );
	        }else{
    	        elem = elem.replaceAll( "$TEMP$", "-" );
	        }
	        
	        if ( Number.isNaN( calc_t_env ) == 0 ) {
    	        elem = elem.replaceAll( "$TEMP1$", calc_t_env );
	        }else{
    	        elem = elem.replaceAll( "$TEMP1$", "-" );
	        
	        }
	        
	        elem = elem.replaceAll( "$TIME$", jsTimestampTime( latest_time ) );
	        elem = elem.replaceAll( "$ACC$", '-' );
	        elem = elem.replaceAll( "$ROT$", '-' );
	        
	        active_devices[ device_id ] = [];
	        active_devices[ device_id ]["elem"] = elem;
	        active_devices[ device_id ]["time"] = latest_time*1000;
	        
	        active_devices[ device_id ]["bat"] = bat*24;
	        active_devices[ device_id ]["snr"] = ekg;
	        
	        active_devices[ device_id ]["type"] = 1;
	        

			
			checkLocation();
			
			setTimeout( updateElems, 700  );
			
		}
		
		
		function updateElems() {
		    for ( device in active_devices ) {
    			setBatteryLevel( "bat-" + device  + "-level", active_devices[ device ]["bat"], 0 ); 
    			setSignalLevel( "snr-" + device  + "-level", active_devices[ device ]["snr"], 0 );
    		}
    		load.clear();
    		
		}
		
		
        function createDashboard( data ) {
			var coin_ids = {};
			data = JSON.parse( data["result"] );
			var times = 0;
			
        	for( const device_id in data ) {
        	
        		if ( parseInt( data[device_id]["type"] ) != 1 ) {
        			continue;
        		}
        		
        		if ( allowed_arr.indexOf( parseInt( device_id ) ) == -1 ) 
						continue;
								
        			for (const [key, value] of Object.entries( data[device_id] )) {
                       if ( Array.isArray( value ) == true ) {
                          if ( value.length == 2 ) {
                          	if ( value[ 0 ] > times && key != "name" && key != "note" ) {
                          		times = value[ 0 ];
                          	}
                          }
                       }
                    }
                    
					try{
					var name;	
					if ( data[ device_id ]["name"] == null )
						name = "-";
					else
						name = data[ device_id ]["name"][ 1 ];
						
    				createElementCoinV1( device_id,     
			    						 data[ device_id ][ "temp1" ][1], 
										 0, 
										 data[ device_id ][ "ir_led" ][1], 
										 data[ device_id ][ "r_led" ][1], 
										 data[ device_id ][ "temp" ][1],
										 data[ device_id ][ "snr" ][1],
										 data[ device_id ][ "bat" ][1],
										 0,
										 type,
										 times,
										 name );  
					}catch(ex) {
						console.log( ex );
					}
					                    times = 0;
	        	global_init = 1;
	        	var curr_time = Date.now()/1000;
	        	coin_int = {};
        	
        	}
        }

       	
		
		
		function requestCreateDashboard() {
			createNewCommands( "task", { "task_name": "GetDataFromModel", "params": {"model": 'LiveViewStorage' } }, createDashboard ); 
		}

		var load = new Loader();
        function setContainer( id, val ) {
    		$( "#" + id ).empty();
    		$( "#" + id ).html( val );
    		
        }
		function getContainerFromTine( last_com ) {
			
			if ( last_com <= 120 ) {
				return "active_coins110";
			}else if ( last_com > 10 && last_com < 3600 ) {
				return "slightly_late_coins";
			}else if ( last_com => 3600 ) {
				return "really_late_coins";
			}
			return 0;
			
		}
		function changeContainerLocation( id, last_com, elem, type) {
			var yy = new Date();
			var tt = (yy.getTime()/1000) -  last_com;
			console.log( tt );
			console.log( id );
			
			var new_c = getContainerFromTine( tt );
			var old_c = $("#"+id).parent().attr('id');
			
			
			if ( new_c == old_c ) {
				return;
			}
			try{
				$("#"+id).remove();
			}catch(error) {
				//console.log( old_c[0] ); 
			}
			
			
					$("#"+new_c).append( elem ).ready(function () {
						try{
						}catch(error) {
						}
					  });

			
		}

		var ff = 0;

		
		function addData(chart, data1) {
			var c = 0;
			////console.log( chart ); 
		    chart.data.datasets.forEach((dataset) => {
		    	data1 = data1.replace( "{", "[" );
		    	data1 = data1.replace( "}", "]" );
		    	data1 = JSON.parse( data1 );
		    	for( i of data1 ) {
		    	
		    		while ( dataset.data.length >= MAX_GRAPH_SIZE+30 ){
		    			dataset.data.shift();
		    		}
		    		c++;
		         	dataset.data.push(i);
		         }
		        
		    });
		    chart.update();
			return c;
		}
		
		
		function addData1(chart, data1, data2) {
			var c = 0;
			try{
			    chart.data.datasets.forEach((dataset) => {
			    	var rr = [];
			    	
			    	for( var x = 0; x < data2.length; x++ ) {
			    		rr[ x ] = data1[ x ];
			    	}
			    	
			    	for( i of rr ) {
			    		while ( dataset.data.length >= MAX_GRAPH_SIZE+30 ){
			    			dataset.data.shift();
			    		}
			    		c++;
			    		try{
			         		dataset.data.push(i);
			    		}catch{
			    			
			    		}
			         }
			        
			    });
			    chart.update();
			}catch (error) {
			}
		   
			return c;
		}		
    	var coin_int = {};
    	
    	function setBatteryLevel( ids, bat, temp ) {
    		bat = parseInt( bat );

    		if ( bat > 3900 ) { 
    			$("#" + ids).attr( "src", "https://" + window.location.hostname + "/img/battery_full.png");
    		}else if ( bat < 3900 && bat >= 3750 ) { 
    			$("#" + ids).attr( "src", "https://" + window.location.hostname + "/img/battery_top.png");
    			
    		}else if ( bat < 3750 && bat >= 3600 ) { 
    			$("#" + ids).attr( "src", "https://" + window.location.hostname + "/img/battery_mid.png");
    			
    		}else if ( bat < 3600 && bat > 3500 ) { 
    			$("#" + ids).attr( "src", "https://" + window.location.hostname + "/img/battery_low.png");
    		}else if ( bat <= 3500  ) { 
    			$("#" + ids).attr( "src", "https://" + window.location.hostname + "/img/battery_dead.png");
    		}
    		
    	}
    	
    	    	
    	function setLastMsg( ids, time ) {
    		$("#time-" + ids).html( jsTimestampTime( time ) );
    	}
    	
    	
     	function setSignalLevel( ids, snr ) {
    	    bat = parseInt( snr );
    		if ( bat <= 50 ) { 
    			$("#" + ids).attr("src","https://" + window.location.hostname + "/img/full_signal.png");
    		}else if ( bat >= 50 && bat <= 70 ) { 
    			$("#" + ids).attr("src","https://" + window.location.hostname + "/img/mid_signal.png");
    		}else if ( bat >= 70 && bat <= 250 ) { 
    			$("#" + ids).attr("src","https://" + window.location.hostname + "/img/low_signal.png");
    		}
    		
    	}  
     	
     	function showSettingsCoin( id, confs ) {
     		window.open("https://" + window.location.hostname + "/components/coin/coin_settings.php?dev_id=" + id + "&conf=" + confs, '_blank');
     		
     	}
     	
     	function showArchiveCoin( id ) {
     		window.open("https://" + window.location.hostname + "/components/coin/coin_archive.php?dev_id=" + id , '_blank');
     		
     	}
     	     	
    	function arrToData( data ) {
    		var resp1 = [];
    		for ( var i of data ) {
    			resp = i[ 1 ];
    			resp = resp.replace( '{', '[' );
    			resp = resp.replace( '}', ']' );
    			
				resp = JSON.parse( resp );
    			for ( var y of resp ) {
    				resp1.push( y ); 
    			}
    		}
    		return resp1;
    	
    	}
    	
    	
    	function checkLocation() {
    		for ( device in active_devices ) {
	    		changeContainerLocation( "container-" + device,active_devices[ device ]["time"]/1000, active_devices[ device ]["elem"], active_devices[ device ]["type"] );

    		}
    		
    	}
    	
    	var active_devices = [];
		var ekg_element;
		
		var wss_port1 = 18892;
		var addr1 = "wss://rbf.nanodesign.sk:" + wss_port1 + "/websocket/";
		var global_socket_wrapper = new SocketWrapper( addr1 );
		
		function start() {

			//load.init();
			var ff = new liveUpdate();
			var ff1 = new liveUpdate1();

			var ff3 = Math.floor(Date.now() / 1000);
			
			//global_socket_wrapper.init();
			//global_socket_wrapper.registerLiveUpdater("new_coin_data", ff);

			global_socket_wrapper.init();
			global_socket_wrapper.registerLiveUpdater("new_coin_data", ff);

			$.ajax({
                url: "components/dash/main_element_coin1.php", 
                context: document.body,
                success: function(response) {
                	ekg_element = response;
                	requestCreateDashboard();
                }
            });
            
            ddd = setInterval( animationStep, 200 );
            setInterval( checkLocation, 4000 );
            global_init = 1;
		}
		var ddd;
		var coin_table = [];
		function searchChanged (){
			
			clearSerch( 1 );
			var search_str = $("#search-bar").val();
			
			for ( key in coin_table ) {
				var elems = "#container-"+coin_table[ key ];
				var names = "" + coin_table[ key ];
				console.log( search_str );
				
				if ( coin_table[key].toString(10).includes( search_str ) ==  true  || names.includes( search_str ) ==  true  ) {
					
				}else{

					if ( $(elems).is(":hidden") == false ) {
						 $(elems).fadeOut();
						 
					}
					
				}
				 
			}
			
		}
		
		function searchChanged1 (){
			
			
			for ( key in coin_table ) {
				var elems = "#container-"+coin_table[key];
				console.log( elems );
				if ( $(elems).is(":hidden") == false ) {
						 $(elems).fadeOut();
						 
				}
			}
			
		}
		
		var active_id;
        function nameChanged() {
        	showInfoMsg( "Data saved", 2);
        }
		
		function changeName( id ) {
			active_id = id;
			$("#meno_s" ).html( id );
		}
        
        function sendNameChange() {
        
        	var names = $("#new_name").val();
        	
        	var timestamp = Date.now()/1000;
        	//createNewCommands( "task", { "task_name": "GetData", "params": {"query": "UPDATE public.\"Coins\" SET  \"name\" = '" + names + "' WHERE id = " + active_id } }, nameChanged );
        	createNewCommands( "task", { "task_name": "UpdateDeviceName", "params": { "name": names, "device_id": active_id }}, nameChanged );
        	
        	showInfoMsg( "Saving data...", 1);
        	//setTimeout( requestCoinNameIdTable, 6000 );
        	
        	//requestCoinNameIdTable();
        	$("#exampleModal").modal("hide");
			$( "#name-cont-" + active_id ).html( names );
        }
        		
        		
		function clearSerch( v ) {
			if ( v == 0 ) 
				$("#search-bar").val('');
			
			for ( key in coin_table ) {
				var elems = "#container-"+coin_table[key];
				
				if ( $(elems).is(":hidden") ) {
					 $(elems).fadeIn();
					 
				} 
			}
		}
		
</script>		
</head>

<body class="sidebar-mini" onload="start()" style="overflow:hidden;" >
	<script>
		load.init();
	</script>
	 <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" >
	  <div class="modal-dialog" role="document" id="dialog-windows">
	    <div class="modal-content">
	      <div class="modal-header">
	        <h5 class="modal-title" id="exampleModalLabel">Zmena mena <span id="meno_s"></span></h5>
	        <button type="button" class="close" data-dismiss="modal" aria-label="Zatvoriť">
	          <span aria-hidden="true">&times;</span>
	        </button>
	      </div>
	      <div class="modal-body">
	        <p> <span class="item-elem">Nove meno:</span> <span class="item-elem" ><input type="text" id="new_name" placeholder="Nove meno..." /></span> </p>
	        <p> <span></span> </p>
	        
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-primary" data-dismiss="modal">Zatvoriť</button>
	        <button type="button" class="btn btn-secondary" onclick="sendNameChange();">Uložiť</button>
	      </div>
	    </div>
	  </div>
	</div>
	
	  <div class="wrapper">
	    <div class="navbar-minimize-fixed">
	      <button class="minimize-sidebar btn btn-link btn-just-icon">
	        <i class="tim-icons icon-align-center visible-on-sidebar-regular text-muted"></i>
	        <i class="tim-icons icon-bullet-list-67 visible-on-sidebar-mini text-muted"></i>
	      </button>
	    </div>
	        <?php
	        
	        $path = $_SERVER['DOCUMENT_ROOT'];
        $path .= "/components/sidebar.php";
        include_once($path);
        
        ?>
	    <div class="main-panel ps ps--active-y ps--scrolling-y momentum-scroll scroll-pane" style="overflow-y: scroll !important;">
	    
	    
	    
	      <!-- Navbar -->
		<?php
	        
	        $path = $_SERVER['DOCUMENT_ROOT'];
        	$path .= "/components/plugin.php";
        	include_once($path);
        
        ?>
	    <?php
	        
	        $path = $_SERVER['DOCUMENT_ROOT'];
            $path .= "/components/navbar.php";
            include_once($path);
        
        ?>
	      <!-- End Navbar -->
		      <div class="content">
			      	<p><i class="tim-icons icon-zoom-split" style="display:inline-block;"  ></i><input placeholder="Vyhladať..." id="search-bar" onchange="searchChanged()" class="form-control" style="display:inline-block;width:95%;margin-left:10px;" /><i class="tim-icons icon-simple-remove" onclick="clearSerch(1)" style="margin-left:10px;display:inline-block;"  ></i></p>
			        <h3 style="width:100%; text-align:left!important;" class="text-center">Aktívna komunikacia</h3>
			        <div class="row row-cols-1 row-cols-md-2" id="active_coins110">
			
			        </div>
			        <h3 style="width:100%; text-align:left!important;" class="text-center">Posledná správa pred hodinou</h3>
			        <div class="row row-cols-1 row-cols-md-2" id="slightly_late_coins">
			        </div>   
			        <h3 style="width:100%; text-align:left!important;" class="text-center">Posledná správa 3 hodinami</h3>
			        <div class="row row-cols-1 row-cols-md-2" id="really_late_coins">
			
			        </div>       
		
		      </div>
	      </div>
			
		<?php
	        
	        $path = $_SERVER['DOCUMENT_ROOT'];
            $path .= "/components/footer.php";
            include_once($path);
            
        ?>
	    </div>
	  <!--   Core JS Files   -->
	    <?php
	        
	        $path = $_SERVER['DOCUMENT_ROOT'];
            $path .= "/components/code_footer.php";
            include_once($path);
            
        ?>

</body>

</html>
