text: /*
  	Modified: 21.04.2021
  
  	Copyright (c) 2021 Thorsten Willert
  
  	Permission is hereby granted, free of charge, to any person obtaining a copy of
  	this software and associated documentation files (the "Software"), to deal in
  	the Software without restriction, including without limitation the rights to use,
  	copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
  	Software, and to permit persons to whom the Software is furnished to do so,
  	subject to the following conditions:
  
  	The above copyright notice and this permission notice shall be included in all
  	copies or substantial portions of the Software.
  
  	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  	INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  	PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  	OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  	SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  */
  
  // Local storage key: File name without suffix + ID of the element
  const sStorage_Key = 'SHMI__' +
  location.pathname.substring(location.pathname.lastIndexOf('/') + 1).replace(/\..+$/, '');
  
  // =========================================================================
  const updateInterval = 1000; // refresh rate of the instruments
  // =========================================================================
  let ig_Snap = 10 ;// snap to grid
  
  $( () => {
  
  
      // =====================================================================
      function init() {
  
      	// load svg-background image or png as fallback
      	let sImage = './pict/' +
      	location.pathname.substring(location.pathname.lastIndexOf('/') + 1).replace(/\..+$/, '')
  
      	$('#IDpict').append(`<img id="ID_RI_image" src="${sImage}.svg" alt="RI" class="svg">`)
  
      	$(".svg").on("error", function(){
      			$(this).attr('src', `${sImage}.png`);
      			$(this).removeClass('svg');
          });
  
      	// =================================================================
          // add data points to select
          $.getJSON('./data/data.json', (data) => {
              $.each(data, (id, val) => {
                  //val = Round(val, 2);
  
                  if (id.indexOf('SP') == -1) {; // setpoint
  
  					if (id.indexOf('DI') !== -1) {
  						$('#ID_option_DI').append($('<option>', {
  							value: id,
  							text: id,
  						}));
  					} else if (id.indexOf('DO') !== -1) {
  						$('#ID_option_DO').append($('<option>', {
  							value: id,
  							text: id,
  						}));
  					// ---------------------------------------------------------
  					} else if (id.indexOf('AI') !== -1) {
  						$('#ID_option_AI').append($('<option>', {
  							value: id,
  							text: id + ' Meter',
  						}));
  						$('#ID_option_AIS').append($('<option>', {
  							value: id + '_S',
  							text: id + ' Sparkline',
  						}));
  						$('#ID_option_AIG').append($('<option>', {
  							value: id + '_G',
  							text: id + ' Gauge',
  						}));
  						$('#ID_option_AIL').append($('<option>', {
  							value: id + '_L',
  							text: id + ' Level',
  						}));
  					// ---------------------------------------------------------
  					} else if (id.indexOf('AO') !== -1) {
  						$('#ID_option_AO').append($('<option>', {
  							value: id,
  							text: id + ' Meter',
  						}));
  						$('#ID_option_AOS').append($('<option>', {
  							value: id + '_S',
  							text: id + ' Sparkline',
  						}));
  						$('#ID_option_AOG').append($('<option>', {
  							value: id + '_G',
  							text: id + ' Gauge',
  						}));
  					}
  				}; // setpoint
              });
          })
          .done( () => {
              $('.js-example-basic-multiple').select2();
              showInstruments();
          });
  
      }
      init();
  
      // ======================================================================
      // inject SVG
  	$('img[src$=".svg"]').each(function() {
  		let $img = jQuery(this);
  		let imgID = $img.attr('id');
  		let imgClass = $img.attr('class');
  		let imgURL = $img.attr('src');
  
  		jQuery.get(imgURL, (data) => {
  			let $svg = jQuery(data).find('svg');
  			if (typeof imgID !== 'undefined') {
  				$svg = $svg.attr('id', imgID );
  			}
  			if (typeof imgClass !== 'undefined') {
  				$svg = $svg.attr('class', imgClass+' replaced-svg');
  			}
  			$svg = $svg.removeAttr('xmlns:a');
  			$img.replaceWith($svg);
  		}, 'xml');
  	});
  
      // ======================================================================
      function savePosition(o) {
      	let obj = o.target;
  
          const oSave = {
              'id': obj.id,
              'type': 'RI',
              'left': Math.round($('#' + obj.id).offset().left),
              'top': Math.round($('#' + obj.id).offset().top),
              'height': obj.clientHeight,
              'width': obj.clientWidth,
              'rotate': 0,
          };
          localStorage.setItem(sStorage_Key + '__' + obj.id, JSON.stringify(oSave));
      };
  
      // ======================================================================
      function showInstruments() {
          let aA = [];
          let aD = [];
          let oInst;
  
          for (let i = 0; i < localStorage.length; i++) {
              oInst = JSON.parse(localStorage.getItem(localStorage.key(i)));
  
              if (oInst.type == 'RI') {
                  if ($('#' + oInst.id).length == 0) {
                      if (oInst.id.indexOf('D') != -1) {
                          aD.push(oInst.id.substr(3, 10));
                      }
                      if (oInst.id.indexOf('A') != -1) {
                          aA.push(oInst.id.substr(3, 10));
                      };
  
                      addInstrumentD(oInst.id.substr(3, 10));
                      addInstrumentA(oInst.id.substr(3, 10));
                  };
              };
          };
          $('#ID_Select_DI, #ID_Select_DO').val(aD).trigger('change');
          $('#ID_Select_AI, #ID_Select_AO').val(aA).trigger('change');
      };
  
      // ======================================================================
      function loadPositions() {
          let oInst;
  
          for (let i = 0; i < localStorage.length; i++) {
              oInst = JSON.parse(localStorage.getItem(localStorage.key(i)));
  
              if (oInst.type == 'RI') {
                  $('#' + oInst.id).offset({
                      top: oInst.top,
                      left: oInst.left,
                  });
                  $('#' + oInst.id).css('height', oInst.height);
                  $('#' + oInst.id).css('width', oInst.width);
                  $('#' + oInst.id).css('rotate', oInst.rotate);
              };
          };
      };
  
      // ======================================================================
      function addEvents() {
  
          // save position after drop or resize
          $('.instrument, .instrumentF, .instrumentG').on('clayfy-drop clayfy-resizeend', (e) => {
          	parent.top.$('#IDcoord').html('');
              savePosition(e);
          });
  
          $('.instrument, .instrumentF, .instrumentG').on('clayfy-drag clayfy-dragstart clayfy-resize clayfy-resizestart', (e) => {
  
          	let obj = e.target;
          	let l = $('#' + obj.id).position().left;
          	let t =  $('#' + obj.id).position().top;
  
  			if(!ig_Snap==0){
  				l = (l/ig_Snap).toFixed()*ig_Snap;
  				t = (t/ig_Snap).toFixed()*ig_Snap;
  				$('#' + obj.id).css('left',l);
  				$('#' + obj.id).css('top',t);
  			}
  
              parent.top.$('#IDcoord').html(
  				Math.round(t) + " / " +
  				Math.round(l) + " | " +
  				obj.clientHeight + " / " +
  				obj.clientWidth
              )
          });
      }
  
      // ======================================================================
      // remove instruments
      $('#ID_Select_DI, #ID_Select_DO, #ID_Select_AI, #ID_Select_AO').on('select2:unselect', (e) => {
          $('#ID_' + e.params.data.id).remove();
          localStorage.removeItem(sStorage_Key + '__ID_' + e.params.data.id);
      });
  
      // ======================================================================
      // add instruments
      $('#ID_Select_DI, #ID_Select_DO').on('select2:select', (e) => {
          addInstrumentD(e.params.data.id);
      });
      $('#ID_Select_AI, #ID_Select_AO').on('select2:select', (e) => {
          addInstrumentA(e.params.data.id);
      });
  
      // widget style
  	$('#ID_Style').change(function() {
  		let style = document.body.style;
  		let nr = parseInt( $(this).val() );
  
  		if ( nr > 0 ) {
  				style.setProperty('--SHMI_drag_bg', `var(--SHMI_drag_bg_${nr})`);
  				style.setProperty('--SHMI_drag_txt', `var(--SHMI_drag_txt_${nr})`);
  				style.setProperty('--SHMI_widget_bg', `var(--SHMI_widget_bg_${nr})`);
  		} else {
  				style.setProperty('--SHMI_drag_bg', "var(--dark)");
  				style.setProperty('--SHMI_drag_txt', "var(--light)");
  				style.setProperty('--SHMI_widget_bg', "rgba(0,0,0,0.5)");
  		}
  	});
  
  	// background
  	$('#ID_BGStyle').change(function() {
  		let bg = $(this).val();
  
  		$('#IDpict').attr('class', `bg-${bg}`);
  /*
  		switch (bg) {
  			case 'dark':
  			case 'primary':
  			case 'secondary':
  				//$('.SHMI_level').css('mix-blend-mode', 'exclusion');
  				$('.SHMI_level').css('filter', 'brightness(150%)');
  				break;
  			default:
  				$('.SHMI_level').css('mix-blend-mode', 'multiply');
  				$('.SHMI_level').css('filter', 'brightness(100%)');
  		};
  */
  	});
  
      // ======================================================================
      function addInstrumentA(id) {
      	let sPrepend = '';
  
          const sHTML_spark =
              `<div class="SHMI_drag SHMI_drag_%2 instrument shadow" title="${id}" id="ID_${id}">
  				<span id="ID_${id}_A" class="float-right"></span>
  				<br />
  				<div id="ID_%2" class="progress" style="padding-top:3px;margin-top:5px; height:20px;background-color:var(--SHMI_widget_bg)">
  					<span id="ID_${id}_spark" class="peity-%3 chart-%3">
  					0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
  					</span>
  				</div>
  			</div>`;
  
          const sHTML_meter =
              `<div class="SHMI_drag SHMI_drag_%2 instrument shadow" title="${id}" id="ID_${id}">
  				<span id="ID_${id}_A" class="float-right"></span>
  				<br />
  				<div id="ID_%2" class="progress" style="padding:1px; margin-top:5px; height:20px;background-color:var(--SHMI_widget_bg)">
  					<div id="ID_${id}_M" class="progress-bar" role="progressbar"></div>
  				</div>
  			</div>`;
  
  		const sHTML_level =
  			`<div class="SHMI_drag_level SHMI_drag_%2 instrumentF" title="${id}" id="ID_${id}">
  				<div id="ID_${id}_L" class="SHMI_level">
  						<span id="ID_${id}_A" class="SHMI_level_value" ></span>
  				</div>
  			</div>`;
  
  		const sHTML_gauge =
  			`<div class="SHMI_drag gauge SHMI_drag_%2 d-flex instrumentG justify-content-center align-middle shadow" title="${id}" id="ID_${id}">
  				<span id="ID_${id}_A" style="position:absolute; top:20px;"></span>
  				<span id="ID_${id}_donut" class="donut donut-%3">0/100</span>
  			</div>`;
  
          if (id.indexOf('AI') !== -1 && id.indexOf('_S') !== -1) {
                  sPrepend += sHTML_spark.replace(/%2/g, 'AI').replace(/%3/g, 'ai')
          } else if (id.indexOf('AO') !== -1 && id.indexOf('_S') !== -1) {
                  sPrepend += sHTML_spark.replace(/%2/g, 'AO').replace(/%3/g, 'ao')
  
          } else if (id.indexOf('AI') !== -1 && id.indexOf('_G') !== -1) {
  				sPrepend += sHTML_gauge.replace(/%2/g, 'AI').replace(/%3/g, 'ai')
  		} else if (id.indexOf('AO') !== -1 && id.indexOf('_G') !== -1) {
  				sPrepend += sHTML_gauge.replace(/%2/g, 'AO').replace(/%3/g, 'ao')
  
  		} else if (id.indexOf('AI') !== -1 && id.indexOf('_L') !== -1) {
  				sPrepend += sHTML_level.replace(/%2/g, 'AI')
          } else if (id.indexOf('AI') !== -1) {
                  sPrepend += sHTML_meter.replace(/%2/g, 'AI')
          } else if (id.indexOf('AO') !== -1) {
                  sPrepend += sHTML_meter.replace(/%2/g, 'AO')
          }
          $('#IDpict').prepend( sPrepend );
  
          $('.instrument').clayfy({
              type: 'resizable',
              container: '#IDpict',
              droppable: '#IDpict',
              minSize: [100, 65],
              maxSize: [300, 65],
              top: false,
              bottom: false,
          });
          // level
          $('.instrumentF').clayfy({
  			type: 'resizable',
  			container: '#IDpict',
  			droppable: '#IDpict',
  			minSize: [20, 65],
  			maxSize: [1000, 1000],
          });
          // gauge
          $('.instrumentG').clayfy({
  			type: 'dropable',
  			container: '#IDpict',
  			droppable: '#IDpict',
  			minSize: [65, 65],
  			maxSize: [65, 65],
          });
  
          // sparklines
          $('.peity-ai').peity('line', {
              fill: ['var(--sparkline_ai_fill)'],
              stroke: 'var(--sparkline_ai_stroke)',
              min: 0,
              max: 100,
              width: '100%',
              strokeWidth: 2,
          });
          $('.peity-ao').peity('line', {
              fill: ['var(--sparkline_ao_fill)'],
              stroke: 'var(--sparkline_ao_stroke)',
              min: 0,
              max: 100,
              width: '100%',
              strokeWidth: 2,
          });
  
          $('.donut-ai').peity('donut', {
              fill: ['var(--sparkline_ai_stroke)', "var(--SHMI_widget_bg)"],
              innerRadius: 17,
              radius: 25
          });
          $('.donut-ao').peity('donut', {
              fill: ['var(--sparkline_ao_stroke)', "var(--SHMI_widget_bg)"],
              innerRadius: 17,
              radius: 25
          });
  
          addEvents();
          loadPositions();
      };
      // ======================================================================
      function addInstrumentD(id) {
      	let sPrepend = '';
  
          const sHTML = `<div class="SHMI_drag SHMI_drag_D%2 instrument nobr shadow" title="${id}" id="ID_${id}" style="height:55px">
  						<span>${id}</span>
          				<span id="TS_${id}" class="font-weight-lighter float-right" style="display:inline-block;font-size:x-small;"></span>
  						<br />
  							<div class="mx-auto" style="width:20px; height:15px; margin-top:5px;">
  								<div class="digi_IO">
  									<span class="digi_back"></span>
  									<span id="ID_${id}_D" class="%3" style="left:0"></span>
  								</div>
  							</div>
  					</div>`;
  
          if (id.indexOf('DI') != -1) {
                  sPrepend += sHTML.replace(/%2/g, 'I').replace(/%3/g, "digi_in")
          } else if (id.indexOf('DO') != -1) {
                  sPrepend +=  sHTML.replace(/%2/g, 'O').replace(/%3/g, "digi_out")
          }
          $('#IDpict').prepend( sPrepend );
  
          $('.instrument').clayfy({
              type: 'resizable',
              container: '#IDpict',
              minSize: [50, 50],
              maxSize: [300, 50],
              top: false,
              bottom: false,
          });
  
          addEvents();
          loadPositions();
      };
  
      // ======================================================================
      function updateValues() {
          let val;
          let id;
          let updatingChart;
          let updatingDonut;
          let values;
          let temp;
          let timestamp;
          let colors = []
      	colors[0] = ['#000000']
      	colors[1] = ['var(--SHMI_signal_on)']
      	colors[2] = ['var(--warning)']
      	colors[4] = ['var(--danger)']
      	colors[8] = ['var(--info)']
  
          parent.top.$('#IDdata').find('input').each(function () {
              val = this.value;
              id = this.id;
              timeStamp = dayjs().unix(  parent.top.$(`#${id}_TS_upd`).val() )
  
              $(`#ID_${id}` ).attr('title', id + " | " + dayjs(timeStamp).format('ll HH:mm:ss') );
  
              // digital
              if (id.indexOf('D') != -1) {
  
              	// mini panels (widgets)
  				$(`#ID_${id}_D`).css('opacity', val);
  				if (val > 0 && val < 8)
  					$(`#ID_${id}_D`).css('background-color', colors[val]);
  				else
  					$(`#ID_${id}_D`).css('background-color', "transparent");
  
  				// timestamp
  				if ($(`#ID_${id}`).width() > 60)
  					$(`#TS_${id}` ).text( dayjs(timeStamp).format('HH:mm:ss') );
  				else
  					$(`#TS_${id}` ).text('');
  
  				// SVG
  				if ( (val & 1 | val & 2 | val & 4 ) && val < 8 ) {
  					if (id.indexOf('DO') != -1) {
  						$(`#SHMI_${id}_D`).css("stroke", colors[val]);
  						$(`#SHMI_${id}_D`).css("stroke-width", "3");
  					}
  					if (id.indexOf('DI') != -1) {
  						$(`#SHMI_${id}_D`).css("stroke", colors[val]);
  						$(`#SHMI_${id}_D`).css("stroke-width", "3");
  					}
  				} else if (val == 0) {
  					$(`#SHMI_${id}_D`).css("stroke",colors[0]);
  					$(`#SHMI_${id}_D`).css("stroke-width", "1");
  
  				}
  				/*
  				if ( val == 8 || val == 9)
  					$(`#SHMI_${id}_D`).css("fill", colors[8]);
  				else
  					$(`#SHMI_${id}_D`).css("fill", "transparent");
  				*/
  			}
              // analog ------------------------------------------------------
              else if ( id.indexOf('AI') != -1 || id.indexOf('AO') != -1 ) {
  				$(`#ID_${id}_A`).text(Round(val) + '%');
  				$(`#ID_${id}_S_A`).text(Round(val) + '%');
  				$(`#ID_${id}_M`).css('width', val + '%');
  				$(`#ID_${id}_L_L`).css('height', val + '%');
  				$(`#ID_${id}_L_A`).text(Round(val) + '%');
  
  				// SVG
  				$(`#SHMI_${id}_A`).text(Round(val) + '%');
  
  				// -------------------------------------------------------------
  				val = Math.round(val)
  				// sparklines
  				updatingChart = $(`#ID_${id}_S_spark`).peity('line');
  				values = updatingChart.text().split(',');
  				values.shift();
  				values.push(Round(val, 0));
  
  				updatingChart
  					.text(values.join(','))
  					.change();
  
  				// donut / gauge
  				$(`#ID_${id}_G_A`).text(val);
  
  				updatingDonat = $(`#ID_${id}_G_donut`).peity('donut');
  				updatingDonat
  					.text( val + '/100')
  					.change();
  			}
          });
  
          setTimeout(updateValues, updateInterval);
      };
      $( () => { updateValues(); });
  });