<?php 

session_start();

$message = '';
$volume = '';
$enable_volume_switch = '0';

if(!$_SESSION['login']){
	header("Location: login.php");
}

$show_login_alert = $_SESSION['show_login_alert'];
$_SESSION['show_login_alert'] = '0';

// load config file and read in data
$device_type = '';
$device_id = '';
$device_name = '';
$firmware_version = '';
$serial_number = trim($_ENV['APPLIANCE_SERIAL']);
$device_name_env = trim($_ENV['APPLIANCE_BOARD']);
$device_name_env = str_replace('"','', $device_name_env); // clear double quotes from $_ENV['APPLIANCE_BOARD']

// get mac_address
$mac_search = "/sbin/ifconfig eth0 | grep 'HWaddr'| awk '{ print $5}'";
$mac_address = shell_exec($mac_search);
$mac_address = trim($mac_address);
$mac_address = str_replace(':','', $mac_address); // clear : from mac address
$mac_address = strtoupper($mac_address); // all upper case

if(!$_ENV['APPLIANCE_PART']){
	// show error message
	$message = '<div class="isa_error"><i class="fa fa-times-circle"></i><div class="message_content">';
	$message .= 'There was a problem reading the appliance part number.';
	$message .= '</div></div>';

	$_SESSION['device_type'] = '0';
} else {
	$device_id = trim($_ENV['APPLIANCE_PART']);
	$device_name = 'Nyquist Appliance';

	if($device_id=='nq-voip'){
		$_SESSION['device_id'] = 'nq-voip';
		$_SESSION['pdf'] = 'SpeakerConfigurationManual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-s810v2'){
		$_SESSION['device_id'] = 'nq-s810v2';
		$_SESSION['pdf'] = 'SpeakerConfigurationManualv2.pdf';
		$device_name = $device_name_env;
		if($device_name == 'Nyquist S810V2'){
			$device_name = 'Nyquist S1810V2';
		}
		if($_SESSION['device_type'] == 'Nyquist S810V2'){
			$_SESSION['device_type'] = 'Nyquist S1810V2';
		}
	}
	if(file_exists('/etc/nyquist/wbcdetected')){
		$device_id=='nq-wbc';
		$_SESSION['device_id'] = 'nq-wbc';
		$_SESSION['pdf'] = 'SpeakerConfigurationManualWBC.pdf';
		$device_name = 'NQ-S1810WBC';
		$_SESSION['device_type'] = 'NQ-S1810WBC VoIP Wall Baffle Combo Spkr/Clock/Msg';
	}
	if($device_id=='nq-dev'){
		$_SESSION['device_id'] = 'nq-dev';
		$_SESSION['pdf'] = '';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-mix'){
		$_SESSION['device_id'] = 'nq-mix';
		$_SESSION['pdf'] = 'MixerPreAmpManual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-asb'){
		$_SESSION['device_id'] = 'nq-asb';
		$_SESSION['pdf'] = 'ASBConfigurationManual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-io'){
		$_SESSION['device_id'] = 'nq-io';
		$_SESSION['pdf'] = 'IOControllerConfigurationManual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-ga10p' || $device_id=='nq-ga10pv'){
		$_SESSION['device_id'] = 'nq-ga10p';
		$_SESSION['pdf'] = 'GA10PConfigurationManual.pdf';
		$device_name = $device_name_env;
	}
	if(in_array($device_id, ['NQ-A2060','NQ-A2120','NQ-A2300'])){
		$_SESSION['device_id'] = 'nq-amp2c';
		$_SESSION['pdf'] = '2ChannelAmpManual.pdf';
		$device_name = $device_name_env;
	}
	if(in_array($device_id, ['NQ-A4060','NQ-A4120','NQ-A4300'])){
		$_SESSION['device_id'] = 'nq-amp4c';
		$_SESSION['pdf'] = '4ChannelAmpManual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-ga20p2'){
		$_SESSION['device_id'] = 'nq-ga20p2';
		$_SESSION['pdf'] = 'GA20P2Manual.pdf';
		$device_name = $device_name_env;
	}
	if(in_array($device_id, ['NQ-PA120','NQ-PA240','NQ-PA600'])){
		$_SESSION['device_id'] = 'nq-nqpaxxx';
		$_SESSION['pdf'] = 'PublicAddressAmpManual.pdf';
		$device_name = $device_name_env;
	}
	if(in_array($device_id, ['NQ-A4060-G2','NQ-A4120-G2','NQ-A4300-G2'])){
		$_SESSION['device_id'] = 'nq-amp4c-g2';
		$_SESSION['pdf'] = '4ChannelAmpG2Manual.pdf';
		$device_name = $device_name_env;
	}
	if(in_array($device_id, ['NQ-A2060-G2','NQ-A2120-G2','NQ-A2300-G2'])){
		$_SESSION['device_id'] = 'nq-amp2c-g2';
		$_SESSION['pdf'] = '2ChannelAmpG2Manual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-edp01'){
		$_SESSION['device_id'] = 'nq-edp01';
		$_SESSION['pdf'] = 'EDP01Manual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-ga400p'){
		$_SESSION['device_id'] = 'nq-ga400p';
		$_SESSION['pdf'] = 'GA400PManual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-ga40p3'){
		$_SESSION['device_id'] = 'nq-ga40p3';
		$_SESSION['pdf'] = 'GA40P3Manual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-ser20p2'){
		$_SESSION['device_id'] = 'nq-ser20p2';
		$_SESSION['pdf'] = 'SER20P2Manual.pdf';
		$device_name = $device_name_env;
	}
	if($device_id=='nq-dsc01'){
		$_SESSION['device_id'] = 'nq-dsc01';
		$_SESSION['pdf'] = 'DSC01Manual.pdf';
		$device_name = $device_name_env;
	}
	if($_SESSION['device_name']==''){ // manually set the device_name if it's not avaialble from SIP.config
		$_SESSION['device_name'] = $device_name;	
	}
		
	// set the help button links
	$_SESSION['help_dashboard'] = 'Using_the_Dashboard.htm#CSH_1';
	$_SESSION['help_firmware'] = 'Updating_Firmware.htm#CSH_2';
	$_SESSION['help_network'] = 'Setting_Network_Tab_Parameters.htm#CSH_3';
	$_SESSION['help_configuration'] = 'Setting_Configuration_Tab_Parameters.htm#CSH_4';
	$_SESSION['help_logs'] = 'Accessing_Log_Files.htm#CSH_5';
	$_SESSION['help_dsp'] = 'Setting_DSP_Parameters.htm';

	// new help file links	
	if(in_array($_SESSION["device_id"],['nq-nqpaxxx','nq-mix','nq-amp2c','nq-amp4c','nq-amp2c-g2','nq-amp4c-g2','nq-voip','nq-s810v2','nq-wbc','nq-asb','nq-edp01','nq-ga400p','nq-io','nq-ga20p2','nq-ga10p','nq-ga40p3','nq-ser20p2','nq-dsc01'])){  // PAMA, MMPA, A2XXX G1&G2, A4XXX G1&G2, nq-voip, nq-s810v2, nq-wbc, nq-asb, nq-edp01, nq-ga400p, nq-io, nq-ga20p2, nq-ga10p, nq-ga40p3, nq-ser20p2, nq-dsc01
		
		// xml file path
        $path = "/var/www/html/help/".$_SESSION["device_id"]."/whxdata/csh.js";

        // Read entire file into string
        $xmlfile = file_get_contents($path);

        $xmlfile = str_replace('gXMLBuffer ="','',$xmlfile);
        $xmlfile = str_replace('";','',$xmlfile);
        $xmlfile = str_replace('\\','',$xmlfile);

        // Convert xml string into an object
        $new = simplexml_load_string($xmlfile);

        // Convert into json
        $con = json_encode($new);

        // Convert into associative array
        $newArr = json_decode($con, true);

        foreach($newArr['item'] as $key => $obj){

           //echo '<pre>';
           //var_dump($obj['@attributes']);
           //echo '</pre>';
			
			// dashboard, firmware, network, configuration, Log, DSP

            $mapid =  $obj['@attributes']['mapid'];
            $mapnum = $obj['@attributes']['mapnum'];
            $topicurl = $obj['@attributes']['topicurl'];
			
			if($mapid=='dashboard'){
				$_SESSION['help_dashboard'] = $topicurl;
			}
			if($mapid=='firmware'){
				$_SESSION['help_firmware'] = $topicurl;
			}
			if($mapid=='network'){
				$_SESSION['help_network'] = $topicurl;
			}
			if($mapid=='configuration'){
				$_SESSION['help_configuration'] = $topicurl;
			}
			if($mapid=='Log'){
				$_SESSION['help_logs'] = $topicurl;
			}
			if($mapid=='DSP'){
				$_SESSION['help_dsp'] = $topicurl;
			}
        }
	}
}

// check status of slider_enabled file
if(file_exists('/etc/nyquist/slider_enabled')){
	$enable_volume_switch = '1';
} else {
	$enable_volume_switch = '0';
}
?>

<!doctype html>
<html lang="en">
<head>
<style>

div.led {
	width: 20px;
	height: 20px;
	clip-path: circle(10px at center);
}
.gray {
	background: radial-gradient(circle, rgba(76, 76, 76, 1) 0%, rgba(0, 0, 0, 0) 100%);
}

.green {
	background: radial-gradient(circle, rgba(0, 255, 0, 1) 0%, rgba(0, 150, 0, 1) 100%);
}

.red {
	background: radial-gradient(circle, rgba(255, 0, 0, .5) 0%, rgba(255, 0, 0, 1) 100%);
}

#clip1, #clip2, #protection_status {
	class:"led gray";
}

</style>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="Bogen Communications LLC">
<meta name="copyright" content="Bogen Communications LLC">
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
<link rel="shortcut icon" href="">
<link rel="stylesheet" href="/css/styles.css">
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/bootstrap-toggle.min.css" >
<link rel="icon" type="image/png" href="/favicon.png" />
<title><?php echo $_SESSION['device_type']; ?> (<?php echo $_SESSION['device_name']; ?>) - Dashboard</title>
</head>

<body>
<input id="standalone_mode_saved" name="standalone_mode_saved"  type="hidden" value="<?php if($_SESSION['standalone_mode']=='1'){ echo '1';} else { echo '0';} ?>">
<input id="no_toggle" name="no_toggle" type="hidden" value="0">
<input id="show_login_alert" name="show_login_alert" type="hidden" value="<?php echo $show_login_alert;?>">
<input id="onload" name="onload" type="hidden" value="1">
	
<div class="container">

<?php include 'navbar.php';?>

<h4><strong><i class="fa fa-dashboard"></i> Dashboard</strong>&nbsp;&nbsp;<a href="/help/<?php echo $_SESSION['device_id']; ?>/#t=<?php echo $_SESSION['help_dashboard']; ?>" type="button" class="btn btn-xs btn-primary" target="_blank"><i class="fa fa-question-circle"></i></a></h4>
<div id="status"></div>
<div id="message_container"><?php echo $message; ?></div>
<br>
<table id="index_table" class="table-condensed">
<tr>
<td><strong>Device Type:</strong></td>
<td><input type="text" class="form-control" id="device_name" name="device_name" placeholder="" style="width:200px;" value="<?php echo $device_name; ?>" readonly></td>
<?php if($_SESSION['device_id']=='nq-asb'){ ?>
<td>&nbsp;&nbsp;&nbsp;</td>
<td><strong>Channel 1 Status:</strong></td>
<td><div id="clip1"></div></td>
<? } ?>
</tr>
<tr>
<td><strong>Serial Number:</strong></td>
<td><input type="text" class="form-control" id="serial_number" name="serial_number" placeholder="" style="width:200px;" value="<?php echo $serial_number; ?>" readonly>
<?php if($_SESSION['device_id']=='nq-asb'){ ?>
<td>&nbsp;&nbsp;&nbsp;</td>
<td><strong>Channel 2 Status:</strong></td>
<td><div id="clip2"></div></td>
<? } ?>
</tr>
<tr>
<td><strong>MAC Address:</strong></td>
<td><input type="text" class="form-control" id="mac_address" name="mac_address" placeholder="" style="width:200px;" value="<?php echo $mac_address; ?>" readonly></td>
<?php if($_SESSION['device_id']=='nq-asb'){ ?>
<td>&nbsp;&nbsp;&nbsp;</td>
<td><strong>Protection Status:</strong></td>
<td><div id="protection_status"></div></td>
<? } ?>
</tr>
<tr>
<td><strong>Firmware Version:</strong></td>
<td><input type="text" class="form-control" id="firmware_version" name="firmware_version" placeholder="" style="width:200px;" value="<?php echo $firmware_version; ?>" readonly></td>
<?php if($_SESSION['device_id']=='nq-asb'){ ?>
<td>&nbsp;&nbsp;&nbsp;</td>
<td><strong>Temperature:</strong></td>
<td><span id="temperature"></span></td>
<? } ?>
</tr>
<?php if(in_array($_SESSION['device_id'],['nq-s810v2','nq-wbc','nq-ga10p','nq-ga10pv','nq-dsc01'])) { // show  relay trigger status for VoIP G2/G3, GA10P, GA10PV, nq-dsc01 ?>
<tr>
<td><strong>Relay Trigger Status:</strong></td>
<td><input type="text" class="form-control" id="relay_trigger_status" name="relay_trigger_status" placeholder="" style="width:200px;" value="" readonly></td>
</tr>	
<? } ?>
<?php if(in_array($_SESSION['device_id'],['nq-ga400p'])) { // show  relay trigger status for GA400P ?>
<tr>
<td><strong>Relay Trigger Status 1:</strong></td>
<td><input type="text" class="form-control" id="relay_trigger_status1" name="relay_trigger_status1" placeholder="" style="width:200px;" value="" readonly></td>
</tr>
<tr>
<td><strong>Relay Trigger Status 2:</strong></td>
<td><input type="text" class="form-control" id="relay_trigger_status2" name="relay_trigger_status2" placeholder="" style="width:200px;" value="" readonly></td>
</tr>
<? } ?>
<?php if(in_array($_SESSION['device_id'],['nq-mix','nq-nqpaxxx','nq-amp2c','nq-amp4c','nq-amp2c-g2','nq-amp4c-g2','nq-edp01','nq-s810v2','nq-ga400p','nq-ga40p3','nq-ga20p2','nq-ga10p','nq-ga10pv','nq-ser20p2'])) { // show standalone button for MMPA, PAXXX, A2XXX GX, A4XXX GX amplifiers, EDP01, VoIP Gen2, GA400P, GA40P3, GA20P2, GA10P, GA10PV, SER20P2 ?>
<tr>
<td><strong>Standalone Operation:</strong></td>
<td><input id="standalone_mode" name="standalone_mode" class="form-control" data-on="Enabled" data-off="Disabled" data-toggle="toggle" data-size="small" type="checkbox" value="<?php if($_SESSION['standalone_mode']=='1'){ echo '1';} else { echo '0';} ?>"></td>
</tr>
<? } ?>
</table>
<?php if(in_array($_SESSION['device_id'],['nq-voip','nq-asb','nq-s810v2','nq-wbc','nq-dsc01'])) { // show volume control for the VoIP Speaker, Bridge Device, VoIP Gen2, VoIP Gen3, nq-dsc01 ?>
<br><br>
<strong>Enable/Disable Volume Cut Level Slider:</strong>&nbsp;&nbsp;<a data-toggle="tooltip" title="Allows the user to manually Enable and Disable the Volume Cut Level slider."><i class='fa fa-lg fa-info-circle'></i></a><br>
<input id="enable_volume_switch" name="enable_volume_switch" class="form-control" data-on="Enabled" data-off="Disabled" data-toggle="toggle" data-size="small" type="checkbox" value="<?php echo $enable_volume_switch;?>"><br><br>
<strong>Volume Cut Level (dB):&nbsp;&nbsp;<span id="volumeLabel"></span></strong>&nbsp;&nbsp;<a data-toggle="tooltip" title="This is a temporary adjustment to allow the user to get a sense of loudness in a room/classroom/hallway."><i class='fa fa-lg fa-info-circle'></i></a><br>
<input id="volume" name="volume" type="range" min="-42" max="0" step="1" value="0" style="width:250px;" onChange="volumeChanged()"></input>
<? } ?>	
</div>
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>
<script src="/js/bootstrap-toggle.min.js"></script>
	
<!--  start standalone confirmation modal -->
<div class="modal fade bs-example-modal-sm modal-standalone-confirmation" id="modal-standalone-confirmation" tabindex="-1" role="dialog" aria-labelledby="modal-standalone-confirmation" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
		 <div class="modal-header">      							
			<h4 class="modal-title"><p align="center">Standalone Operation</p></h4>
		</div>
		<div align="left" id="modal-body" class="modal-body">
			<div style="text-align:left; width:100%;">
			<div id="eula_agreement_div">
            <?php if($_SESSION['standalone_mode']=='0'){ ?>
            <strong>End-User License Agreement Review is Required for Standalone Operation:<br><br>
			 <a href="/help/pdfs/Nyquist-EULA.pdf" type="button" class="btn btn-sm btn-default" target="_blank"><i class='fa fa-file-pdf-o'></i>&nbsp;&nbsp;End-User License Agreement (PDF)</a><br><br>
			Do you agree with the End-User License Agreement?</strong><br><br>
            <?php } ?>
			</div>
			<div id="standalone_mode_body_div">
			 <?php if($_SESSION['standalone_mode']=='0'){ ?><strong>End-User License Agreement: YES <font color="green"><i class="fa fa-check-square"></i></font></strong><br><br> <?php } ?>
			When <strong>Standalone Operation is <?php if($_SESSION['standalone_mode']=='1'){ echo 'Disabled';} else { echo 'Enabled';}?></strong> the firmware <strong><?php if($_SESSION['standalone_mode']=='1'){ echo 'Enables';} else { echo 'Disables';}?></strong> code that:<br><br>
				• Fetches device configuration from Nyquist server<br>
				• Registers with Nyquist server (via SIP)<br>
				• Stores backup information to Nyquist server<br>
				• Allows access to Nyquist server-based NTP <br><br>
			<strong>Are you sure you want to make Standalone Operation <?php if($_SESSION['standalone_mode']=='1'){ echo 'Disabled';} else { echo 'Enabled';}?>?</strong>
			</div>	
			</div>
		</div>
		<div id="modal-footer" class="modal-footer">   
		<div id="standalone_mode_footer_div">
			<button type="button" name="noButton" id="noButton" onClick="switch_standalone_back();"  class="btn btn-xs btn-danger" style="min-width:50px;">No</button>
			<button  type="button" name="yesButton" id="yesButton" onClick="switch_standalone();" class="btn btn-xs btn-success" style="min-width:50px;">Yes</button>
		</div>
		<div id="eula_close_div">
			<button type="button" name="noAgreement" id="noAgreement" onClick="switch_standalone_back();"  class="btn btn-xs btn-danger" style="min-width:50px;">No</button>
			<button  type="button" name="yesAgreement" id="yesAgreement" onClick="eula_agreement();" class="btn btn-xs btn-success" style="min-width:50px;">Yes</button>
		</div>
		</div>
</div>  							
</div>
</div>
<!--  end standalone confirmation modal -->
	
<!--  start login_alert_modal -->
<div id="login_alert_modal" class="modal" tabindex="-1" role="dialog" aria-labelledby="login_alert_modal" data-backdrop="static" data-keyboard="false">
	<div class="modal-dialog">
	<div class="modal-content">
			 <div class="modal-header">       							
			<h4 class="modal-title"><p align="center">Warning</p></h4>
			</div>
		<?php 
		$login_alert_text = '';
		if($_SESSION['standalone_mode']=='1'){
			$login_alert_text = 'The default Web Password has not been changed.  This is a security risk.  Please update the Web Password on the Configuration Settings page.';
		} else {
			$login_alert_text = 'The default Web Password has not been changed.  This is a security risk.  Please update the Web Password for '. $_SESSION['device_type'].' ('. $_SESSION['device_name']. ') on the Nyquist server.';
		}
		?>
			<div id="login_alert_text" align="left" class="modal-body"><?php echo $login_alert_text;?></div>
			<div class="modal-footer">        							
				<button type="button" class="btn btn-xs btn-default" data-dismiss="modal" style="min-width:50px;">OK</button>
			</div>
	</div>  							
	</div>
	</div>
<!--  end login_alert_modal -->
	
<!--  start Volume Cut Level modal -->
<div class="modal fade bs-example-modal-sm modal-volume-cut" id="modal-volume-cut" tabindex="-1" role="dialog" aria-labelledby="modal-volume-cut" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
		 <div class="modal-header">      							
			<h4 class="modal-title"><p align="center">Temporary Volume Adjustment Notice</p></h4>
		</div>
		<div align="left" id="modal-body" class="modal-body">
			<div style="text-align:left; width:100%;">
			This volume control is for <strong>temporary adjustments only.</strong><br><br>
            <ul>
                <li>Changes here are valid for <strong>up to 60 minutes,</strong> then will be overwritten.</li>
                <li>Use this slider only for<strong> tuning individual devices in real time </strong>to find a comfortable level.</li>
                <li>For <strong>permanent changes</strong>, update the settings on the <strong>Nyquist Server</strong>.</li>
			</ul>
			</div>
		</div>
		<div id="modal-footer" class="modal-footer">   
			<button type="button" class="btn btn-xs btn-default" data-dismiss="modal" style="min-width:50px;">OK</button>
		</div>
</div>  							
</div>
</div>
<!--  end Volume Cut Level modal -->
	
</body>
</html>
<script>
// on page load

window.onload = function() {  
		
	var device_id = '<?php echo $_SESSION['device_id']; ?>';
	
	// only start the web socket for the ASB
	if(device_id=='nq-asb'){ 
		init_socket(); 
	}
	if(['nq-asb','nq-voip','nq-s810v2','nq-wbc','nq-dsc01'].indexOf(device_id)>-1){
		get_volume();
	}
	get_firmware_status();
	if(['nq-s810v2','nq-wbc','nq-dsc01'].indexOf(device_id)>-1){
		get_relay_trigger_status(1);
		setInterval(function () {
			get_relay_trigger_status(1);
		}, 5000);
	}
	if(['nq-ga10p','nq-ga10pv'].indexOf(device_id)>-1){
		get_relay_trigger_status(2);
		setInterval(function () {
			get_relay_trigger_status(2);
		}, 5000);	
	}
	if(['nq-ga400p'].indexOf(device_id)>-1){
		get_relay_trigger_status(3);
		get_relay_trigger_status(4);
		setInterval(function () {
			get_relay_trigger_status(3);
			get_relay_trigger_status(4);
		}, 5000);	
	}
	$("#clip1").data({timeout:0, value:2, last:[]});
	$("#clip2").data({timeout:0, value:2, last:[]});
	$("#protection_status").data({timeout:0, value:2, last:[]});
	// clear message after 10 seconds
	setTimeout(function(){ 
		document.getElementById("message_container").innerHTML = '';
	}, 3000);
	
	if(['nq-mix','nq-nqpaxxx','nq-amp2c','nq-amp4c','nq-amp2c-g2','nq-amp4c-g2','nq-edp01','nq-s810v2','nq-wbc','nq-ga400p','nq-ga40p3','nq-ga10p','nq-ga10pv','nq-ga20p2','nq-ser20p2','nq-dsc01'].indexOf(device_id)>-1){
	   if(document.getElementById("standalone_mode_saved").value=='1'){
            document.getElementById("no_toggle").value = '1';
            $('#standalone_mode').bootstrapToggle('toggle');
		}
	}
	
	// login alert modal
	if(document.getElementById("show_login_alert").value=='1'){
		// show modal
		$('#login_alert_modal').modal('show');
	}

	// check enable_volume_switch status for specific devices
	if(['nq-voip','nq-asb','nq-s810v2','nq-wbc','nq-dsc01'].indexOf(device_id)>-1){
		
		if(document.getElementById("enable_volume_switch").value=='1'){
			// toggle switch
			$('#enable_volume_switch').bootstrapToggle('toggle');
        } else {
			// disable volume slider
            document.getElementById("volume").disabled = true;
        }

        // allow enable_volume_switch ajax to work after initial possible toggle 
        document.getElementById("onload").value = '0';

        // start checking existence of slider_enabled file every 5 seconds
        var file_check = setInterval(fileCheck, 5000);
	}
}

// web socket
var socket;
var id2class = [ "red", "green", "gray" ];
var sync_timeout;

function init_socket() {
	var host = "wss://" + location.hostname + '/ws';
	try {
		socket = new WebSocket(host);
		console.log('WebSocket - status '+socket.readyState);
		socket.onopen    = function(msg) { 
			console.log("Welcome - status "+this.readyState); 
		};	
		
		socket.onmessage = function(msg) {
			var amp_status = JSON.parse(msg.data);
			var c1_data = $("#clip1").data();
			var c2_data = $("#clip2").data();
			var dis_data = $("#protection_status").data();
			var timeouts  = [];

			var temp = amp_status.temp;

			if ((c1_data.last.length == 0 && c1_data.value != amp_status.clip_ch1) || 
					(amp_status.clip_ch1 != c1_data.last[c1_data.last.length - 1])) {
				c1_data.last.push(amp_status.clip_ch1);
				c1_data.timeout = Math.round(300 / c1_data.last.length);
				timeouts.push(c1_data.timeout);
			}

			if ((c2_data.last.length == 0 && c2_data.value != amp_status.clip_ch2) || 
					(amp_status.clip_ch2 != c2_data.last[c2_data.last.length - 1])) {
				c2_data.last.push(amp_status.clip_ch2);
				c2_data.timeout = Math.round(300 / c2_data.last.length);
				timeouts.push(c2_data.timeout);
			}

			if ((dis_data.last.length == 0 && dis_data.value != amp_status.dis_rp) || 
					(amp_status.dis_rp != dis_data.last[dis_data.last.length - 1])) {
				dis_data.last.push(amp_status.dis_rp);
				dis_data.timeout = Math.round(300 / dis_data.last.length);
				timeouts.push(dis_data.timeout);
			}

			timeouts.sort(function(a, b){return a - b});
			clearTimeout(sync_timeout);
			sync_timeout = setTimeout(resync_LED, timeouts[0], timeouts[0]);
			document.getElementById("temperature").innerHTML = temp + '&#8451;';
		};
		
		socket.onclose   = function(msg) { 
			console.log("Disconnected - status "+this.readyState); 
			$("#clip1").data({timeout:0, value:2, last:[]});
			$("#clip2").data({timeout:0, value:2, last:[]});
			$("#protection_status").data({timeout:0, value:2, last:[]});
			document.getElementById("clip1").setAttribute("class", "led gray");
			document.getElementById("clip2").setAttribute("class", "led gray");
			document.getElementById("protection_status").setAttribute("class", "led gray");
			document.getElementById("temperature").innerHTML = '';
		};
	}
	catch(ex){ 
		console.log(ex); 
	}
}
$('#volume').on('input', function(){
	$("#volumeLabel").text(volume.value);
});

function resync_LED(timeout) {
	var c1_data = $("#clip1").data();
	var c2_data = $("#clip2").data();
	var dis_data = $("#protection_status").data();
	var timeouts  = [];

	if (c1_data.timeout) {
		if ((c1_data.timeout - timeout) > 0) {
			c1_data.timeout -= timeout;
			timeouts.push(c1_data.timeout);
		}
		else {
			c1_data.value = c1_data.last.shift();
			document.getElementById("clip1").setAttribute("class", "led " + id2class[c1_data.value]);
			if (!c1_data.last.length)
				c1_data.timeout = 0;
			else
				timeouts.push(c1_data.timeout);
		}
	}

	if (c2_data.timeout) {
		if ((c2_data.timeout -timeout) > 0) {
			c2_data.timeout -= timeout;
			timeouts.push(c2_data.timeout);
		}
		else {
			c2_data.value = c2_data.last.shift();
			document.getElementById("clip2").setAttribute("class", "led " + id2class[c2_data.value]);
			if (!c2_data.last.length)
				c2_data.timeout = 0;
			else
				timeouts.push(c2_data.timeout);
		}
	}

	if (dis_data.timeout) {
		if ((dis_data.timeout - timeout) > 0) {
			dis_data.timeout -= timeout;
			timeouts.push(dis_data.timeout);
		}
		else {
			dis_data.value = dis_data.last.shift();
			document.getElementById("protection_status").setAttribute("class", "led " + id2class[dis_data.value]);
			if (!dis_data.last.length)
				dis_data.timeout = 0;
			else
				timeouts.push(dis_data.timeout);
		}
	}

	if(timeouts.length) {
		timeouts.sort(function(a, b){return a - b});
		sync_timeout = setTimeout(resync_LED, timeouts[0], timeouts[0]);
	}

}
// get volume
function get_volume(){
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//console.log(xmlhttp.responseText);
				document.getElementById("volume").value = parseInt(xmlhttp.responseText);
				$("#volumeLabel").text(xmlhttp.responseText);	
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=get_volume",true);
   		xmlhttp.send();
}
// save volume
function volumeChanged(){
	
	document.getElementById("status").innerHTML = '<i class="fa fa-refresh fa-spin fa-fw"></i> <strong>Processing ... </strong>';
	
	var volume = document.getElementById("volume");
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//console.log(xmlhttp.responseText);
				
				document.getElementById("status").innerHTML = '';
				document.getElementById("message_container").innerHTML = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">Volume updated.<br></div></div><br>';
				
				// clear message after 10 seconds
				setTimeout(function(){ 
					document.getElementById("message_container").innerHTML = '';
				}, 3000);
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=set_volume&v=" + volume.value,true);
   		xmlhttp.send();
}
function set_volume_control(stream, label){
	
	document.getElementById("status").innerHTML = '<i class="fa fa-refresh fa-spin fa-fw"></i> <strong>Processing ... </strong>';
	
	var volume = document.getElementById(stream);
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//alert(xmlhttp.responseText);
				
				document.getElementById("status").innerHTML = '';
				document.getElementById("message_container").innerHTML = '<div class="isa_success"><i class="fa fa-check"></i><div class="message_content">' + label + ' Updated.<br></div></div><br>';
				
				//clear message after 10 seconds
				setTimeout(function(){ 
					document.getElementById("message_container").innerHTML = '';
				}, 3000);
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=set_volume_control&v=" + volume.value + '&d=' + stream,true);
   		xmlhttp.send();
}
function get_volume_control(stream){
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//alert(xmlhttp.responseText);
				var match = xmlhttp.responseText.match(/\d+/);
				
				var volume = (match[0]);
				document.getElementById(stream).value = volume;
				$("#" + stream + "_label").text(volume);	

        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=get_volume_control&d=" + stream,true);
   		xmlhttp.send();
}
function get_firmware_status(){
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				//alert(xmlhttp.responseText);
				
				var dataArray = xmlhttp.responseText.split("|");
				var old_version = dataArray[0];
				var new_version = dataArray[1];
				
				// set firmware version
				document.getElementById("firmware_version").value = old_version;
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=get_firmware_status",true);
   		xmlhttp.send();
}
function get_relay_trigger_status(device_type){
	
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				// console.log(xmlhttp.responseText);
				var relay_trigger_status;
				if(xmlhttp.responseText==1){
				   relay_trigger_status = 'Active';
				} else {
					 relay_trigger_status = 'Inactive';
				}
				if(device_type==1 || device_type==2){
				   // set firmware version
					document.getElementById("relay_trigger_status").value = relay_trigger_status;
				}
				if(device_type==3){
				   // set firmware version
					document.getElementById("relay_trigger_status1").value = relay_trigger_status;
				}
				if(device_type==4){
				   // set firmware version
					document.getElementById("relay_trigger_status2").value = relay_trigger_status;
				}
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=get_relay_trigger_status&d="+device_type,true);
   		xmlhttp.send();
}
function confirm_standalone(){
	
	$('.modal-standalone-confirmation').modal('show');
	
	var standalone_mode_saved = document.getElementById("standalone_mode_saved").value;
	if(standalone_mode_saved=='0'){
	   document.getElementById('standalone_mode_body_div').style.display = 'none';
	   document.getElementById('standalone_mode_footer_div').style.display = 'none';
	   document.getElementById('eula_agreement_div').style.display = 'block';
	   document.getElementById('eula_close_div').style.display = 'block';
	} else {
		document.getElementById('eula_close_div').style.display = 'none';
	}
}
function switch_standalone_back(){
	
	$('.modal-standalone-confirmation').modal('hide');
	document.getElementById("no_toggle").value = '1';
	$('#standalone_mode').bootstrapToggle('toggle');
}
function switch_standalone(){
	
	document.getElementById("modal-body").innerHTML = '<i class="fa fa-refresh fa-spin fa-fw"></i> Standalone Operation changed to <?php if($_SESSION['standalone_mode']=='1'){ echo 'Disabled';} else { echo 'Enabled';}?>. Logging out...';
	document.getElementById("modal-footer").innerHTML = '';
		
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				// console.log(xmlhttp.responseText);
				
				setTimeout(function(){
        			window.open("index.php", "_self");
    			}, 5000);
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=switch_standalone",true);
   		xmlhttp.send();
}
// standalone_mode 
$(function() {
    $('#standalone_mode').bootstrapToggle();
});
$(function() {
  $('#standalone_mode').change(function() {
	   var no_toggle = document.getElementById("no_toggle").value;
	   if(no_toggle=='0'){
		  confirm_standalone();
	   }
	  document.getElementById("no_toggle").value = '0';
    })
});
// enable_volume_switch 
$(function() {
    $('#enable_volume_switch').bootstrapToggle();
});
$(function() {
  $('#enable_volume_switch').change(function() {
	   var enable_volume_switch = document.getElementById("enable_volume_switch").value;
	   var onload = document.getElementById("onload").value;
	  if(onload==1){
		 // do nothing
	  } else {
		 if(enable_volume_switch=='0'){
             document.getElementById("enable_volume_switch").value = '1';
             enable_disable_volume('1');
			 document.getElementById("volume").disabled = false;
			 $('.modal-volume-cut').modal('show');
         } else {
             document.getElementById("enable_volume_switch").value = '0';
             enable_disable_volume('0');
			 document.getElementById("volume").disabled = true;
         }
	  }
    })
});
function enable_disable_volume(data){
			
	var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				// console.log(xmlhttp.responseText);
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=enable_disable_volume&d="+data,true);
   		xmlhttp.send();
}
function eula_agreement(){
	 document.getElementById('standalone_mode_body_div').style.display = 'block';
	 document.getElementById('standalone_mode_footer_div').style.display = 'block';
 	 document.getElementById('eula_agreement_div').style.display = 'none';
	 document.getElementById('eula_close_div').style.display = 'none';
}
function fileCheck(){
	
	var enable_volume_switch = document.getElementById("enable_volume_switch").value;
	// check for slider_enabled file only if volume switch is enabled on Web-UI
	if(enable_volume_switch=='1'){  
	   var xmlhttp=new XMLHttpRequest();
    	xmlhttp.onreadystatechange=function() {
        	if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				// success 
				// console.log(xmlhttp.responseText);
				if(xmlhttp.responseText=='0'){
				   // reload the page if file is no longer there
				   window.location.reload();
				}
        	}
		}
	 	xmlhttp.open("GET","scripts.php?s=file_check",true);
   		xmlhttp.send();
	}
}
//  tooltip
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})
</script>
