/* APEX JAVASCRIPT FILE */
/* CUSTOMERS UPDATE */

var softwareVersion = "V1.3.5S"

var demoMode = 0;

var worker;
var workerDiscovery;

var defaultLogin = "admin";
var defaultPassword = "admin";

var mainWaitingTime = 3000;

var refreshDataEnable = false;

var runDiscovery = false;
var runSubscription = false;

var discoverySubscription = new Array();

var subscriptionUpdate = 0;
var delayBetweenSubscriptionAfterUpdate = 5;

var loginLocal = 0;
var httpSecure = 0;

var usernameHttp = "admin";
var passwordHttp = "admin";

var streamMinLevelWarning = -60.0

var screenHeight = 0;
var screenWidth = 0;

var screenScrollHeight = 0;

var discoveryWorker = new Array(0);

//HOTSPOT CONFIG 

var hotspotWpaVersionDefault = 2;
var hotspotChannelVersionDefault = 5;

//READBACK
var channelCount = 4;
var channel1Count = 1;
var channel3Count = 3;
var channel16Count = 16;
var moduleCount = 4;
var readBackSolo = new Array(4);
var overviewVuMeterHeight = 30;

var readBackLimiter = new Array();

var readBackLimiterCount = 5
var subscribeEnable = true;
var subscribeEnableDelay = 1000;

var packetLostCount = 0;
var packetLostMax = 10;

var readbackChannel = "a";
var readbackUserRmsLim = "b";
var readbackUserPeakLim = "c";
var readbackSpeakerRmsLim = "d";
var readbackSpeakerPeakLim = "e";
var readbackAmpLim = "f";

var readbackModuleAmpOn = "g";
var readbackModuleTemp = "h";
var readbackModuleAveragePower = "i";
var readbackModuleOvertemp = "j";
var readbackModuleVoltage = "k";

var outOfRangeVoltageValue = 10;

//time in ms
var readbackRefresh = 250;
var timeRefresh = 1000;
//global scale factor db level;
var globalDbScaleFactor = 0;
var discoveryTimer = 5000;
var poolMonitorDelay = 2000;

var readBackDiscovery = new Array();
var readBackStatus = new Array();

//DISCOVERY LIST
var discoveryList = new Array();

var lastCommand = null;
var lastCommands = null;
var delayBetweenCommand = 50;
var delayBetweenCommands = 50;
// var countdown = 0;
var countdownEnable = false;

var wsArray;

var rtWs;

//VAR SOFTWARE UPDATE
var updateFile = null;
var updateTempFile = null;
var fileCheck = false;
var fileChecker = "update.sh";

//OVERVIEW MENU
var labelOverviewChannel = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P"];
var labelOverviewChannel3ch = ["SUB", "B", "LEFT", "RIGHT"];
var labelBridgeOverviewChannel = ["A-B", "C-D", "E-F", "G-H", "I-J", "K-L", "M-N", "O-P"];
var idBridgeChannel = ["12", "34", "56", "78", "910", "1112", "1314", "1516"];
var iconOverviewCount = 7;
var iconOverviewIdList = ["overviewButtonMenuSource", "overviewButtonMenuGain", "overviewButtonMenuDelay", "overviewButtonMenuPeq", "overviewButtonMenuXover", "overviewButtonMenuLimiter", "overviewButtonMenuSpeaker"];
var iconOverviewIconList = ["./img/MixMtx.png", "./img/Gain.png", "./img/Delay.png", "./img/PEQ.png", "./img/XOver.png", "./img/Limiter.png", "./img/Preset.png"];
var iconOverviewLabelList = ["Mixer", "Gain", "Delay", "PEQ", "X-Over", "Limiter", "Speaker"];


//SOURCE
var sourceChannelCount = 4;
var sourceCount = 8;
var sourceName = ["0", "1", "2", "3"];
var sourceAnalogCount = 4;
var sourceNetworkCount = 4;
var sourceStreamCount = 2;
var sourceDefaultLabel = ["Channel 1", "Channel 2", "Channel 3", "Channel 4"];
var sourceCurrentLabel = ["", "", "", ""];
var sourcePrimaryDefaultValue = [4, 5, 6, 7];
var sourceSecondaryDefaultValue = [0, 1, 2, 3];
var sourceAnalogLabel = "Analog ";
var sourceAnalogLabelShort = "AN";
var sourceNetworkLabel = "Network ";
var sourceNetworkLabelShort = "NW";
var sourceStreamLabel = "Stream ";
var sourceStreamLabelShort = "ST";

var sourceOverviewLabel = ["AN-A", "AN-B", "AN-C", "AN-D", "NW 1", "NW 2", "NW 3", "NW 4", "ST L", "ST R", "Sine", "Pink N."];
var source1ChOverviewLabel = ["Analog", "AN-B", "AN-C", "AN-D", "NW 1", "NW 2", "NW 3", "NW 4", "ST L", "ST R", "Sine", "Pink N."];

//SIGNAL GENERATOR 
var freqGenFrequencyMin = 30;
var freqGenFrequencyMax = 10000;
var freqGenGainMin = -50.0;
var freqGenGainMax = -20.0;
var pinkNoiseGainMin = -50.0;
var pinkNoiseGainMax = -10.0;

//MIXER
var maxMixerInput = 12;

//GAIN
var gainScaleMin = -80.0;
var gainScaleMax = 15.0;

//DELAY
var delayScaleMin = 0.0;
var delayScaleMax = 250.0;
var speedOfSound = 342 // m/s
var delayMeterScaleMin = 0.0;
var delayMeterScaleMax = 85.5;

//PEQ
var eqCount = 12; //MAX EQ PER CANAL
var eqEnaDefault = false;
var eqFreqDefault = 1000.0;
var eqFreqDefaultInit = [50, 100, 200, 300, 400, 500, 1000, 2000, 3000, 4000, 5000, 10000];
var eqGainDefault = 0.0;
var eqQDefault = 2.5;
var eqBwDefault = 0.573;

var eqTypeDefault = 0;
var eqXLockDefault = false;
var eqYLockDefault = false;

var gain_scalePEQ = new Array(3);
gain_scalePEQ[0] = [6, 3, 0, -3, -6];
gain_scalePEQ[1] = [18, 12, 6, 0, -6, -12, -18];
gain_scalePEQ[2] = [18, 12, 6, 0, -6, -12, -18, -24, -30, -36];
var gain_scalePEQ_line = new Array(3);
gain_scalePEQ_line[0] = [6, 4.5, 3, 1.5, 0, -1.5, -3, -4.5, -6];
gain_scalePEQ_line[1] = [18, 15, 12, 9, 6, 3, 0, -3, -6, -9, -12, -15, -18];
gain_scalePEQ_line[2] = [18, 12, 6, 0, -6, -12, -18, -24, -30, -36];

var phase_scale = new Array(2);
phase_scale[0] = [180, 90, 0, -90, -180];
phase_scale[1] = [720, 360, 0, -360, -720];
var phase_scale_line = new Array(2);
phase_scale_line[0] = [180, 135, 90, 45, 0, -45, -90, -135, -180];
phase_scale_line[1] = [720, 540, 360, 180, 0, -180, -360, -540, -720];

var typeScaleMinPEQ = 0;
var typeScaleMaxPEQ = 15;

var freqScaleMinPEQ = 10;
var freqScaleMaxPEQ = 22000;
var freqScaleStepPEQ = 1;
var freqScaleLabelPEQ = "Hz";

var gainScaleMinPEQ = -40.0;
var gainScaleMaxPEQ = 15.0;
var gainScaleStepPEQ = 0.1;
var gainScaleLabelPEQ = "dB";

var qScaleMin = 0.1;
var qScaleMax = 48.0;
var qScaleStep = 0.01;
var qScaleLable = "";

var qScaleMinPEQ = 0.1;
var qScaleMaxPEQ = 48.0;

var bwScaleMin = 0.03;
var bwScaleMax = 6.5;

var fS = 48000;

var widgetPEQX = 1200;
var widgetPEQY = 800;

var widgetPEQMarginLeft = 35;
var widgetPEQMarginRight = 10;
var widgetPEQMarginRightDual = 35;
var widgetPEQMarginTop = 15;
var widgetPEQMarginBottom = 25;
var graphPEQHeight = 0;
var graphPEQWidth = 0;

var widgetPEQMainXLock = false;
var widgetPEQMainYLock = false;
var widgetPEQMainQLock = false;

var yZeroPEQ = 0;

var defaultMaxViewFreqPEQ = 24000;

var scale = (Math.log10(defaultMaxViewFreqPEQ) - 1);

var peqLabelCount = 16;
var peqLabelShort = ["Bell-Sym",
    "Bell-ASym",
    "Notch",
    "Low-Shel 6dB/o",
    "Low-Shel 12dB/o",
    "High-Shel 6dB/o",
    "High-Shel 12dB/o",
    "All-Pass 90°",
    "All-Pass 180°",
    "H-P 6dB/o",
    "H-P 12dB/o",
    "H-P VarQ 12dB/o",
    "Low-P 6dB/o",
    "Low-P 12dB/o",
    "L-P VarQ 12dB/o",
    "Band-Pass"
];

var peqLabel = ["Bell-Sym",
    "Bell-ASym",
    "Notch",
    "Low-Shel 6dB/oct",
    "Low-Shel 12dB/oct",
    "High-Shel 6dB/oct",
    "High-Shel 12dB/oct",
    "All-Pass 90°",
    "All-Pass 180°",
    "High-Pass 6dB/oct",
    "High-Pass 12dB/oct",
    "High-Pass VariQ 12dB/oct",
    "Low-Pass 6dB/oct",
    "Low-Pass 12dB/oct",
    "Low-Pass VariQ 12dB/oct",
    "Band-Pass"
];

var peqSelectedModalType = 0;

var peqViewMode = 0;
var peqGainScaleType = 2;
var peqPhaseScaleType = 0;

var peqTabMagX = new Array(eqCount);
var peqTabPhaX = new Array(eqCount);

var eqParam = { ena: eqEnaDefault, frequency: eqFreqDefault, gain: eqGainDefault, q: eqQDefault, type: eqTypeDefault, a: {}, b: {}, xLock: eqXLockDefault, yLock: eqYLockDefault };

var arrayEqParam = null;

var eqParamDraggable = new Object();
var arrayEqParamDraggable = new Array();
var peqDrag = [];
var peqDraggie = [];

var peqSoloSelected = 0;

// XOVER
var xoverCount = 2; //draggable stuff
var xoverEnaDefault = false;

var gain_scaleXOVER = new Array(4);
gain_scaleXOVER[0] = [12, 9, 6, 3, 0, -3, -6, -9, -12];
gain_scaleXOVER[1] = [24, 18, 12, 6, 0, -6, -12, -18, -24];
gain_scaleXOVER[2] = [48, 36, 24, 12, 0, -12, -24, -36, -48];
gain_scaleXOVER[3] = [120, 90, 60, 30, 0, -30, -60, -90, -120];
var gain_scaleXOVER_line = new Array(4);
gain_scaleXOVER_line[0] = [12, 9, 6, 3, 0, -3, -6, -9, -12];
gain_scaleXOVER_line[1] = [24, 18, 12, 6, 0, -6, -12, -18, -24];
gain_scaleXOVER_line[2] = [48, 36, 24, 12, 0, -12, -24, -36, -48];
gain_scaleXOVER_line[3] = [120, 90, 60, 30, 0, -30, -60, -90, -120];

var widgetXOVERX = 1200;
var widgetXOVERY = 800;
var widgetXOVERMarginLeft = 35;
var widgetXOVERMarginRight = 10;
var widgetXOVERMarginRightDual = 35;
var widgetXOVERMarginTop = 15;
var widgetXOVERMarginBottom = 25;
var graphXOVERHeight = 0;
var graphXOVERWidth = 0;
var widgetXOVERMainXLock = false;
var widgetXOVERMainYLock = false;
var widgetXOVERMainQLock = false;
var yZeroXOVER = 0;
var defaultMaxViewFreqPEQXOVER = 24000;
var scale = (Math.log10(defaultMaxViewFreqPEQ) - 1);

var highPassDefaultFrequency = 100;
var lowPassDefaultFrequency = 1000;
var highPassDefaultType = 3;
var lowPassDefaultType = 5;

var xoverTabMagX = new Array(xoverCount);
var xoverTabPhaX = new Array(xoverCount);


var xoverDefaultViewMode = 0;

var xoverGainScaleType = 2;
var xoverDefaultGainScaleType = 2;

var xoverPhaseScaleType = 1;
var xoverDefaultPhaseScaleType = 1;

var typeScaleMinXOVER = 0;
var typeScaleMaxXOVER = 18;

var highPassEqParam = { ena: eqEnaDefault, frequency: eqFreqDefault, gain: eqGainDefault, q: eqQDefault, type: eqTypeDefault, a: {}, b: {}, xLock: eqXLockDefault, yLock: eqYLockDefault };
var lowPassEqParam = { ena: eqEnaDefault, frequency: eqFreqDefault, gain: eqGainDefault, q: eqQDefault, type: eqTypeDefault, a: {}, b: {}, xLock: eqXLockDefault, yLock: eqYLockDefault };

// var arrayEqParam = null;

var eqParamDraggable = new Object();

var highPassDraggable;
var lowPassDraggable;

var highPassDrag;
var lowPassDrag;

var highPassDraggie;
var lowPassDraggie;

//19 XOVER AVAILABLE
var xoverLabel = ["Butterworth 6dB/oct",
    "Butterworth 12dB/oct",
    "Butterworth 18dB/oct",
    "Butterworth 24dB/oct",
    "Butterworth 30dB/oct",
    "Butterworth 36dB/oct",
    "Butterworth 42dB/oct",
    "Butterworth 48dB/oct",
    "Linkwitz-Riley 12dB/oct",
    "Linkwitz-Riley 24dB/oct",
    "Linkwitz-Riley 36dB/oct",
    "Linkwitz-Riley 48dB/oct",
    "Bessel 12dB/oct",
    "Bessel 18dB/oct",
    "Bessel 24dB/oct",
    "Bessel 30dB/oct",
    "Bessel 36dB/oct",
    "Bessel 42dB/oct",
    "Bessel 48dB/oct",
]

//LIMITER
var limiterRmsThresDefault = -0.7;
var rmsThresScaleMin = 10;
var rmsThresScaleMax = 130;

var limiterRmsAttackDefault = 20;
var rmsAttackScaleMin = 0.1;
var rmsAttackScaleMax = 6000;


var limiterRmsReleaseDefault = 320.0;
var rmsReleaseScaleMin = 5.0;
var rmsReleaseScaleMax = 10000;

var limiterPeakThresDefault = -1.9;
var peakThresScaleMin = 10;
var peakThresScaleMax = 180;

var limiterPeakReleaseDefault = 320.0;
var peakReleaseScaleMin = 5.0;
var peakReleaseScaleMax = 500;

var loadTable = [2.0, 2.7, 4, 8, 16, 70, 100];

var rmsThresScaleMinPreset = -17
    // var rmsThresScaleMaxPreset = -0.7
    // var rmsThresScaleMaxPreset = 5.3
var rmsThresScaleMaxPreset = 11
var peakThresScaleMinPreset = -21
    // var peakThresScaleMaxPreset = -1.9
var peakThresScaleMaxPreset = 4.1
var peakThresScaleMaxPreset = 11

//SPEAKER

var soloFolderSpeakerSelected = 0;
var soloFileSpeakerSelected = 0;

var demoFolderCount = 5;
var demoFileMaxCount = 15;

var speakerPresetExtension = ".cpspkr";
var speakerFolderPresetExtension = ".cpspkrfr";
var globalPresetExtension = ".cpglob";
var downloadSpeakerPresetName = "";

var updateJsonFile = "";
var updateJsonName = "";
var updateJsonStatus = 0;

//FIR
var firSize = 768;
var firLengthMin = 32;
var firLengthMax = 768;
var firScaleMin = -1;
var firScaleMax = 1;

//DATA 
var arrayAmplifier;
var arrayGroup;
var arrayGroupData;

var listFolder = "";

//GROUP ASSIGN
var groupAssignAmplifier = 0;
var groupAssigneChannel = 0;
var groupAssigneChannelLabelMaxLength = 16
var groupLabelMaxLength = 12
var groupButtonLabelMaxLength = 9

//AMPLIFIER COUNT FOR DEMO
var arrayAmpSizeDemo = 5;

var groupCount = 6;

var soloChannelSelected = 0;

var soloAmplifierSelected = 0;
var groupAssignAmplifierSelected = 0;

var groupGroupSelected = 0;
var groupGroupPanel = 0;
// 0 = GAIN, 1 = DELAY, 2 = PEQ

var displaySoloGroup = 0; //0 FOR SOLO & 1 FOR GROUP

//GLOBAL PRESET

var channel16PresetTimeOut = 45000;
var channel4PresetTimeOut = 10000;
var channel1PresetTimeOut = 8000;

//RESET ALL
var resetAllTimeOut = 60000;

var soloFolderGlobalSelected = 0;
var soloFileGlobalSelected = 0;

var globalPresetCreateFolderAction = "Create Folder";
var globalPresetRenameFolderAction = "Rename Folder";
var globalPresetDeleteFolderAction = "Delete Folder";
var globalPresetDeleteFolderProtectedAction = "No Action"

var globalPresetCreatePresetAction = "Create Preset";
var globalPresetEditPresetAction = "Save Preset";
var globalPresetRenamePresetAction = "Rename Preset";
var globalPresetSaveAsPresetAction = "Save As Preset";
var globalPresetDeletePresetAction = "Delete Preset";
var globalPresetDeletePresetProtectedAction = "No Action";
var globalPresetLoadPresetAction = "Load Preset";

var ws = null;

var cmd_get_solo_mute = "get_solo_mute";
var cmd_set_speaker_mute = "set_solo_mute";
var cmd_get_solo_gain = "get_solo_gain";
var cmd_get_solo_polarity = "get_solo_polarity";
var cmd_get_solo_delay_enable = "get_solo_delay_enable";
var cmd_get_solo_delay_value = "get_solo_delay_value";
var cmd_get_solo_peq_enable = "get_solo_peq_enable";
var cmd_get_solo_peq_type = "get_solo_peq_type";
var cmd_get_solo_peq_freq = "get_solo_peq_freq";
var cmd_get_solo_peq_gain = "get_solo_peq_gain";
var cmd_get_solo_peq_q = "get_solo_peq_q";

var cmd_get_solo_xover_hp_enable = "get_solo_xover_hp_enable";
var cmd_get_solo_xover_hp_type = "get_solo_xover_hp_type";
var cmd_get_solo_xover_hp_freq = "get_solo_xover_hp_freq";
var cmd_get_solo_xover_lp_enable = "get_solo_xover_lp_enable";
var cmd_get_solo_xover_lp_type = "get_solo_xover_lp_type";
var cmd_get_solo_xover_lp_freq = "get_solo_xover_lp_freq";
var cmd_get_solo_lim_rms_thres = "get_solo_lim_rms_thres";
var cmd_get_solo_lim_rms_attack = "get_solo_lim_rms_attack";
var cmd_get_solo_lim_rms_release = "get_solo_lim_rms_release";
var cmd_get_solo_lim_peak_thres = "get_solo_lim_peak_thres";
var cmd_get_solo_lim_peak_release = "get_solo_lim_peak_release";
var cmd_get_solo_channel_source_pri = "get_solo_channel_source_pri";
var cmd_get_solo_channel_source_sec = "get_solo_channel_source_sec";
var cmd_get_solo_channel_mixer_gain = "get_solo_channel_mixer_gain";

var cmd_get_solo_channel_name = "get_solo_channel_name";

var cmd_get_speaker_preset_folder_names = "get_speaker_preset_folder_names";
var cmd_get_speaker_preset_file_names = "get_speaker_preset_file_names";
var cmd_get_speaker_preset_file = "get_speaker_preset_file";
var cmd_get_speaker_preset_list_names = "get_speaker_preset_list_names";

//VARIANT5 AND VARIANT6 SPEAKER PRESET COMMANDS
var cmd_get_all_speaker_preset_folder_names = "get_all_speaker_preset_folder_names";
var cmd_get_all_speaker_preset_file_names = "get_all_speaker_preset_file_names";
var cmd_get_all_speaker_preset_file = "get_all_speaker_preset_file";
var cmd_get_all_speaker_preset_list_names = "get_all_speaker_preset_list_names";

var cmd_get_global_preset_folder_names = "get_global_preset_folder_names";
var cmd_get_global_preset_file_names = "get_global_preset_file_names";

var cmd_set_solo_mute = "set_solo_mute";
var cmd_set_solo_gain = "set_solo_gain";
var cmd_set_solo_polarity = "set_solo_polarity";
var cmd_set_solo_delay_enable = "set_solo_delay_enable";
var cmd_set_solo_delay_value = "set_solo_delay_value";
var cmd_set_solo_peq_enable = "set_solo_peq_enable";
var cmd_set_solo_peq_type = "set_solo_peq_type";
var cmd_set_solo_peq_freq = "set_solo_peq_freq";
var cmd_set_solo_peq_gain = "set_solo_peq_gain";
var cmd_set_solo_peq_q = "set_solo_peq_q";
var cmd_set_solo_peq = "set_solo_peq";

var cmd_set_solo_xover_hp_enable = "set_solo_xover_hp_enable";
var cmd_set_solo_xover_hp_freq = "set_solo_xover_hp_freq";
var cmd_set_solo_xover_hp_type = "set_solo_xover_hp_type";
var cmd_set_solo_xover_lp_enable = "set_solo_xover_lp_enable";
var cmd_set_solo_xover_lp_freq = "set_solo_xover_lp_freq";
var cmd_set_solo_xover_lp_type = "set_solo_xover_lp_type";
var cmd_set_solo_lim_rms_thres = "set_solo_lim_rms_thres";
var cmd_set_solo_lim_rms_attack = "set_solo_lim_rms_attack";
var cmd_set_solo_lim_rms_release = "set_solo_lim_rms_release";
var cmd_set_solo_lim_peak_thres = "set_solo_lim_peak_thres";
var cmd_set_solo_lim_peak_release = "set_solo_lim_peak_release";
var cmd_set_solo_channel_source_pri = "set_solo_channel_source_pri";
var cmd_set_solo_channel_source_sec = "set_solo_channel_source_sec";
var cmd_set_solo_channel_mixer_gain = "set_solo_channel_mixer_gain";
var cmd_set_solo_channel_name = "set_solo_channel_name";

var cmd_get_group_mute = "get_group_mute";
var cmd_get_group_gain = "get_group_gain";
var cmd_get_group_polarity = "get_group_polarity";
var cmd_get_group_delay_enable = "get_group_delay_enable";
var cmd_get_group_delay_value = "get_group_delay_value";
var cmd_get_group_peq_enable = "get_group_peq_enable";
var cmd_get_group_peq_type = "get_group_peq_type";
var cmd_get_group_peq_freq = "get_group_peq_freq";
var cmd_get_group_peq_gain = "get_group_peq_gain";
var cmd_get_group_peq_q = "get_group_peq_q";
var cmd_get_group_name = "get_group_name";

var cmd_set_group_mute = "set_group_mute";
var cmd_set_group_gain = "set_group_gain";
var cmd_set_group_polarity = "set_group_polarity";
var cmd_set_group_delay_enable = "set_group_delay_enable";
var cmd_set_group_delay_value = "set_group_delay_value";
var cmd_set_group_peq_enable = "set_group_peq_enable";
var cmd_set_group_peq_type = "set_group_peq_type";
var cmd_set_group_peq_freq = "set_group_peq_freq";
var cmd_set_group_peq_gain = "set_group_peq_gain";
var cmd_set_group_peq_q = "set_group_peq_q";
var cmd_set_group_peq = "set_group_peq";
var cmd_set_group_name = "set_group_name";

var cmd_get_assign_channel_to_group = "get_assign_channel_to_group";
var cmd_set_assign_channel_to_group = "set_assign_channel_to_group";


var cmd_start_readback = "start_readback";
var cmd_stop_readback = "stop_readback";
var cmd_get_readback = "get_readback";

var cmd_software_update = "software_update";

var cmd_create_speaker_preset_file = "create_speaker_preset_file";
var cmd_upload_speaker_preset_file = "upload_speaker_preset_file";
var cmd_delete_speaker_preset_file = "delete_speaker_preset_file";
var cmd_edit_speaker_preset_file = "edit_speaker_preset_file";
var cmd_set_speaker_preset_file = "set_speaker_preset_file";
var cmd_set_label_speaker_preset_file = "set_label_speaker_preset_file";
var cmd_rename_speaker_preset_file = "rename_speaker_preset_file";
var cmd_create_speaker_preset_folder = "create_speaker_preset_folder";
var cmd_delete_speaker_preset_folder = "delete_speaker_preset_folder";
var cmd_rename_speaker_preset_folder = "rename_speaker_preset_folder";

var cmd_get_speaker_preset_files_from_folder = "get_speaker_preset_files_from_folder"
var cmd_set_speaker_preset_files_from_folder = "set_speaker_preset_files_from_folder"

var cmd_get_all_speaker_preset_files_from_folder = "get_all_speaker_preset_files_from_folder"
var cmd_set_all_speaker_preset_files_from_folder = "set_all_speaker_preset_files_from_folder"

//VARIANT5 AND VARIANT6 SPEAKER PRESET COMMANDS
var cmd_create_all_speaker_preset_file = "create_all_speaker_preset_file";
var cmd_upload_all_speaker_preset_file = "upload_all_speaker_preset_file";
var cmd_delete_all_speaker_preset_file = "delete_all_speaker_preset_file";
var cmd_edit_all_speaker_preset_file = "edit_all_speaker_preset_file";
var cmd_set_all_speaker_preset_file = "set_all_speaker_preset_file";
var cmd_rename_all_speaker_preset_file = "rename_all_speaker_preset_file";
var cmd_create_all_speaker_preset_folder = "create_all_speaker_preset_folder";
var cmd_delete_all_speaker_preset_folder = "delete_all_speaker_preset_folder";
var cmd_rename_all_speaker_preset_folder = "rename_all_speaker_preset_folder";

var cmd_create_global_preset_file = "create_global_preset_file";
var cmd_delete_global_preset_file = "delete_global_preset_file";
var cmd_edit_global_preset_file = "edit_global_preset_file";
var cmd_get_global_preset_file = "get_global_preset_file";
var cmd_set_global_preset_file = "set_global_preset_file";
var cmd_rename_global_preset_file = "rename_global_preset_file";
var cmd_create_global_preset_folder = "create_global_preset_folder";
var cmd_delete_global_preset_folder = "delete_global_preset_folder";
var cmd_rename_global_preset_folder = "rename_global_preset_folder";
var cmd_upload_global_preset_file = "upload_global_preset_file";

var cmd_get_json_data = "get_json_data";

var cmd_get_neighbour_list = "get_neighbour_list";
var cmd_set_clear_neighbour_list = "clear_neighbour_list";

var cmd_hotspot_enable = "hotspot_enable";
var cmd_set_hotspot_config = "set_hotspot_config";
var cmd_set_local_description = "set_local_description";
var cmd_set_bridge_mode_12 = "set_bridge_mode_12";
var cmd_set_bridge_mode_34 = "set_bridge_mode_34";
var cmd_set_bridge_mode_56 = "set_bridge_mode_56";
var cmd_set_bridge_mode_78 = "set_bridge_mode_78";
var cmd_set_bridge_mode_910 = "set_bridge_mode_910";
var cmd_set_bridge_mode_1112 = "set_bridge_mode_1112";
var cmd_set_bridge_mode_1314 = "set_bridge_mode_1314";
var cmd_set_bridge_mode_1516 = "set_bridge_mode_1516";
var cmd_get_bridge_mode_12 = "get_bridge_mode_12";
var cmd_get_bridge_mode_34 = "get_bridge_mode_34";
var cmd_get_bridge_mode_56 = "get_bridge_mode_56";
var cmd_get_bridge_mode_78 = "get_bridge_mode_78";
var cmd_get_bridge_mode_910 = "get_bridge_mode_910";
var cmd_get_bridge_mode_1112 = "get_bridge_mode_1112";
var cmd_get_bridge_mode_1314 = "get_bridge_mode_1314";
var cmd_get_bridge_mode_1516 = "get_bridge_mode_1516";
var cmd_get_lan_config = "get_lan_config";
var cmd_set_lan_config = "set_lan_config";
var cmd_get_apex_cloud = "get_apex_cloud";
var cmd_set_apex_cloud = "set_apex_cloud";
var cmd_get_spotify_config = "get_spotify_config";
var cmd_set_spotify_config = "set_spotify_config";
var cmd_get_airplay_config = "get_airplay_config";
var cmd_set_airplay_config = "set_airplay_config";
var cmd_get_about = "get_about";
var cmd_set_hiz_filter = "set_hiz_filter";
var cmd_get_hiz_filter = "get_hiz_filter";
var cmd_set_amp_stage_disable = "set_amp_stage_disable";

var cmd_set_freq_gen_frequency = "set_freq_gen_frequency";
var cmd_set_freq_gen_gain = "set_freq_gen_gain";
var cmd_set_pink_gen_gain = "set_pink_gen_gain";

var cmd_eth_dhcp = "eth_dhcp";
var cmd_eth_static = "eth_static";

var cmd_close_ws = "close_ws";
var cmd_ipc_error = "ipc_error";

var defautPresetLogin = "admin";
var defautPresetPassword = "CPPresetCreator";

var presetKey = "CPPresetKey";

var ws = null;
var command = null;

var cmd_status = [0, 1, 2, 3, 4, 5, 6, 7]; //0 : set || 1 : sent || 2 : response || 3 : close || 4 : resend (first try) || 5 : resend (second try) || 6 : resend (third try) || 7 : fail
var cmd_status_label = ["set", "sent", "response", "close", "resend (first try)", "resend (second try)", "resend (third try)", "fail"];

var ws_ip = "127.0.0.1";
var ws_port = "5678";

var request_pool = new Array();

var cmd_set_speaker_mute = "set_solo_mute";
var cmd_set_speaker_gain = "set_speaker_gain";
var cmd_set_speaker_polarity = "set_speaker_polarity";
var cmd_set_speaker_delay_enable = "set_speaker_delay_enable";
var cmd_set_speaker_delay_value = "set_speaker_delay_value";
var cmd_set_speaker_peq_enable = "set_speaker_peq_enable";
var cmd_set_speaker_peq_type = "set_speaker_peq_type";
var cmd_set_speaker_peq_freq = "set_speaker_peq_freq";
var cmd_set_speaker_peq_gain = "set_speaker_peq_gain";
var cmd_set_speaker_peq_q = "set_speaker_peq_q";

var cmd_set_speaker_xover_hp_enable = "set_speaker_xover_hp_enable";
var cmd_set_speaker_xover_hp_freq = "set_speaker_xover_hp_freq";
var cmd_set_speaker_xover_hp_type = "set_speaker_xover_hp_type";
var cmd_set_speaker_xover_lp_enable = "set_speaker_xover_lp_enable";
var cmd_set_speaker_xover_lp_freq = "set_speaker_xover_lp_freq";
var cmd_set_speaker_xover_lp_type = "set_speaker_xover_lp_type";
var cmd_set_speaker_fir_table = "set_speaker_fir_table";
var cmd_set_speaker_lim_rms_thres = "set_speaker_lim_rms_thres";
var cmd_set_speaker_lim_rms_attack = "set_speaker_lim_rms_attack";
var cmd_set_speaker_lim_rms_release = "set_speaker_lim_rms_release";
var cmd_set_speaker_lim_peak_thres = "set_speaker_lim_peak_thres";
var cmd_set_speaker_lim_peak_release = "set_speaker_lim_peak_release";
var cmd_set_speaker_channel_source_pri = "set_speaker_channel_source_pri";
var cmd_set_speaker_channel_source_sec = "set_speaker_channel_source_sec";

var cmd_get_xover_hp_freq_from_preset = "get_xover_hp_freq_from_preset";
var cmd_get_xover_lp_freq_from_preset = "get_xover_lp_freq_from_preset";

var cmd_oem_get_status = "oem_get_status";
var cmd_oem_remove_code = "oem_remove_code";
var cmd_oem_check_code = "oem_check_code";
var cmd_oem_set_code = "oem_set_code";

var cmd_get_front_lock = "get_front_lock";
var cmd_set_front_lock = "set_front_lock";
var cmd_run_locate = "run_locate";
var cmd_reset_factory = "reset_factory";
var cmd_reset_audio = "reset_audio";

//STATUS

var moduleTempGood = 65
var moduleTempWarning = 70

////////////////////////////apex_v0_add.js import////////////////////////////

var winHeightFader = 0;
var winHeightFaderLimiter = 0;

var winWidth = 0;
var winHeightVuMeter = 0;
var labelFader = [-80, -70.0, -60.0, -50.0, -40.0, -30.0, -20.0, -10.0, 0.0, 10.0, 15.0];
var labelFaderMixer = [-80.0, -70.0, -60.0, -50.0, -40.0, -30.0, -20.0, -10.0, 0.0, 10.0, 15.0];
var labelFaderMark = [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0];
var labelVuMeter = [-60.0, -50.0, -45.0, -40.0, -35.0, -30.0, -25.0, -20.0, -19.0, -18.0, -17.0, -16.0, -15.0, -14.0, -13.0, -12.0, -11.0, -10.0, -9.0, -8.0, -7.0, -6.0, -5.0, -4.0, -3.0, -2.0, -1.0, 0.0];
var labelGRVuMeter = [60.0, 50.0, 45.0, 40.0, 35.0, 30.0, 25.0, 20.0, 19.0, 18.0, 17.0, 16.0, 15.0, 14.0, 13.0, 12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0, 0.0];
var labelVuMeterMark = [1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
var labelDelay = [0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 150.0, 200.0, 250.0];
var labelDelayMark = [1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1];

var counts = [0, 0, 0];

var freq_scale = [10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000];
var freq_scale_text = ["10", "20", "50", "100", "200", "500", "1k", "2k", "5k", "10k", "20k"];
var freq_scale_line = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000];

// XOVER
var xtabPhaX = new Array(eqCount);

function commandConstructor() {
    this.command = null;
    this.query_arg1 = null;
    this.query_arg2 = null;
    this.query_arg3 = null;
    this.query_arg4 = null;

    this.response_arg1 = null;
    this.response_arg2 = null;

    this.status = 0;
    this.query_time = Date.now();
    this.query_id = 0;
}

//SPEAKER PRESET

var defaultFolderCount = 1;
var defaultFileCount = 0;

var defaultFolderName = "defaultFolder";
var defaultFileName = "defaultFile";
var defaultVersionName = "1.0";
var defaultDesc = "Pass through";

var protectedFolderName = "Default Folder";
var protectedPresetName = "Default Preset";

var protectedFolderOEMName = "OEM Folder";
var protectedPresetOEMName = "OEM Flat Preset";
var protectedFolderSpeakerOEMName = "OEM1234";

var protectedSpeakerFolderName = "Factory Folder";
var protectedSpeakerPresetName = "Blank Preset";

var channelCount = 4;
var peqCount = 12;

//COPY CHANNEL PARAMETERS 

var cmd_set_copy_channel_parameters = "set_copy_channel_parameters";

//OVERIDE TOSTRING FUNCTION TO DISPLAY COMMAND CONSTRUCTOR
commandConstructor.prototype.toString = function() {
    return "COMMAND : " + this.command + " // Arg1 : " + this.query_arg1 + " // Arg2 : " + this.query_arg2 + " // Arg3 : " + this.query_arg3 + " // Arg4 : " + this.query_arg4 + " // R Arg1 : " + this.response_arg1 + " // R Arg2 : " + this.response_arg2 + " // STATUS " + cmd_status_label[this.status] + " // TIMESTAMP : " + this.query_id;
}

function findWithAttr(array, attr, value, cmd) {
    let ret = -1;
    let tmp = 0;
    let retCount = 0;
    let tmp2 = -1;
    for (var i = 0; i < array.length; i++) {
        if (array[i][attr] === parseInt(value)) {
            tmp++;
            tmp2 = i;
        }
        if (array[i][attr] === parseInt(value) && array[i].command === cmd) {
            ret = i;
            retCount++;
        }
    }
    if (ret === -1 && tmp2 != -1) {
        // console.log("Same commands : " + tmp + " // retCount : " + retCount + " // cmd : " + cmd + " // COMMAND : " + array[tmp2].toString() + " // CURRENT TIMESTAMP : " + value);
    }
    return ret;
}

function findNameWithinArray(array, value) {
    var ret = -1;
    for (var i = 0; i < array.length; i++) {
        if (array[i].name === value)
            ret = i;
    }
    return ret;
}

function commandToJSON(cmd) {
    var ret = "";
    ret += "[";
    ret += "{";
    ret += "\"command\":\"" + cmd.command + "\",";
    if (cmd.query_arg1 != "null")
        ret += "\"arg1\": 0,";
    if (cmd.query_arg2 != "null") {
        if (typeof(cmd.query_arg2) === 'string')
            ret += "\"arg2\": \"" + cmd.query_arg2 + "\",";
        else
            ret += "\"arg2\": " + cmd.query_arg2 + ",";
    }
    if (cmd.query_arg3 != "null")
        ret += "\"arg3\": " + cmd.query_arg3 + ",";
    if (cmd.query_arg4 != "null") {
        if (typeof(cmd.query_arg4) === 'string' && cmd.command != "subscribe")
            ret += "\"arg4\": \"" + cmd.query_arg4 + "\",";
        else
            ret += "\"arg4\": " + cmd.query_arg4 + ",";
    }
    ret += "\"query_time\":" + cmd.query_id;
    ret += "}";
    ret += "]";
    return ret;
}

function stringsToJSON(cmd) {
    var ret = "";
    ret += "[";
    ret += "{";
    ret += "\"command\":\"" + cmd.command + "\",";
    if (cmd.query_arg1 != "null")
        ret += "\"arg1\":0,";
    if (cmd.query_arg2 != "null")
        ret += "\"arg2\":\"" + cmd.query_arg2 + "\",";
    if (cmd.query_arg3 != "null")
        ret += "\"arg3\":" + cmd.query_arg3 + ",";
    if (cmd.query_arg4 != "null")
        ret += "\"arg4\":\"" + cmd.query_arg4 + "\",";
    ret += "\"query_time\":" + cmd.query_id;
    ret += "}";
    ret += "]";
    return ret;
}

function commandsToJSON(cmdArray) {
    var ret = "";
    ret += "[";
    for (i = 0; i < cmdArray.length; i++) {
        ret += "{";
        ret += "\"command\":\"" + cmdArray[i].command + "\",";
        if (cmdArray[i].query_arg1 != "null")
            ret += "\"arg1\": 0,";
        if (cmdArray[i].query_arg2 != "null") {
            if (typeof(cmdArray[i].query_arg2) === 'string')
                ret += "\"arg2\": \"" + cmdArray[i].query_arg2 + "\",";
            else
                ret += "\"arg2\": " + cmdArray[i].query_arg2 + ",";
        }
        if (cmdArray[i].query_arg3 != "null")
            ret += "\"arg3\": " + cmdArray[i].query_arg3 + ",";
        if (cmdArray[i].query_arg4 != "null") {
            if (typeof(cmdArray[i].query_arg4) === 'string' && cmdArray[i].command != "subscribe" && cmdArray[i].command != cmd_set_speaker_fir_table)
                ret += "\"arg4\": \"" + cmdArray[i].query_arg4 + "\",";
            else
                ret += "\"arg4\": " + cmdArray[i].query_arg4 + ",";
        }
        ret += "\"query_time\":" + cmdArray[i].query_id;
        ret += "}";
        if (i < cmdArray.length - 1)
            ret += ",";
    }
    ret += "]";
    return ret;
}

function download(content, fileName, contentType) {
    const a = document.createElement("a");
    var ciphertext = CryptoJS.AES.encrypt(content, presetKey);
    const file = new Blob([ciphertext], { type: contentType });
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}

$.fn.maxDelayCompute = function() {
    if (arrayAmplifier[soloAmplifierSelected].model)
        for (var j = 0; j < channel16Count; j++) {
            var currentDelay = 0;
            if (arrayAmplifier[soloAmplifierSelected].channel[j].delay.delayEna) {
                currentDelay += arrayAmplifier[soloAmplifierSelected].channel[j].delay.delay;
            }
            for (var i = 0; i < groupCount; i++) {
                if (arrayAmplifier[soloAmplifierSelected].channel[j].group[i] === 1) {
                    if (arrayGroup[i].delay.delayEna) {
                        currentDelay += arrayGroup[i].delay.delay;
                    }
                }
            }
            // $("#itemQuarterTotalDelay" + j).html("(" + currentDelay.toFixed(0) + "ms)");
            $("#itemQuarterTotalDelay" + j).html("(" + currentDelay.toFixed(0) + ")");
            if (currentDelay >= 250)
                $("#itemQuarterTotalDelay" + j).addClass("Max");
        }
}

function loadFile(filePath) {
    var result = null;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", filePath, false);
    xmlhttp.send();
    if (xmlhttp.status == 200) {
        result = xmlhttp.responseText;
        lines = result.split("\n");
        usernameHttp = lines[0];
        passwordHttp = lines[1];
    }
}

//WEB SOCKET CREATION
$.fn.createWebSocket = function() {
    if (demoMode === 0) {
        request_pool[0] = new Array();
        //TO UNCOMMENT
        $.fn.poolMonitor();
        var href = $(location).attr("href");
        var r = /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/;
        var t;
        if (href.match(r) != null) {
            //IP ADDRESS
            t = href.match(r);
            loginLocal = 1;
        } else {
            t = new Array(1);
            var x = 0;
            if (href.indexOf(".me/") >= 0) {
                x = href.indexOf(".me/");
                x = x + 3;
            } else
                x = href.length;
            t[0] = href.slice(7, x);
            httpSecure = 1;
        }
        //TEST IF SERVER IS AVAILABLE
        if (t) {
            if (t[0]) {
                ws_ip = t[0];
            }
            var ws_string = "ws://" + ws_ip + ":" + ws_port + "/";
            if (httpSecure === 1) {
                loadFile("id.txt");
                ws_string = "ws://" + usernameHttp + ":" + passwordHttp + "@" + ws_ip + ":" + ws_port + "/";
            }
            if (ws === null || ws.readyState === WebSocket.CLOSED) {
                ws = new WebSocket(ws_string);
                ws.onmessage = function wsOnMessage(event) {
                    $.fn.receiveCommandWS(event);
                    return false;
                };

                ws.onopen = function wsOnOpen(event) {
                    runSubscription = false;
                    packetLostCount = 0;
                    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_get_neighbour_list, "null", "null", "null", "null")));
                    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_get_lan_config, 0, "null", "null", "null")));
                    ws.send(commandToJSON($.fn.getCommandFromArgs(cmd_oem_get_status, 0, "null", "null", "null")));
                    $("#iconEthernet").attr("src", "./img/ethernet_hover.png");
                };

                ws.onerror = function(event) {
                    setTimeout(function() {
                        $("#iconEthernet").attr("src", "./img/ethernet_fail.png");
                        runSubscription = false;
                        $("#mainLoader").addClass("is-active");
                        $.fn.createWebSocket();
                    }, 2000);
                };

                ws.onclose = function(e) {
                    setTimeout(function() {
                        $("#iconEthernet").attr("src", "./img/ethernet_fail.png");
                        runSubscription = false;
                        $("#mainLoader").addClass("is-active");
                        $.fn.createWebSocket();
                    }, 2000);
                };

            }
        }
    }
}

$.fn.createDiscoveryWorker = function() {
    if (demoMode === 0) {
        if (window.Worker) {
            for (var i = 0; i < discoveryList.length; i++) {
                readBackDiscovery[i] = new Array(4);
                readBackLimiter[i] = new Array(4);
                readBackStatus[i] = new Array(moduleCount);
                if (i > 0 && request_pool.length < discoveryList.length)
                    request_pool.push(new Array());
                for (var j = 0; j < channel16Count; j++) {
                    readBackLimiter[i][j] = new Array(6);
                }
                for (var k = 0; k < moduleCount; k++) {
                    readBackStatus[i][k] = new Array(10);
                }
                if (typeof(discoveryWorker[i]) == "undefined") {
                    var dw = new Object();
                    dw.worker = new Worker("./js/apex_worker_discovery.js");
                    dw.status = 0;
                    dw.subscription = 0;
                    dw.alive = false;
                    dw.ws = false;
                    dw.index = i;
                    discoveryWorker.push(dw);
                    discoveryWorker[i].worker.onmessage = function(e) {
                        $.fn.receiveDiscoveryWorkerMessage(e.data.index, e.data);
                    }
                }
            }

            for (var i = 0; i < discoveryList.length; i++) {
                let msg = new Object();
                msg.url = "test" + i;
                let nocloud = 0;
                if (loginLocal && discoveryList[i].ip_addr != "0.0.0.0") {
                    if (usernameHttp != "admin" && passwordHttp != "admin" && i === 0)
                        msg.url = "ws://" + usernameHttp + ":" + passwordHttp + "@" + discoveryList[i].ip_addr + ":5678";
                    else
                        msg.url = "ws://admin:admin@" + discoveryList[i].ip_addr + ":5678";
                } else if (loginLocal && discoveryList[i].ip_addr === "0.0.0.0") {
                    if (usernameHttp != "admin" && passwordHttp != "admin" && i === 0)
                        msg.url = "ws://" + usernameHttp + ":" + passwordHttp + "@" + ws_ip + ":5678";
                    else
                        msg.url = "ws://admin:admin@" + ws_ip + ":5678";
                } else {
                    if ((usernameHttp != "admin" || passwordHttp != "admin") && i === 0)
                        msg.url = "ws://" + usernameHttp + ":" + passwordHttp + "@" + discoveryList[i].cloud_device_name + ".apexconnect.me:5678";
                    else if (discoveryList[i].cloud_device_name.length == 0)
                        nocloud = 1;
                    else
                        msg.url = "ws://admin:admin@" + discoveryList[i].cloud_device_name + ".apexconnect.me:5678";
                }
                msg.index = i;
                msg.command = "wsUrl";
                if (discoveryWorker[i].status === 0 && nocloud == 0) {
                    discoveryWorker[i].worker.postMessage(msg);
                    discoveryWorker[i].status = 1;
                    discoveryWorker[i].ws = true;
                }
            }
        } else {
            alert("worker not supported by your browser");
        }
        $.fn.dataLoaded();
    } else {
        for (var i = 0; i < channel16Count; i++) {
            readBackDiscovery[i] = new Array(4);
            readBackLimiter[i] = new Array(4);
            readBackStatus[i] = new Array(10);
        }
    }
}

$.fn.closeDiscoveryWS = function(index) {
    let msg = new Object();
    msg.command = "closeWs";
    discoveryWorker[index].worker.postMessage(msg);
    discoveryWorker[index].worker.terminate();
}

$.fn.openDiscoveryWS = function(index) {
    let msg = new Object();
    msg.command = "openWs";
    discoveryWorker[index].worker.postMessage(msg);
}

function compareWords(a, b) {
    if (a.name.toLowerCase() < b.name.toLowerCase()) {
        return -1;
    } else {
        return 1;
    }
}

$.fn.receiveDiscoveryWorkerMessage = function(index, data) {
    try {
        if (data.command === cmd_close_ws) {
            discoveryWorker[data.index].ws = false;
            $("#discoveryListDevice" + index).removeClass("btnSelector");
            $("#discoveryListDevice" + index).addClass("btnSelectorOffline");
        } else if (data.command === cmd_ipc_error) {
            console.log("IPC error");
        } else {
            var msgR = JSON.parse(data.data);
            var i = -1;
            if (msgR.command != "get_json_data")
                if (request_pool[index])
                    i = findWithAttr(request_pool[index], "query_id", msgR.query_time, msgR.command);
                //IF WE FOUND THE RELATED COMMAND, CHANGE STATUS TO "finish"
            if (i > -1) {
                index_msg = i;
                request_pool[index][i].response_arg1 = msgR.arg1;
                request_pool[index][i].response_arg2 = msgR.arg2;
            }

            // switch (data.command) {
            switch (data.command) {

                case cmd_get_readback:
                    if (index === 0) {
                        if ($("#mainLoader").hasClass("is-active"))
                            $("#mainLoader").removeClass("is-active");
                        if ($("#softwareLoader").hasClass("is-active")) {
                            setTimeout(function() {
                                $("#softwareLoader").removeClass("is-active");
                                $("#softwareLoader").attr("data-text", "Software updating");
                            }, 5000);
                        }
                    }
                    if (msgR.arg2) {
                        var temp = JSON.parse(msgR.arg2);
                        if (temp) {
                            for (var a = 0; a < channel16Count; a++) {
                                //READBACK LEVEL
                                readBackDiscovery[index][a] = parseFloat(temp[readbackChannel + (a + 1)]) + globalDbScaleFactor;
                                //CHANNEL LIMITERS
                                readBackLimiter[index][a][0] = parseFloat(temp[readbackUserRmsLim + (a + 1)]);
                                readBackLimiter[index][a][1] = parseFloat(temp[readbackUserPeakLim + (a + 1)]);
                                readBackLimiter[index][a][2] = parseFloat(temp[readbackSpeakerRmsLim + (a + 1)]);
                                readBackLimiter[index][a][3] = parseFloat(temp[readbackSpeakerPeakLim + (a + 1)]);
                                readBackLimiter[index][a][4] = parseFloat(temp[readbackAmpLim + (a + 1)]);
                                readBackLimiter[index][a][5] = 0;
                                for (var b = 0; b < 5; b++)
                                    readBackLimiter[index][a][5] += readBackLimiter[index][a][b];
                            }
                            for (var b = 0; b < moduleCount; b++) {
                                //STATUS DATA
                                readBackStatus[index][b][0] = temp[readbackModuleTemp + (b + 1)]
                                readBackStatus[index][b][1] = temp[readbackModuleAmpOn + (b + 1)]
                                readBackStatus[index][b][2] = temp[readbackModuleOvertemp + (b + 1)]
                                readBackStatus[index][b][3] = temp[readbackModuleVoltage + (b + 1)]
                            }

                        }
                    }
                    break;
                case cmd_get_global_preset_file:
                    var name = "global_preset";
                    if (downloadSpeakerPresetName != "")
                        name = downloadSpeakerPresetName;
                    downloadSpeakerPresetName = "";
                    download(JSON.stringify(msgR.arg2), name + globalPresetExtension, "text/plain");
                    break;

                case cmd_set_global_preset_file:
                    if (msgR.arg1.toString() != "OK") {
                        alert("Global Preset Loading Error");
                    }
                    let timeout = 1000;
                    switch ($.fn.getModel()) {
                        case 9:
                            timeout = channel1PresetTimeOut;
                            break;
                        case 8:
                            timeout = channel16PresetTimeOut;
                            break;
                        case 7:
                            timeout = channel16PresetTimeOut;
                            break;
                        case 6:
                            timeout = channel1PresetTimeOut;
                            break;
                        case 5:
                            timeout = channel1PresetTimeOut;
                            break;
                        default:
                            timeout = channel4PresetTimeOut;
                            break;
                    }
                    setTimeout(function() {
                        $("#presetLoader").removeClass("is-active");
                    }, timeout);
                    break;

                case cmd_set_speaker_preset_file:
                    if (msgR.arg1.toString() != "OK") {
                        alert("Speaker Preset Loading Error");
                    }
                    setTimeout(function() {
                        $("#presetLoader").removeClass("is-active");
                        //DISPLAY NEW PRESET LABEL
                        $.fn.updateOverviewPresetLabel();
                    }, 2000);

                    setTimeout(function() {
                        $.fn.setDataSoloSpeaker(100);
                    }, 3000);
                    break;

                case cmd_set_label_speaker_preset_file:
                    if (msgR.arg1.toString() != "OK") {
                        alert("Speaker Preset Loading Error");
                    }
                    setTimeout(function() {
                        $("#presetLoader").removeClass("is-active");
                        //DISPLAY NEW PRESET LABEL
                        $.fn.updateOverviewPresetLabel();
                    }, 2000);

                    setTimeout(function() {
                        $.fn.setDataSoloSpeaker(100);
                    }, 3000);
                    break;

                case cmd_set_all_speaker_preset_file:
                    if (msgR.arg1.toString() != "OK") {
                        alert("Speaker Preset Loading Error");
                    }
                    setTimeout(function() {
                        $("#presetLoader").removeClass("is-active");
                        //DISPLAY NEW PRESET LABEL
                        $.fn.updateOverviewPresetLabel();
                    }, 2000);

                    setTimeout(function() {
                        $.fn.setDataSoloSpeaker(100);
                    }, 3000);
                    break;

                case cmd_software_update:
                    switch (msgR.arg2) {
                        case "ERROR: Could not find update runner.":
                            break;
                        case "ERROR: Unable to start update runner.":
                            break;
                        case "Update launched.":
                            break;
                        case "ERROR: Unable to decode the payload.":
                            break;
                        case "ERROR: The archive is damaged.":
                            break;
                        case "ERROR: Unable to create temporary file.":
                            break;
                        default:
                            break;
                    }
                    break;

                case cmd_get_speaker_preset_folder_names:
                    let foldersSpeaker = msgR.arg2;
                    let tempFoldersSpeaker = new foldersConstructor(foldersSpeaker.length);
                    for (var a = 0; a < foldersSpeaker.length; a++) {
                        tempFoldersSpeaker.folderList[a].name = foldersSpeaker[a];
                    }
                    arrayAmplifier[index].folderSpeaker = tempFoldersSpeaker;
                    arrayAmplifier[index].folderSpeaker.folderCount = foldersSpeaker.length;

                    var arrCmd = new Array();
                    for (var i = 0; i < arrayAmplifier[index].folderSpeaker.folderCount; i++) {
                        arrCmd.push($.fn.getCommandFromArgs(cmd_get_speaker_preset_file_names, index, arrayAmplifier[index].folderSpeaker.folderList[i].name, "null", "null"));
                    }
                    $.fn.sendCommandsWS(arrCmd);
                    break;

                case cmd_get_all_speaker_preset_folder_names:
                    let foldersAllSpeaker = msgR.arg2;
                    let tempFoldersAllSpeaker = new foldersConstructor(foldersAllSpeaker.length);
                    for (var a = 0; a < foldersAllSpeaker.length; a++) {
                        tempFoldersAllSpeaker.folderList[a].name = foldersAllSpeaker[a];
                    }
                    arrayAmplifier[index].folderSpeaker = tempFoldersAllSpeaker;
                    arrayAmplifier[index].folderSpeaker.folderCount = foldersAllSpeaker.length;

                    var arrCmd = new Array();
                    for (var i = 0; i < arrayAmplifier[index].folderSpeaker.folderCount; i++) {
                        arrCmd.push($.fn.getCommandFromArgs(cmd_get_all_speaker_preset_file_names, index, arrayAmplifier[index].folderSpeaker.folderList[i].name, "null", "null"));
                    }
                    $.fn.sendCommandsWS(arrCmd);
                    break;

                case cmd_get_speaker_preset_file_names:
                    if (i > -1) {
                        var files = request_pool[index][i].response_arg2;
                        var tempFiles = new Array(files.length);
                        for (var b = 0; b < files.length; b++) {
                            tempFiles[b] = new fileConstructor(b);
                            tempFiles[b].name = files[b];
                        }
                        tempFiles = tempFiles.sort(compareWords);
                        var foldIndex = findNameWithinArray(arrayAmplifier[index].folderSpeaker.folderList, request_pool[index][i].query_arg2);
                        if (foldIndex > -1) {
                            arrayAmplifier[index].folderSpeaker.folderList[foldIndex].fileList = tempFiles;
                            arrayAmplifier[index].folderSpeaker.folderList[foldIndex].fileCount = files.length;
                        }
                    }
                    break;

                case cmd_get_all_speaker_preset_file_names:
                    if (i > -1) {
                        var files = request_pool[index][i].response_arg2;
                        var tempFiles = new Array(files.length);
                        for (var b = 0; b < files.length; b++) {
                            tempFiles[b] = new fileConstructor(b);
                            tempFiles[b].name = files[b];
                        }
                        tempFiles = tempFiles.sort(compareWords);
                        var foldIndex = findNameWithinArray(arrayAmplifier[index].folderSpeaker.folderList, request_pool[index][i].query_arg2);
                        if (foldIndex > -1) {
                            arrayAmplifier[index].folderSpeaker.folderList[foldIndex].fileList = tempFiles;
                            arrayAmplifier[index].folderSpeaker.folderList[foldIndex].fileCount = files.length;
                        }
                    }
                    break;

                case cmd_get_speaker_preset_list_names:
                    var preset_list = msgR.arg2;
                    var tempFolders = new foldersConstructor(preset_list.length);
                    for (var a = 0; a < preset_list.length; a++) {
                        tempFolders.folderList[a].name = preset_list[a]["folder_name"];
                    }
                    arrayAmplifier[index].folderSpeaker = tempFolders;
                    arrayAmplifier[index].folderSpeaker.folderCount = preset_list.length;

                    for (var a = 0; a < preset_list.length; a++) {
                        var tempFiles = new Array(preset_list[a]["files"].length);
                        for (var b = 0; b < preset_list[a]["files"].length; b++) {
                            tempFiles[b] = new fileConstructor(b);
                            tempFiles[b].name = preset_list[a]["files"][b].file_name;
                            tempFiles[b].file_name = preset_list[a]["files"][b].file_name;

                            tempFiles[b].author = preset_list[a]["files"][b].author;
                            tempFiles[b].version = preset_list[a]["files"][b].version;
                            tempFiles[b].note = preset_list[a]["files"][b].note;

                            tempFiles[b].protected = preset_list[a]["files"][b].oem;
                        }
                        tempFiles = tempFiles.sort(compareWords);
                        arrayAmplifier[index].folderSpeaker.folderList[a].fileList = tempFiles;
                        arrayAmplifier[index].folderSpeaker.folderList[a].fileCount = preset_list[a]["files"].length;
                    }

                    $.fn.setDataSoloSpeaker(100);
                    break;

                case cmd_get_all_speaker_preset_list_names:
                    var preset_list = msgR.arg2;
                    var tempFolders = new foldersConstructor(preset_list.length);
                    for (var a = 0; a < preset_list.length; a++) {
                        tempFolders.folderList[a].name = preset_list[a]["folder_name"];
                    }
                    arrayAmplifier[index].folderSpeaker = tempFolders;
                    arrayAmplifier[index].folderSpeaker.folderCount = preset_list.length;

                    for (var a = 0; a < preset_list.length; a++) {
                        var tempFiles = new Array(preset_list[a]["files"].length);
                        for (var b = 0; b < preset_list[a]["files"].length; b++) {
                            tempFiles[b] = new fileConstructor(b);
                            tempFiles[b].name = preset_list[a]["files"][b].file_name;
                            tempFiles[b].file_name = preset_list[a]["files"][b].file_name;

                            tempFiles[b].author = preset_list[a]["files"][b].author;
                            tempFiles[b].version = preset_list[a]["files"][b].version;
                            tempFiles[b].note = preset_list[a]["files"][b].note;

                            tempFiles[b].protected = preset_list[a]["files"][b].oem;
                        }
                        tempFiles = tempFiles.sort(compareWords);
                        arrayAmplifier[index].folderSpeaker.folderList[a].fileList = tempFiles;
                        arrayAmplifier[index].folderSpeaker.folderList[a].fileCount = preset_list[a]["files"].length;
                    }

                    $.fn.setDataSoloSpeaker(100);
                    break;

                case cmd_get_speaker_preset_file:
                    var name = "preset";
                    if (downloadSpeakerPresetName != "")
                        name = downloadSpeakerPresetName;
                    downloadSpeakerPresetName = "";
                    download(JSON.stringify(msgR.arg2), name + speakerPresetExtension, "text/plain");
                    break;

                case cmd_get_all_speaker_preset_file:
                    var name = "preset";
                    if (downloadSpeakerPresetName != "")
                        name = downloadSpeakerPresetName;
                    downloadSpeakerPresetName = "";
                    download(JSON.stringify(msgR.arg2), name + speakerPresetExtension, "text/plain");
                    break;

                case cmd_get_global_preset_folder_names:
                    if (i > -1) {
                        let folders = msgR.arg2;
                        if (folders.length > 0) {
                            let tempFolders = new foldersConstructor(folders.length);
                            for (var a = 0; a < folders.length; a++) {
                                tempFolders.folderList[a].name = folders[a];
                            }
                            arrayAmplifier[index].folderGlobal = tempFolders;
                            arrayAmplifier[index].folderGlobal.folderCount = folders.length;

                            var arrCmd = new Array();
                            for (var i = 0; i < arrayAmplifier[index].folderGlobal.folderCount; i++) {
                                arrCmd.push($.fn.getCommandFromArgs(cmd_get_global_preset_file_names, index, arrayAmplifier[index].folderGlobal.folderList[i].name, "null", "null"));
                            }
                            $.fn.sendCommandsWS(arrCmd);

                            $.fn.setDataSoloGlobal(100);
                        } else {
                            arrayAmplifier[index].folderGlobal = new foldersConstructor(0);
                            arrayAmplifier[index].folderGlobal.folderCount = 0;
                            $.fn.setDataSoloGlobal(100);
                        }
                    }
                    break;

                case cmd_get_global_preset_file_names:
                    if (i > -1) {
                        var files = request_pool[index][i].response_arg2;
                        var tempFiles = new Array(files.length);
                        for (var b = 0; b < files.length; b++) {
                            tempFiles[b] = new fileConstructor(b);
                            tempFiles[b].name = files[b];
                        }
                        var foldIndex = findNameWithinArray(arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList, request_pool[index][i].query_arg2);
                        if (foldIndex > -1) {
                            arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[foldIndex].fileList = tempFiles;
                            arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[foldIndex].fileCount = files.length;
                            $.fn.setDataSoloGlobal(100);
                        }
                    }
                    break;

                case cmd_create_speaker_preset_file:
                    if (msgR.arg1 === "OK") {
                        $.fn.sendCommandWS(cmd_get_speaker_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
                        setTimeout(function() {
                            $.fn.setDataSoloSpeaker(100);
                            $("#presetUploader").removeClass("is-active");
                        }, 5000);
                    }
                    break;

                case cmd_create_all_speaker_preset_file:
                    if (msgR.arg1 === "OK") {
                        $.fn.sendCommandWS(cmd_get_all_speaker_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
                        setTimeout(function() {
                            $.fn.setDataSoloSpeaker(100);
                            $("#presetUploader").removeClass("is-active");
                        }, 5000);
                    }
                    break;

                case cmd_upload_speaker_preset_file:
                    if (msgR.arg1 === "OK") {
                        $.fn.sendCommandWS(cmd_get_speaker_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
                        setTimeout(function() {
                            $.fn.setDataSoloSpeaker(100);
                            $("#presetUploader").removeClass("is-active");
                        }, 2000);
                    }
                    break;

                case cmd_upload_all_speaker_preset_file:
                    if (msgR.arg1 === "OK") {
                        $.fn.sendCommandWS(cmd_get_all_speaker_preset_list_names, soloAmplifierSelected, "null", "null", "null");
                        setTimeout(function() {
                            $.fn.setDataSoloSpeaker(100);
                            $("#presetUploader").removeClass("is-active");
                        }, 2000);
                    }
                    break;

                case cmd_set_speaker_preset_files_from_folder:
                    if (msgR.arg1 === "OK") {
                        $("#presetUploader").removeClass("is-active");
                        $.fn.sendCommandWS(cmd_get_speaker_preset_list_names, 0, "null", "null", "null");
                    } else {
                        $("#presetUploader").removeClass("is-active");
                        alert("Preset name already exist in folder !");
                    }
                    break;

                case cmd_set_all_speaker_preset_files_from_folder:
                    if (msgR.arg1 === "OK") {
                        $("#presetUploader").removeClass("is-active");
                        $.fn.sendCommandWS(cmd_get_all_speaker_preset_list_names, 0, "null", "null", "null");
                    } else {
                        $("#presetUploader").removeClass("is-active");
                        alert("Preset name already exist in folder !");
                    }
                    break;

                case cmd_upload_global_preset_file:
                    if (msgR.arg1 === "OK") {
                        $.fn.sendCommandWS(cmd_get_global_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
                        setTimeout(function() {
                            $.fn.setDataSoloGlobal(100);
                            $("#presetUploader").removeClass("is-active");
                        }, 2000);
                    }
                    break;

                case cmd_get_lan_config:
                    var jsonObj = msgR.arg2;
                    if (arrayAmplifier[index].network.lan.ip != jsonObj.ip) {
                        arrayAmplifier[index].network.lan.ip = jsonObj.ip;
                        if (index === soloAmplifierSelected) {
                            $("#lanIpInput").val(arrayAmplifier[index].network.lan.ip);

                            // if (arrayAmplifier[soloAmplifierSelected].label.length > 0)
                            $(".topMenuTitle").html("" + arrayAmplifier[soloAmplifierSelected].label + " : " + arrayAmplifier[soloAmplifierSelected].network.lan.ip);
                        }
                        let idDest3 = "#dldcds" + index;
                        if ($(idDest3))
                            $(idDest3).html(arrayAmplifier[index].network.lan.ip);
                    }
                    if (arrayAmplifier[index].network.lan.mask != jsonObj.mask) {
                        arrayAmplifier[index].network.lan.mask = jsonObj.mask;
                        if (index === soloAmplifierSelected)
                            $("#lanMaskInput").val(arrayAmplifier[index].network.lan.mask);
                    }
                    if (arrayAmplifier[index].network.lan.gw != jsonObj.gateway) {
                        arrayAmplifier[index].network.lan.gw = jsonObj.gateway;
                        if (index === soloAmplifierSelected)
                            $("#lanGatewayInput").val(arrayAmplifier[index].network.lan.gw);
                    }
                    if (arrayAmplifier[index].network.lan.dhcp != jsonObj.dhcp) {
                        arrayAmplifier[index].network.lan.dhcp = jsonObj.dhcp;
                        if (index === soloAmplifierSelected) {
                            if (arrayAmplifier[index].network.lan.dhcp) {
                                $("#lanDhcpEnable").prop("checked", true);
                                $("#lanDhcpEnable").attr("value", true);
                            } else {
                                $("#lanDhcpEnable").prop("checked", false);
                                $("#lanDhcpEnable").attr("value", false);
                            }
                        }
                    }
                    break;

                case cmd_get_about:
                    if ($("#mainLoader").hasClass("is-active"))
                        $("#mainLoader").removeClass("is-active");
                    var jsonObj = msgR.arg2;
                    arrayAmplifier[index].model = jsonObj.model;
                    arrayAmplifier[index].hardwareVersion = jsonObj.hardware_version;
                    arrayAmplifier[index].serial = jsonObj.serial;
                    $("#aboutModelValue").html(arrayAmplifier[index].model);
                    $("#aboutHardwareVersionValue").html(arrayAmplifier[index].hardwareVersion);
                    $("#aboutSerialValue").html(arrayAmplifier[index].serial);
                    $.fn.setupDiscoverySolo();
                    break;

                case cmd_get_neighbour_list:
                    try {
                        var files = JSON.parse(msgR.arg2);
                        if (discoveryList.length < 1) {
                            discoveryList = new Array(files.length);
                            for (var c = 0; c < files.length; c++) {
                                discoveryList[c] = new discoveredAmpConstructor(files[c]);
                            }
                        } else if (discoveryList.length < files.length) {
                            for (var d = 0; d < (files.length - discoveryList.length); d++) {
                                discoveryList.push(new discoveredAmpConstructor(files[discoveryList.length + d]));
                            }
                            $.fn.createDiscoveryWorker();
                        } else if (discoveryList.length === files.length) {
                            let sortList = 0;
                            for (var e = 0; e < discoveryList.length; e++) {
                                if (discoveryList[e].desc != files[e].desc && e > 0) {
                                    discoveryList[e].desc = files[e].desc;
                                    let idDest1 = "#assignGroupTabAmpName" + e;
                                    let idDest2 = "#groupAssignAmpSelectedName";
                                    if ($(idDest1))
                                        $(idDest1).html(discoveryList[e].desc);
                                    if (groupAssignAmplifierSelected === e) {
                                        $(idDest2).html(discoveryList[e].desc);
                                    }
                                }
                                discoveryList[e].desc = files[e].desc;
                                discoveryList[e].hw_addr = files[e].hw_addr;
                                discoveryList[e].alive = files[e].alive;
                                discoveryList[e].last_report_time = files[e].last_report_time;
                                discoveryList[e].model = files[e].model;
                                discoveryList[e].cloud_device_name = files[e].cloud_device_name;

                                if (discoveryList[e].hw_addr != files[e].hw_addr)
                                    sortList++;
                            }
                            if (sortList > 0) {
                                $.fn.setDiscoverySource();
                            }
                        }
                    } catch (e) {
                        // console.log("Fail to parse get_neighbour_list");
                    }
                    break;

                case cmd_get_xover_hp_freq_from_preset:
                    if (i > -1) {
                        var hpf = parseInt(request_pool[index][i].response_arg2);
                        if (hpf >= 0) {
                            arrayAmplifier[index].channel[request_pool[index][i].query_arg4].xover.hpSpeakerPresetFreqLimit = hpf;
                        }
                    }
                    break;

                case cmd_get_xover_lp_freq_from_preset:
                    if (i > -1) {
                        var lpf = parseInt(request_pool[index][i].response_arg2);
                        if (lpf >= 0) {
                            arrayAmplifier[index].channel[request_pool[index][i].query_arg4].xover.lpSpeakerPresetFreqLimit = lpf;
                        }
                    }
                    break;

                case cmd_oem_check_code:
                    if (msgR.arg1 === "OK") {

                    } else {
                        updateJsonFile = "";
                        updateJsonStatus = 0;
                        $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>Unable to load OEM preset : wrong OEM code ");
                    }
                    break;

                case cmd_set_hotspot_config:
                    if (msgR.arg1 === "OK") {
                        setTimeout(function() {
                            $("#hotspotSsidInput").css("border", "none");
                            $("#hotspotPasswordInput").css("border", "none");
                        }, 2000);
                    }
                case cmd_oem_get_status:
                    if (msgR.arg2) {
                        var temp = msgR.arg2;
                        if (temp.oem_code_enable === true) {
                            arrayAmplifier[index].oem = true;
                        }
                    }

                    // GET NEIGHBOUR LIST setDiscoverySource
                case cmd_get_json_data:
                    if (discoveryWorker[data.index].ws === false) {
                        discoveryWorker[data.index].ws = true;
                        $("#discoveryListDevice" + index).removeClass("btnSelectorOffline");
                        $("#discoveryListDevice" + index).addClass("btnSelector");
                    }
                    if (subscriptionUpdate === 0) {
                        var jsonObj = JSON.parse(msgR.arg2);
                        //CHANNELS PARAMETERS
                        //CHECK IF IT'S A 4 CHANNELS OR A 16 CHANNELS
                        var amountOfChannel = channelCount;
                        if ($.fn.getModel(index) == 7 || $.fn.getModel(index) == 8) {
                            amountOfChannel = channel16Count;
                        }
                        // displayVal("amount of channels", amountOfChannel);

                        for (var t = 0; t < amountOfChannel; t++) {
                            // PRESET
                            if (arrayAmplifier[index].channel[t].preset != jsonObj[0][t].preset) {
                                arrayAmplifier[index].channel[t].preset = jsonObj[0][t].preset;
                            }

                            // SOURCE
                            if (arrayAmplifier[index].channel[t].source.primary != parseInt(jsonObj[0][t].source_pri) || arrayAmplifier[index].channel[t].source.secondary != parseInt(jsonObj[0][t].source_sec) || arrayAmplifier[index].channel[t].label != jsonObj[0][t].name) {
                                arrayAmplifier[index].channel[t].source.primary = parseInt(jsonObj[0][t].source_pri);
                                arrayAmplifier[index].channel[t].source.secondary = parseInt(jsonObj[0][t].source_sec);
                                arrayAmplifier[index].channel[t].label = jsonObj[0][t].name.toString();
                                $.fn.setDataSoloSourceUpdate(t);
                            }

                            // SIGNAL GENERATOR
                            if (arrayAmplifier[index].signalGenerator.frequencyGenerator.frequency != parseInt(parseInt(jsonObj[2].signal_generator.frequency_generator.frequency).toFixed(0)) || arrayAmplifier[index].signalGenerator.frequencyGenerator.gain != parseFloat(parseFloat(jsonObj[2].signal_generator.frequency_generator.gain).toFixed(1)) || arrayAmplifier[index].signalGenerator.pinkNoise.gain != parseFloat(parseFloat(jsonObj[2].signal_generator.pink_noise.gain).toFixed(1))) {
                                arrayAmplifier[index].signalGenerator.frequencyGenerator.frequency = parseInt(parseInt(jsonObj[2].signal_generator.frequency_generator.frequency).toFixed(0));
                                arrayAmplifier[index].signalGenerator.frequencyGenerator.gain = parseFloat(parseFloat(jsonObj[2].signal_generator.frequency_generator.gain).toFixed(1));
                                arrayAmplifier[index].signalGenerator.pinkNoise.gain = parseFloat(parseFloat(jsonObj[2].signal_generator.pink_noise.gain).toFixed(1));
                                $.fn.setDataSoloSigGen(3, 0);
                            }

                            // MIXER
                            var updateMixer = 0
                            for (var p = 0; p < maxMixerInput; p++) {
                                if (arrayAmplifier[index].channel[t].mixer.gain[p] != parseFloat(parseFloat(jsonObj[0][t].mixer[p].gain).toFixed(1))) {
                                    arrayAmplifier[index].channel[t].mixer.gain[p] = parseFloat(parseFloat(jsonObj[0][t].mixer[p].gain).toFixed(1));
                                    updateMixer++;
                                }
                            }
                            if (updateMixer > 0 && index === soloAmplifierSelected && t === soloChannelSelected)
                                $.fn.setDataSoloMixerUpdate(t);

                            // GAIN
                            if (arrayAmplifier[index].channel[t].gain.gain != parseFloat(parseFloat(jsonObj[0][t].gain).toFixed(1)) || arrayAmplifier[index].channel[t].gain.polarityEna != jsonObj[0][t].polarity || arrayAmplifier[index].channel[t].gain.muteEna != jsonObj[0][t].mute) {
                                arrayAmplifier[index].channel[t].gain.gain = parseFloat(parseFloat(jsonObj[0][t].gain).toFixed(1));
                                arrayAmplifier[index].channel[t].gain.polarityEna = jsonObj[0][t].polarity;
                                arrayAmplifier[index].channel[t].gain.muteEna = jsonObj[0][t].mute;
                                if (index === soloAmplifierSelected) {
                                    $.fn.setDataSoloGainUpdate(t);
                                }
                                // console.log("UPDATE GAIN FROM SUBSCRITPION");
                            }
                            if (index === soloAmplifierSelected) {
                                var labelId = "#overviewSourceLabel" + t;
                                $(labelId).html("" + arrayAmplifier[index].channel[t].gain.gain.toFixed(1) + "dB");
                            }

                            // DELAY
                            if (arrayAmplifier[index].channel[t].delay.delay != parseFloat(parseFloat(jsonObj[0][t].delay_value).toFixed(2)) || arrayAmplifier[index].channel[t].delay.delayEna != jsonObj[0][t].delay_enable) {
                                arrayAmplifier[index].channel[t].delay.delay = parseFloat(parseFloat(jsonObj[0][t].delay_value).toFixed(2));
                                arrayAmplifier[index].channel[t].delay.delayEna = jsonObj[0][t].delay_enable;
                                if (index === soloAmplifierSelected)
                                    $.fn.setDataSoloDelayUpdate(t);
                                // console.log("UPDATE DELAY FROM SUBSCRITPION");
                            }

                            // PEQ
                            var updatePEQ = 0;
                            for (var u = 0; u < peqCount; u++) {
                                updatePEQ = 0;
                                // PEQ ENABLE
                                if (arrayAmplifier[index].channel[t].peq.peq[u].ena != jsonObj[0][t].peq[u].enable) {
                                    arrayAmplifier[index].channel[t].peq.peq[u].ena = jsonObj[0][t].peq[u].enable;
                                    updatePEQ++;
                                }

                                // PEQ TYPE
                                if (arrayAmplifier[index].channel[t].peq.peq[u].type != jsonObj[0][t].peq[u].type) {
                                    arrayAmplifier[index].channel[t].peq.peq[u].type = jsonObj[0][t].peq[u].type;
                                    updatePEQ++;
                                }

                                // PEQ FREQ
                                if (arrayAmplifier[index].channel[t].peq.peq[u].frequency != parseInt(jsonObj[0][t].peq[u].freq)) {
                                    arrayAmplifier[index].channel[t].peq.peq[u].frequency = parseInt(jsonObj[0][t].peq[u].freq);
                                    updatePEQ++;
                                }

                                // PEQ GAIN
                                if (arrayAmplifier[index].channel[t].peq.peq[u].gain != parseFloat(parseFloat(jsonObj[0][t].peq[u].gain).toFixed(1))) {
                                    arrayAmplifier[index].channel[t].peq.peq[u].gain = parseFloat(parseFloat(jsonObj[0][t].peq[u].gain).toFixed(1));
                                    updatePEQ++;
                                }

                                // PEQ Q
                                if (arrayAmplifier[index].channel[t].peq.peq[u].q != parseFloat(parseFloat(jsonObj[0][t].peq[u].q).toFixed(1))) {
                                    arrayAmplifier[index].channel[t].peq.peq[u].q = parseFloat(parseFloat(jsonObj[0][t].peq[u].q).toFixed(1));
                                    updatePEQ++;
                                }
                                if (updatePEQ > 0 && $("#peqMainPanel").is(":visible")) {
                                    if (index === soloAmplifierSelected && t == soloChannelSelected) {
                                        $.fn.setDataSoloPEQUpdate(u);
                                    }
                                }
                            }

                            // XOVER HIGHPASS
                            if (arrayAmplifier[index].channel[t].xover.hpType != parseInt(jsonObj[0][t].xover_hp_filter.xover_hp_type) || arrayAmplifier[index].channel[t].xover.hpEna != jsonObj[0][t].xover_hp_filter.xover_hp_enable || arrayAmplifier[index].channel[t].xover.hpFreq != parseInt(jsonObj[0][t].xover_hp_filter.xover_hp_freq)) {
                                arrayAmplifier[index].channel[t].xover.hpType = parseInt(jsonObj[0][t].xover_hp_filter.xover_hp_type);
                                arrayAmplifier[index].channel[t].xover.hpEna = jsonObj[0][t].xover_hp_filter.xover_hp_enable;
                                arrayAmplifier[index].channel[t].xover.hpFreq = parseInt(jsonObj[0][t].xover_hp_filter.xover_hp_freq);
                                if (index === soloAmplifierSelected)
                                    $.fn.setDataSoloXover(2, 0);
                                // console.log("UPDATE XOVER HP FROM SUBSCRITPION");
                            }

                            // XOVER LOWPASS
                            if (arrayAmplifier[index].channel[t].xover.lpType != parseInt(jsonObj[0][t].xover_lp_filter.xover_lp_type) || arrayAmplifier[index].channel[t].xover.lpEna != jsonObj[0][t].xover_lp_filter.xover_lp_enable || arrayAmplifier[index].channel[t].xover.lpFreq != parseInt(jsonObj[0][t].xover_lp_filter.xover_lp_freq)) {
                                arrayAmplifier[index].channel[t].xover.lpType = parseInt(jsonObj[0][t].xover_lp_filter.xover_lp_type);
                                arrayAmplifier[index].channel[t].xover.lpEna = jsonObj[0][t].xover_lp_filter.xover_lp_enable;
                                arrayAmplifier[index].channel[t].xover.lpFreq = parseInt(jsonObj[0][t].xover_lp_filter.xover_lp_freq);
                                if (index === soloAmplifierSelected)
                                    $.fn.setDataSoloXover(3, 0);
                                // console.log("UPDATE XOVER LP FROM SUBSCRITPION");
                            }

                            // XOVER HIGHPASS SPEAKER PRESET OVERIDE
                            // let indexSpeakerPreset = (2 * t) + 3;
                            if (arrayAmplifier[index].channel[t].xover.hpSpeakerPresetOveride != jsonObj[3][t].xover_hp_filter.xover_hp_overide || arrayAmplifier[index].channel[t].xover.hpSpeakerPresetFreq != parseInt(jsonObj[3][t].xover_hp_filter.xover_hp_freq)) {
                                arrayAmplifier[index].channel[t].xover.hpSpeakerPresetOveride = jsonObj[3][t].xover_hp_filter.xover_hp_overide;
                                arrayAmplifier[index].channel[t].xover.hpSpeakerPresetFreq = parseInt(jsonObj[3][t].xover_hp_filter.xover_hp_freq);
                                if (arrayAmplifier[index].channel[t].xover.hpSpeakerPresetOveride)
                                    $.fn.setDataSoloXover(7, 0);
                                // console.log("UPDATE SPEAKER PRESET XOVER HP FROM SUBSCRITPION");
                            }

                            // XOVER LOWPASS SPEAKER PRESET OVERIDE
                            // indexSpeakerPreset = (2 * t) + 4;
                            if (arrayAmplifier[index].channel[t].xover.lpSpeakerPresetOveride != jsonObj[3][t].xover_lp_filter.xover_lp_overide || arrayAmplifier[index].channel[t].xover.lpSpeakerPresetFreq != parseInt(jsonObj[3][t].xover_lp_filter.xover_lp_freq)) {
                                arrayAmplifier[index].channel[t].xover.lpSpeakerPresetOveride = jsonObj[3][t].xover_lp_filter.xover_lp_overide;
                                arrayAmplifier[index].channel[t].xover.lpSpeakerPresetFreq = parseInt(jsonObj[3][t].xover_lp_filter.xover_lp_freq);
                                if (arrayAmplifier[index].channel[t].xover.lpSpeakerPresetOveride)
                                    $.fn.setDataSoloXover(8, 0);
                                // console.log("UPDATE SPEAKER PRESET XOVER LP FROM SUBSCRITPION");
                            }

                            // LIMITER 
                            if (arrayAmplifier[index].channel[t].limiter.rmsThres != getThresholdInVolt(parseFloat(jsonObj[0][t].lim_rms.lim_rms_thres), 0) || arrayAmplifier[index].channel[t].limiter.rmsAttack != parseFloat(jsonObj[0][t].lim_rms.lim_rms_attack) || arrayAmplifier[index].channel[t].limiter.rmsRelease != parseFloat(jsonObj[0][t].lim_rms.lim_rms_release) || arrayAmplifier[index].channel[t].limiter.peakThres != getThresholdInVolt(parseFloat(jsonObj[0][t].lim_peak.lim_peak_thres), 1) || arrayAmplifier[index].channel[t].limiter.peakRelease != parseFloat(jsonObj[0][t].lim_peak.lim_peak_release)) {
                                arrayAmplifier[index].channel[t].limiter.rmsThres = getThresholdInVolt(parseFloat(jsonObj[0][t].lim_rms.lim_rms_thres), 0);
                                arrayAmplifier[index].channel[t].limiter.rmsAttack = parseFloat(jsonObj[0][t].lim_rms.lim_rms_attack);
                                arrayAmplifier[index].channel[t].limiter.rmsRelease = parseFloat(jsonObj[0][t].lim_rms.lim_rms_release);
                                arrayAmplifier[index].channel[t].limiter.peakThres = getThresholdInVolt(parseFloat(jsonObj[0][t].lim_peak.lim_peak_thres), 1);
                                arrayAmplifier[index].channel[t].limiter.peakRelease = parseFloat(jsonObj[0][t].lim_peak.lim_peak_release);
                                if (index === soloAmplifierSelected)
                                    $.fn.setDataSoloLimiterUpdate();
                                // console.log("UPDATE LIMITER FROM SUBSCRITPION");
                            }

                            // ASSIGN TO GROUP
                            for (var x = 0; x < groupCount; x++) {
                                if (arrayAmplifier[index].channel[t].group[x] != parseInt(jsonObj[0][t].assigned_to_group[x])) {
                                    //console.log("FROM WS : amplifier : " + index + " // channel : " + t + " // group : " + x + " // new status : " + jsonObj[0][t].assigned_to_group[x]);
                                    arrayAmplifier[index].channel[t].group[x] = parseInt(jsonObj[0][t].assigned_to_group[x]);
                                    // TO UNCOMMENT
                                    $.fn.setDataGroupAssign(0, index, t, x);

                                    // console.log("UPDATE GROUP ASSIGN FROM SUBSCRITPION");
                                }
                            }
                        }
                        if (index == 0) {
                            //GROUPS PARAMETERS
                            for (var v = 0; v < groupCount; v++) {
                                if (arrayGroup[v].gain.gain != parseFloat(parseFloat(jsonObj[1][v].gain).toFixed(1)) || arrayGroup[v].gain.muteEna != jsonObj[1][v].mute || arrayGroup[v].gain.polarityEna != jsonObj[1][v].polarity) {
                                    arrayGroup[v].gain.gain = parseFloat(parseFloat(jsonObj[1][v].gain).toFixed(1));
                                    arrayGroup[v].gain.muteEna = jsonObj[1][v].mute;
                                    arrayGroup[v].gain.polarityEna = jsonObj[1][v].polarity;
                                    $.fn.setDataGroupGainUpdate();
                                    // console.log("UPDATE GAIN GROUP FROM SUBSCRITPION");
                                }
                                // DELAY
                                if (arrayGroup[v].delay.delay != parseFloat(parseFloat(jsonObj[1][v].delay_value).toFixed(1)) || arrayGroup[v].delay.delayEna != jsonObj[1][v].delay_enable) {
                                    arrayGroup[v].delay.delay = parseFloat(parseFloat(jsonObj[1][v].delay_value).toFixed(1));
                                    arrayGroup[v].delay.delayEna = jsonObj[1][v].delay_enable;
                                    $.fn.setDataGroupDelayUpdate();
                                    // console.log("UPDATE DELAY GROUP FROM SUBSCRITPION");
                                }
                                // PEQ
                                var updatePEQ = 0;
                                for (var w = 0; w < peqCount; w++) {
                                    updatePEQ = 0;
                                    if (arrayGroup[v].peq[w].ena != jsonObj[1][v].peq[w].enable) {
                                        arrayGroup[v].peq[w].ena = jsonObj[1][v].peq[w].enable;
                                        updatePEQ++;
                                        // console.log("peq ena");
                                    }

                                    // PEQ TYPE
                                    if (arrayGroup[v].peq[w].type != parseInt(jsonObj[1][v].peq[w].type)) {
                                        arrayGroup[v].peq[w].type = parseInt(jsonObj[1][v].peq[w].type);
                                        updatePEQ++;
                                        // console.log("peq type");
                                    }

                                    // PEQ FREQ
                                    if (arrayGroup[v].peq[w].frequency != parseInt(jsonObj[1][v].peq[w].freq)) {
                                        arrayGroup[v].peq[w].frequency = parseInt(jsonObj[1][v].peq[w].freq);
                                        updatePEQ++;
                                        // console.log("peq freq");
                                    }

                                    // PEQ GAIN
                                    if (arrayGroup[v].peq[w].gain != parseFloat(jsonObj[1][v].peq[w].gain)) {
                                        arrayGroup[v].peq[w].gain = parseFloat(jsonObj[1][v].peq[w].gain);
                                        updatePEQ++;
                                        // console.log("peq gain");
                                    }

                                    // PEQ Q
                                    if (arrayGroup[v].peq[w].q != parseFloat(jsonObj[1][v].peq[w].q)) {
                                        arrayGroup[v].peq[w].q = parseFloat(jsonObj[1][v].peq[w].q);
                                        updatePEQ++;
                                        // console.log("peq q");
                                    }

                                    if (updatePEQ > 0 && $("#peqGroupPanel").is(":visible")) {
                                        $.fn.setDataSoloPEQUpdate(w);
                                        // console.log("UPDATE PEQ" + w + " GROUP FROM SUBSCRITPION // UPDATE VALUE :" + updatePEQ);
                                    }
                                }

                                // GROUP NAME
                                if (arrayGroup[v].label != jsonObj[1][v].name) {
                                    arrayGroup[v].label = jsonObj[1][v].name;
                                    $.fn.setDataGroupLabel(0, v);
                                    // console.log("UPDATE NAME GROUP FROM SUBSCRITPION");
                                }
                            }
                        }

                        //ALL GROUPS PARAMETERS
                        for (var v = 0; v < groupCount; v++) {
                            if (arrayGroupData[index][v].gain.gain != parseFloat(parseFloat(jsonObj[1][v].gain).toFixed(1)) || arrayGroupData[index][v].gain.muteEna != jsonObj[1][v].mute || arrayGroupData[index][v].gain.polarityEna != jsonObj[1][v].polarity) {
                                arrayGroupData[index][v].gain.gain = parseFloat(parseFloat(jsonObj[1][v].gain).toFixed(1));
                                arrayGroupData[index][v].gain.muteEna = jsonObj[1][v].mute;
                                arrayGroupData[index][v].gain.polarityEna = jsonObj[1][v].polarity;
                            }
                            // DELAY
                            if (arrayGroupData[index][v].delay.delay != parseFloat(parseFloat(jsonObj[1][v].delay_value).toFixed(1)) || arrayGroupData[index][v].delay.delayEna != jsonObj[1][v].delay_enable) {
                                arrayGroupData[index][v].delay.delay = parseFloat(parseFloat(jsonObj[1][v].delay_value).toFixed(1));
                                arrayGroupData[index][v].delay.delayEna = jsonObj[1][v].delay_enable;
                            }
                            // PEQ
                            var updatePEQ = 0;
                            for (var w = 0; w < peqCount; w++) {
                                if (arrayGroupData[index][v].peq[w].ena != jsonObj[1][v].peq[w].enable) {
                                    arrayGroupData[index][v].peq[w].ena = jsonObj[1][v].peq[w].enable;
                                }

                                // PEQ TYPE
                                if (arrayGroupData[index][v].peq[w].type != parseInt(jsonObj[1][v].peq[w].type)) {
                                    arrayGroupData[index][v].peq[w].type = parseInt(jsonObj[1][v].peq[w].type);
                                }

                                // PEQ FREQ
                                if (arrayGroupData[index][v].peq[w].frequency != parseInt(jsonObj[1][v].peq[w].freq)) {
                                    arrayGroupData[index][v].peq[w].frequency = parseInt(jsonObj[1][v].peq[w].freq);
                                }

                                // PEQ GAIN
                                if (arrayGroupData[index][v].peq[w].gain != parseFloat(jsonObj[1][v].peq[w].gain)) {
                                    arrayGroupData[index][v].peq[w].gain = parseFloat(jsonObj[1][v].peq[w].gain);
                                }

                                // PEQ Q
                                if (arrayGroupData[index][v].peq[w].q != parseFloat(jsonObj[1][v].peq[w].q)) {
                                    arrayGroupData[index][v].peq[w].q = parseFloat(jsonObj[1][v].peq[w].q);
                                }
                            }
                            // GROUP NAME
                            if (arrayGroupData[index][v].label != jsonObj[1][v].name) {
                                arrayGroupData[index][v].label = jsonObj[1][v].name;
                            }
                        }

                        // // SETTINGS

                        // WLAN CONFIG
                        if (arrayAmplifier[index].network.wlan.ssid != jsonObj[2].SSID) {
                            arrayAmplifier[index].network.wlan.ssid = jsonObj[2].SSID
                            if (index === soloAmplifierSelected)
                                $("#hotspotSsidInput").val(arrayAmplifier[index].network.wlan.ssid);
                            // console.log("UPDATE SSID NAME FROM SUBSCRIPTION");
                        }
                        if (arrayAmplifier[index].network.wlan.password != jsonObj[2].hotspot_pass) {
                            arrayAmplifier[index].network.wlan.password = jsonObj[2].hotspot_pass;
                            if (index === soloAmplifierSelected)
                                $("#hotspotPasswordInput").val(arrayAmplifier[index].network.wlan.password);
                            // console.log("UPDATE SSID PASSWORD FROM SUBSCRIPTION");
                        }

                        if (arrayAmplifier[index].network.wlan.enable != jsonObj[2].hotspot_status) {
                            arrayAmplifier[index].network.wlan.enable = jsonObj[2].hotspot_status;
                            if (index === soloAmplifierSelected) {
                                $("#hotspotEnableInput").prop("checked", arrayAmplifier[index].network.wlan.enable);
                                $("#hotspotEnableInput").attr("value", arrayAmplifier[index].network.wlan.enable);
                            }
                        }

                        if (arrayAmplifier[index].cloud.device_name != jsonObj[2].cloud_device_name) {
                            arrayAmplifier[index].cloud.device_name = jsonObj[2].cloud_device_name;
                            if (index === soloAmplifierSelected) {
                                $("#cloudNameInput").val(arrayAmplifier[index].cloud.device_name);
                                // if (arrayAmplifier[soloAmplifierSelected].label.length > 0)
                                $(".topMenuTitle").html("" + arrayAmplifier[soloAmplifierSelected].label + " : " + arrayAmplifier[soloAmplifierSelected].network.lan.ip);
                            }
                            // console.log("UPDATE CLOUD DEVICE NAME FROM SUBSCRIPTION");
                        }

                        if (arrayAmplifier[index].cloud.username != jsonObj[2].cloud_username) {
                            arrayAmplifier[index].cloud.username = jsonObj[2].cloud_username;
                            if (index === soloAmplifierSelected)
                                $("#cloudLoginInput").val(arrayAmplifier[index].cloud.username);
                            // console.log("UPDATE CLOUD USERNAME FROM SUBSCRIPTION");
                        }

                        if (arrayAmplifier[index].cloud.password != jsonObj[2].cloud_password) {
                            arrayAmplifier[index].cloud.password = jsonObj[2].cloud_password;
                            if (index === soloAmplifierSelected)
                                $("#cloudPasswordInput").val(arrayAmplifier[index].cloud.password);
                            // console.log("UPDATE CLOUD PASSWORD FROM SUBSCRIPTION");
                        }

                        if (arrayAmplifier[index].cloud.enable != jsonObj[2].cloud_enable) {
                            arrayAmplifier[index].cloud.enable = jsonObj[2].cloud_enable;
                            if (index === soloAmplifierSelected) {
                                $("#cloudEnableInput").prop("checked", arrayAmplifier[index].cloud.enable);
                                $("#cloudEnableInput").attr("value", arrayAmplifier[index].cloud.enable);
                            }
                        }

                        if (arrayAmplifier[index].streaming.spotify.device_name != jsonObj[2].spotify_device_name) {
                            arrayAmplifier[index].streaming.spotify.device_name = jsonObj[2].spotify_device_name;
                            if (index === soloAmplifierSelected)
                                $("#spotifyNameInput").val(arrayAmplifier[index].streaming.spotify.device_name);
                            // console.log("UPDATE SPOTIFY DEVICE NAME FROM SUBSCRIPTION");
                        }
                        if (arrayAmplifier[index].streaming.spotify.email != jsonObj[2].spotify_email) {
                            arrayAmplifier[index].streaming.spotify.email = jsonObj[2].spotify_email;
                            if (index === soloAmplifierSelected)
                                $("#spotifyEmailInput").val(arrayAmplifier[index].streaming.spotify.email);
                            // console.log("UPDATE SPOTIFY EMAIL FROM SUBSCRIPTION");
                        }
                        if (arrayAmplifier[index].streaming.spotify.password != jsonObj[2].spotify_password) {
                            arrayAmplifier[index].streaming.spotify.password = jsonObj[2].spotify_password;
                            if (index === soloAmplifierSelected)
                                $("#spotifyPasswordInput").val(arrayAmplifier[index].streaming.spotify.password);
                            // console.log("UPDATE SPOTIFY PASSWORD FROM SUBSCRIPTION");
                        }

                        if (arrayAmplifier[index].streaming.spotify.enable != jsonObj[2].spotify_enable) {
                            arrayAmplifier[index].streaming.spotify.enable = jsonObj[2].spotify_enable;
                            if (index === soloAmplifierSelected) {
                                $("#spotifyEnableInput").prop("checked", arrayAmplifier[index].streaming.spotify.enable);
                                $("#spotifyEnableInput").attr("value", arrayAmplifier[index].streaming.spotify.enable);
                            }
                        }

                        if (arrayAmplifier[index].streaming.airplay.device_name != jsonObj[2].airplay_device_name) {
                            arrayAmplifier[index].streaming.airplay.device_name = jsonObj[2].airplay_device_name;
                            if (index === soloAmplifierSelected)
                                $("#airplayNameInput").val(arrayAmplifier[index].streaming.airplay.device_name);
                            // console.log("UPDATE AIRPLAY DEVICE NAME FROM SUBSCRITPTION");
                        }

                        if (arrayAmplifier[index].streaming.airplay.password != jsonObj[2].airplay_password) {
                            arrayAmplifier[index].streaming.airplay.password = jsonObj[2].airplay_password;
                            if (index === soloAmplifierSelected)
                                $("#spotifyPasswordInput").val(arrayAmplifier[index].streaming.airplay.password);
                            // console.log("UPDATE AIRPLAY PASSWORD FROM SUBSCRITPTION");
                        }

                        if (arrayAmplifier[index].streaming.airplay.enable != jsonObj[2].airplay_enable) {
                            arrayAmplifier[index].streaming.airplay.enable = jsonObj[2].airplay_enable;
                            if (index === soloAmplifierSelected) {
                                $("#airplayEnableInput").prop("checked", arrayAmplifier[index].streaming.airplay.enable);
                                $("#airplayEnableInput").attr("value", arrayAmplifier[index].streaming.airplay.enable);
                            }
                        }

                        if (arrayAmplifier[index].label != jsonObj[2].discovery_id) {
                            arrayAmplifier[index].label = jsonObj[2].discovery_id
                            if (index === soloAmplifierSelected) {
                                $("#amplifierDescription").val(arrayAmplifier[index].label);
                                $(".topMenuTitle").html("" + arrayAmplifier[soloAmplifierSelected].label + " : " + arrayAmplifier[soloAmplifierSelected].network.lan.ip);
                            }
                            // console.log("UPDATE AMPLIFIER DESCRIPTION FROM SUBSCRIPTION");
                        }

                        if (arrayAmplifier[index].amp_stage_disabled != jsonObj[2].amp_stage_disabled) {
                            arrayAmplifier[index].amp_stage_disabled = jsonObj[2].amp_stage_disabled;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge12 != jsonObj[2].bridge_mode_12) {
                            arrayAmplifier[index].bridge.bridge12 = jsonObj[2].bridge_mode_12;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge34 != jsonObj[2].bridge_mode_34) {
                            arrayAmplifier[index].bridge.bridge34 = jsonObj[2].bridge_mode_34;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge56 != jsonObj[2].bridge_mode_56) {
                            arrayAmplifier[index].bridge.bridge56 = jsonObj[2].bridge_mode_56;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge78 != jsonObj[2].bridge_mode_78) {
                            arrayAmplifier[index].bridge.bridge78 = jsonObj[2].bridge_mode_78;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge910 != jsonObj[2].bridge_mode_910) {
                            arrayAmplifier[index].bridge.bridge910 = jsonObj[2].bridge_mode_910;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge1112 != jsonObj[2].bridge_mode_1112) {
                            arrayAmplifier[index].bridge.bridge1112 = jsonObj[2].bridge_mode_1112;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge1314 != jsonObj[2].bridge_mode_1314) {
                            arrayAmplifier[index].bridge.bridge1314 = jsonObj[2].bridge_mode_1314;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        if (arrayAmplifier[index].bridge.bridge1516 != jsonObj[2].bridge_mode_1516) {
                            arrayAmplifier[index].bridge.bridge1516 = jsonObj[2].bridge_mode_1516;
                            if (index === soloAmplifierSelected) {
                                // $.fn.setVisualBridge();
                                $.fn.setDataSoloOutputUpdate();
                            }
                        }

                        var updateHiZ = 0;
                        var chCount = channelCount;
                        if ($.fn.getModel(index) == 7 || $.fn.getModel(index) == 8) {
                            chCount = channel16Count;
                        }
                        for (var z = 0; z < chCount; z++) {
                            if (arrayAmplifier[index].hiZ[z] != jsonObj[2].high_impedance_filter[z]) {
                                arrayAmplifier[index].hiZ[z] = jsonObj[2].high_impedance_filter[z];
                                updateHiZ++;
                            }
                        }
                        if (updateHiZ > 0) {
                            $.fn.setDataSoloHiZ(0, 100);
                        }

                        if (arrayAmplifier[index].frontPanelLocked != jsonObj[2].front_lock)
                            arrayAmplifier[index].frontPanelLocked = jsonObj[2].front_lock;

                        $.fn.runAfterFirstSubscription(index);
                    } else {
                        subscriptionUpdate--;
                    }
                    break;
                    // }
                default:
                    if (msgR.arg1 != "OK")
                    // console.log("defdiscowork:" + data.command);
                        break;
            }
        }
    } catch (e) {
        // console.log("error parsing:" + e);
    }
}

function download(content, fileName, contentType) {
    const a = document.createElement("a");
    var ciphertext = CryptoJS.AES.encrypt(content, presetKey);
    const file = new Blob([ciphertext], { type: contentType });
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}

$.fn.arrayToMessage = function(arrayCmd) {
    var ret = "";
    ret = commandsToJSON(arrayCmd);
    return ret;
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

$.fn.sendWebSocketData = function(index, data) {
    if (data.toString().indexOf("readback") === -1 && data.toString().indexOf("neighbour") === -1 && data.toString().indexOf("get_solo_channel_name") === -1 && data.toString().indexOf("subscribe") === -1 && data.toString().indexOf("names") === -1 && data.toString().indexOf("\"arg1\": 0") > -1)
        subscriptionUpdate = delayBetweenSubscriptionAfterUpdate;
    if (discoveryWorker[index].status === 1) {
        try {
            // if (data.toString().indexOf("set_group_gain") != -1)
            // console.log(data);
            var obj = new Object();
            obj.data = data;
            discoveryWorker[index].worker.postMessage(obj);
            return 0;
        } catch (err) {
            // console.log("WS Send Error : " + err);
            return -1;
        }
    }
}

$.fn.sendStringWS = function(command, arg1, arg2, arg3, arg4) {
    var temp_request = new commandConstructor();
    //SET COMMAND OBJECT PARAMETERS
    temp_request.command = command;
    temp_request.query_arg1 = arg1;
    temp_request.query_arg2 = arg2;
    temp_request.query_arg3 = arg3;
    temp_request.query_arg4 = arg4;

    //SET THE query_time TO RANDOMLY GENERATE TIMESTAMP
    temp_request.query_time = Date.now();
    temp_request.query_id = $.fn.getRandomValue();
    var send_text = stringsToJSON(temp_request);
    // console.log(send_text);
    $.fn.sendWebSocketData(arg1, send_text);
}

$.fn.sendCommandWS = function(command, arg1, arg2, arg3, arg4) {

    var temp_timestamp = 0;
    var temp_request = new commandConstructor();
    //TEST IF WEBSOCKET IS CREATED
    if (discoveryWorker[arg1].status == 1) {
        //CREATE A NEW COMMAND OBJECT

        //SET COMMAND OBJECT PARAMETERS
        temp_request.command = command;
        temp_request.query_arg1 = arg1;
        temp_request.query_arg2 = arg2;
        temp_request.query_arg3 = arg3;
        temp_request.query_arg4 = arg4;

        //SET THE query_time TO RANDOMLY GENERATE TIMESTAMP
        temp_request.query_time = Date.now();
        temp_request.query_id = $.fn.getRandomValue();

        if (lastCommand != null) {
            //IF COMMAND SEND MORE THAN "delayBetweenCommand" MS BEFORE
            if (Math.abs(temp_request.query_time - lastCommand.query_time) > delayBetweenCommand) {
                //SEND COMMAND
                var send_text = commandToJSON(temp_request);
                // console.log("SEND WS:" + send_text);
                if ($.fn.sendWebSocketData(arg1, send_text) == 0) {
                    temp_request.status = 1;
                    if (temp_request.command != cmd_get_readback && temp_request.command != cmd_get_neighbour_list)
                        request_pool[arg1].push(temp_request);
                }
            } else {
                // console.log("command too close : " + temp_request.command + " // delay : " + Math.abs(temp_request.query_time - lastCommand.query_time));
                Singleton.getCountdown().time = delayBetweenCommand;
                if (Singleton.getCountdown().enable === false)
                    $.fn.sendLastCommand();
            }
        } else {
            //IF FIRST SENT COMMAND, SEND IT 

            //SEND COMMAND
            var send_text = commandToJSON(temp_request);
            if ($.fn.sendWebSocketData(arg1, send_text) == 0) {
                temp_request.status = 1;
                if (temp_request.command != cmd_get_readback && temp_request.command != cmd_get_neighbour_list)
                    request_pool[arg1].push(temp_request);
            }
        }
    } else {
        temp_timestamp = -1
    }
    if (temp_request.command !== cmd_get_readback && temp_request.command !== cmd_get_neighbour_list) {
        lastCommand = temp_request;
    }
    return temp_timestamp;
}

$.fn.getRandomValue = function() {
    let ret = 0;
    let rnd = 0;
    rnd = Math.random();
    ret = Math.floor((Date.now() * (rnd * 463)) + (rnd * 569));
    return ret;
}

$.fn.getCommandFromArgs = function(cmd, arg1, arg2, arg3, arg4) {
    var temp_request = new commandConstructor();

    //SET COMMAND OBJECT PARAMETERS
    temp_request.command = cmd;
    temp_request.query_arg1 = arg1;
    temp_request.query_arg2 = arg2;
    temp_request.query_arg3 = arg3;
    temp_request.query_arg4 = arg4;

    if (command != cmd_get_readback)
        temp_request.query_id = $.fn.getRandomValue();
    else
        temp_request.query_id = 1;
    if (command != cmd_get_readback)
        temp_request.query_time = Date.now();
    else
        temp_request.query_time = 1;

    return temp_request;
}

$.fn.sendCommandsWS = function(arrayCmd) {
    if (lastCommands != null) {
        //IF COMMAND SEND MORE THAN "delayBetweenCommands" MS BEFORE
        if (Math.abs(arrayCmd[0].query_time - lastCommands[0].query_time) > delayBetweenCommands) {
            lastCommands = arrayCmd;
            var send_text = commandsToJSON(arrayCmd);
            if ($.fn.sendWebSocketData(arrayCmd[0].query_arg1, send_text) === 0) {
                for (var i = 0; i < arrayCmd.length; i++) {
                    if (i > -1) {
                        arrayCmd[i].status = 1;
                    }
                    request_pool[arrayCmd[0].query_arg1].push(arrayCmd[i]);
                }
            }
        } else {
            // console.log("command too close : " + arrayCmd[0].command);
            lastCommands = arrayCmd;
            Singletons.getCountdown().time = delayBetweenCommands + 1;
            if (Singletons.getCountdown().enable === false)
                $.fn.sendLastCommands();
        }
    } else {
        lastCommands = arrayCmd;
        //IF FIRST SENT COMMAND, SEND IT 
        var send_text = commandsToJSON(arrayCmd);
        if ($.fn.sendWebSocketData(arrayCmd[0].query_arg1, send_text) === 0) {
            for (var i = 0; i < arrayCmd.length; i++) {
                if (i > -1) {
                    arrayCmd[i].status = 1;
                }
                request_pool[arrayCmd[0].query_arg1].push(arrayCmd[i]);
            }
        }
    }
}

$.fn.sendLastCommand = function() {
    if (Singleton.getCountdown().time > 0) {
        Singleton.getCountdown().enable = true;
        Singleton.getCountdown().time = Singleton.getCountdown().time - 5;
        setTimeout($.fn.sendLastCommand, 5);
    } else {
        // console.log("send last command : " + lastCommand.toString());
        var send_text = commandToJSON($.fn.getCommandFromArgs(lastCommand.command, lastCommand.query_arg1, lastCommand.query_arg2, lastCommand.query_arg3, lastCommand.query_arg4));
        if (lastCommand.command.indexOf("group") > -1) {
            for (var i = 0; i < arrayAmplifier.length; i++) {
                if (returnGroupGroupRegistration(i, groupGroupSelected) > 0 || send_text.toString().indexOf("set_assign_channel_to_group") > -1) {
                    let send = commandToJSON($.fn.getCommandFromArgs(lastCommand.command, lastCommand.query_arg1, lastCommand.query_arg2, lastCommand.query_arg3, lastCommand.query_arg4));
                    $.fn.sendWebSocketData(i, send);
                }
            }
        } else {
            if ($.fn.sendWebSocketData(lastCommand.query_arg1, send_text) === 0) {
                lastCommand.status = 1;
                request_pool[lastCommand.query_arg1].push(lastCommand);
            }
        }
        Singleton.getCountdown().enable = false;
    }
}

//CREATE UNIQUE COUNTDOWN FOR LAST COMMAND SEND
var Singleton = (function() {
    var countdown;

    function createCountdown() {
        var cd = new Object();
        cd.time = 0;
        cd.enable = false;
        return cd;
    }

    return {
        getCountdown: function() {
            if (!countdown) {
                countdown = createCountdown();
            }
            return countdown;
        }
    };
})();

$.fn.sendLastCommands = function() {
    if (Singletons.getCountdown().time > 0) {
        Singletons.getCountdown().enable = true;
        Singletons.getCountdown().time = Singletons.getCountdown().time - 5;
        setTimeout($.fn.sendLastCommands, 5);
    } else {

        if (lastCommands[0].command.indexOf("group") > -1) {
            for (var i = 0; i < arrayAmplifier.length; i++) {
                let send = commandsToJSON(lastCommands);
                if (returnGroupGroupRegistration(i, groupGroupSelected) > 0 || send.toString().indexOf("set_assign_channel_to_group") > -1)
                    $.fn.sendWebSocketData(i, send);
            }
        } else {
            var send_text = commandsToJSON(lastCommands);
            if ($.fn.sendWebSocketData(lastCommands[0].query_arg1, send_text) === 0) {
                for (var i = 0; i < lastCommands.length; i++) {
                    if (i > -1) {
                        lastCommands[i].status = 1;
                    }
                    request_pool[lastCommands[0].query_arg1].push(lastCommands[i]);
                }
            }
        }
        Singletons.getCountdown().enable = false;
    }
}

//CREATE UNIQUE COUNTDOWN FOR LAST COMMAND SEND
var Singletons = (function() {
    var countdown;

    function createCountdown() {
        var cd = new Object();
        cd.time = 0;
        cd.enable = false;
        return cd;
    }

    return {
        getCountdown: function() {
            if (!countdown) {
                countdown = createCountdown();
            }
            return countdown;
        }
    };
})();

$.fn.receiveCommandWS = function(event) {
    var msg = null;
    var i = -1;
    //TEST IF JSON RESPONSE IS A VALID JSON FILE
    try {
        if (event.data != "JSON is not valid.") {
            msg = JSON.parse(event.data);
            if (msg) {
                i = -1
                var msgR = JSON.parse(event.data)
                    //IF MESSAGE IS AN ANSWER FROM THE UI INTERFACE
                if (parseInt(msgR.query_time) > 0) {
                    switch (msgR.command) {
                        case cmd_get_neighbour_list:
                            try {
                                var files = JSON.parse(msgR.arg2);
                                if (discoveryList.length < 1) {

                                    discoveryList = new Array(files.length);
                                    for (var c = 0; c < files.length; c++) {
                                        discoveryList[c] = new discoveredAmpConstructor(files[c]);
                                    }
                                    $.fn.setupOverviewSolo($.fn.getModel());
                                    $.fn.setupSourceSolo($.fn.getModel());
                                } else if (discoveryList.length != files.length) {
                                    for (var d = 0; d < (files.length - discoveryList.length); d++) {
                                        discoveryList.push(new discoveredAmpConstructor(files[discoveryList.length + d]));
                                    }
                                } else if (discoveryList.length === files.length) {
                                    for (var e = 0; e < discoveryList.length; e++) {
                                        if (discoveryList[e].desc != files[e].desc && e > 0) {
                                            discoveryList[e].desc = files[e].desc;
                                            let idDest1 = "#assignGroupTabAmpName" + e;
                                            let idDest2 = "#groupAssignAmpSelectedName";
                                            if ($(idDest1))
                                                $(idDest1).html(discoveryList[e].desc);
                                            if (groupAssignAmplifierSelected === e) {
                                                $(idDest2).html(discoveryList[e].desc);
                                            }
                                        }
                                        discoveryList[e].hw_addr = files[e].hw_addr;
                                        if (discoveryList[e].ip_addr != files[e].ip_addr) {
                                            let idDest3 = "#dldcds" + e;
                                            discoveryList[e].ip_addr = files[e].ip_addr;
                                            if ($(idDest3))
                                                $(idDest3).html(discoveryList[e].ip_addr);
                                        }
                                        discoveryList[e].alive = files[e].alive;
                                        discoveryList[e].last_report_time = files[e].last_report_time;
                                        discoveryList[e].model = files[e].model;
                                        discoveryList[e].cloud_device_name = files[e].cloud_device_name;
                                    }
                                }
                                if (loginLocal && ws_ip != discoveryList[0].ip_addr)
                                    discoveryList[0].ip_addr = ws_ip;
                            } catch (e) {
                                // console.log("Fail to parse get_neighbour_list");
                            }
                            // $.fn.setDiscoverySource();

                            // $.fn.setupOverviewSolo($.fn.getModel());

                            // $.fn.setupSourceSolo($.fn.getModel());

                            break;
                        case cmd_get_lan_config:
                            var jsonObj = msgR.arg2;
                            if (arrayAmplifier[0].network.lan.ip != jsonObj.ip) {
                                arrayAmplifier[0].network.lan.ip = jsonObj.ip;
                                $("#lanIpInput").val(arrayAmplifier[0].network.lan.ip);
                            }
                            if (arrayAmplifier[0].network.lan.mask != jsonObj.mask) {
                                arrayAmplifier[0].network.lan.mask = jsonObj.mask;
                                $("#lanMaskInput").val(arrayAmplifier[0].network.lan.mask);
                            }
                            if (arrayAmplifier[0].network.lan.gw != jsonObj.gateway) {
                                arrayAmplifier[0].network.lan.gw = jsonObj.gateway;
                                $("#lanGatewayInput").val(arrayAmplifier[0].network.lan.gw);
                            }
                            if (arrayAmplifier[0].network.lan.dhcp != jsonObj.dhcp) {
                                arrayAmplifier[0].network.lan.dhcp = jsonObj.dhcp;
                                if (jsonObj.dhcp) {
                                    $("#lanDhcpEnable").prop("checked", true);
                                    $("#lanDhcpEnable").attr("value", true);
                                } else {
                                    $("#lanDhcpEnable").prop("checked", false);
                                    $("#lanDhcpEnable").attr("value", false);
                                }
                            }

                            if ($("#lanIpInput").val() != arrayAmplifier[0].network.lan.ip)
                                $("#lanIpInput").val(arrayAmplifier[0].network.lan.ip);
                            if ($("#lanMaskInput").val() != arrayAmplifier[0].network.lan.mask)
                                $("#lanMaskInput").val(arrayAmplifier[0].network.lan.mask);
                            if ($("#lanGatewayInput").val() != arrayAmplifier[0].network.lan.gw)
                                $("#lanGatewayInput").val(arrayAmplifier[0].network.lan.gw);

                            // $.fn.setDiscoverySource();
                            $.fn.runAfterFirstDiscovery();
                            break;
                        case cmd_oem_get_status:
                            if (msgR.arg2) {
                                var temp = msgR.arg2;
                                if (temp.oem_code_enable === true) {
                                    arrayAmplifier[0].oem = true;
                                }
                            }
                        default:
                            break;
                    }
                }
            }
        } else
            console.log("JSON NOT VALID");
    } catch (e) {
        if (i > -1)
            console.log("error in JSON parse : " + e + " // msg : " + msg + " // request : " + request_pool[i].toString());
        else
            console.log("error in JSON parse : " + e + " // msg : " + msg);
    }
}

$.fn.poolMonitor = function() {
    for (var t = 0; t < arrayAmplifier.length; t++) {
        if (request_pool[t] != null && request_pool[t].length > 0) {
            var deleteArray = new Array();
            for (var i = 0; i < request_pool[t].length; i++) {
                switch (parseInt(request_pool[t][i].status)) {
                    case 0:
                        break;
                    case 1:
                        request_pool[t][i].status = 4;
                        break;
                    case 2:
                        request_pool[t][i].status = 3;
                        break;
                    case 3:
                        deleteArray.push(i);
                        break;
                    case 4: //SEND COMMAND
                        request_pool[t][i].status = 7;
                        break;
                    case 5:
                        request_pool[t][i].status = 7;
                        break;
                    case 6: //SEND COMMAND
                        request_pool[t][i].status = 7;
                        break;
                    case 7:
                        deleteArray.push(i);
                        break;
                    default:
                        break;
                }
            }
            for (var j = 0; j < deleteArray.length; j++) {
                request_pool[t].splice(deleteArray[j], 1);
            }
        }
    }
    setTimeout(function() { $.fn.poolMonitor() }, poolMonitorDelay);
}

function amplifierFinder(array, value) {
    for (var i = 0; i < array.length; i += 1) {
        if (array[i].label === value) {
            return i;
        }
    }
    return -1;
}

function hostpotConvert(config) {
    var ret = "";
    ret += "{\"ssid\":\"" + config.ssid + "\"";
    ret += ",\"wpa_version\":" + config.wpa_version;
    ret += ",\"channel\":" + config.channel;
    ret += ",\"password\":\"" + config.password + "\"}";
    return ret;
}

function testClick() {
    console.log("hello world test click");
}

$.fn.setUpdateFile = function() {
    if (fileCheck === true) {
        updateFile = updateTempFile[0];
        // console.log("update file set");
    }
}

$.fn.uploadPreset = function(source) {
    var sourceString = JSON.stringify(source);
    sourceString = sourceString.replaceAll("\"", "\\\"");
    if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        $.fn.sendStringWS(cmd_upload_all_speaker_preset_file, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + "/" + updateJsonName, "null", sourceString);
    } else {
        $.fn.sendStringWS(cmd_upload_speaker_preset_file, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + "/" + updateJsonName, "null", sourceString);
    }
}
$.fn.uploadGlobalPreset = function(source) {
    var sourceString = JSON.stringify(source);
    sourceString = sourceString.replaceAll("\"", "\\\"");
    $.fn.sendStringWS(cmd_upload_global_preset_file, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name + "/" + updateJsonName, "null", sourceString);
}

$.fn.uploadFolderPreset = function(source) {
    var sourceString = JSON.stringify(source);
    sourceString = sourceString.replaceAll("\"", "\\\"");
    if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        $.fn.sendStringWS(cmd_set_all_speaker_preset_files_from_folder, 0, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name, "null", sourceString);
    } else {
        $.fn.sendStringWS(cmd_set_speaker_preset_files_from_folder, 0, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name, "null", sourceString);
    }
}

$.fn.checkUpdateSpeakerPreset = function(source) {
    // TEST CONTAIN KEYS ON JSON

    if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        if (Object.keys(source).length != 4) {
            return 1;
        } else {
            ret = "";
            for (var i = 0; i < channelCount; i++) {
                ret += $.fn.checkSpeakerPresetContent(source[i]);
            }
            if (ret == "0000")
                ret = 0;
            return ret;
        }
    } else {
        if (Object.keys(source).length != 10) {
            return 2;
        } else {
            return $.fn.checkSpeakerPresetContent(source);
        }
    }
}

$.fn.checkSpeakerPresetContent = function(source) {

    if (!source.hasOwnProperty("gain"))
        return "GAIN FIELD IS MISSING";
    if (!source.hasOwnProperty("polarity"))
        return "POLARITY FIELD IS MISSING";

    if (!source.hasOwnProperty("delay_enable"))
        return "DELAYENABLE FIELD IS MISSING";
    if (!source.hasOwnProperty("delay_value"))
        return "DELAY VALUE FIELD IS MISSING";

    if (!source.hasOwnProperty("peq"))
        return "PEQS FIELD IS MISSING";
    if (source.peq.length != peqCount)
        return "PEQs COUNT VALUE ERROR";

    for (var i = 0; i < peqCount; i++) {
        if (!source.peq[i].hasOwnProperty("enable"))
            return "ENABLE PEQ" + i + " FIELD IS MISSING";
        if (!source.peq[i].hasOwnProperty("type"))
            return "TYPE PEQ" + i + " FIELD IS MISSING";
        if (!source.peq[i].hasOwnProperty("freq"))
            return "FREQ PEQ" + i + " FIELD  IS MISSING";
        if (!source.peq[i].hasOwnProperty("gain"))
            return "GAIN PEQ" + i + " FIELD  IS MISSING";
        if (!source.peq[i].hasOwnProperty("q"))
            return "Q PEQ" + i + " FIELD IS MISSING";
    }

    if (!source.hasOwnProperty("xover_hp_filter"))
        return "XOVER HP FILTER FIELDs IS MISSING";
    if (!source.xover_hp_filter.hasOwnProperty("xover_hp_enable"))
        return "XOVER HP ENABLE FIELD IS MISSING";
    if (!source.xover_hp_filter.hasOwnProperty("xover_hp_type"))
        return "XOVER HP TYPE FIELD IS MISSING";
    if (!source.xover_hp_filter.hasOwnProperty("xover_hp_freq"))
        return "XOVER HP FREQ FIELD IS MISSING";
    if (!source.hasOwnProperty("xover_lp_filter"))
        return "XOVER LP FIELDs IS MISSING";
    if (!source.xover_lp_filter.hasOwnProperty("xover_lp_enable"))
        return "XOVER LP ENABLE FIELD IS MISSING";
    if (!source.xover_lp_filter.hasOwnProperty("xover_lp_type"))
        return "XOVER LP TYPE FIELD IS MISSING";
    if (!source.xover_lp_filter.hasOwnProperty("xover_lp_freq"))
        return "XOVER LP FREQ FIELD IS MISSING";

    if (!source.hasOwnProperty("fir_table"))
        return "FIR TABLE FIELD IS MISSING";

    if (!source.hasOwnProperty("lim_rms"))
        return "LIMITER RMS FIELDS IS MISSING";
    if (!source.lim_rms.hasOwnProperty("lim_rms_thres"))
        return "LIMITER RMS THRES FIELD IS MISSING";
    if (!source.lim_rms.hasOwnProperty("lim_rms_attack"))
        return "LIMITER RMS ATTACK FIELD IS MISSING";
    if (!source.lim_rms.hasOwnProperty("lim_rms_release"))
        return "LIMITER RMS RELEASE FIELD IS MISSING";

    if (!source.hasOwnProperty("lim_peak"))
        return "LIMITER FIELDS IS MISSING";
    if (!source.lim_peak.hasOwnProperty("lim_peak_thres"))
        return "LIMITER PEAK THRES FIELD IS MISSING";
    if (!source.lim_peak.hasOwnProperty("lim_peak_release"))
        return "LIMITER PEAK RELEASE FIELD IS MISSING";

    // TEST VALUE ON JSON
    if (source.gain < gainScaleMin || source.gain > gainScaleMax)
        return "GAIN VALUE OUT OF RANGE";
    if (typeof source.polarity != "boolean")
        return "POLARITY ENABLE NOT BOOLEAN";

    if (source.delay_value < delayScaleMin || source.delay_value > delayScaleMax)
        return "DELAY VALUE OUT OF RANGE";
    if (typeof source.delay_enable != "boolean")
        return "DELAY ENABLE NOT BOOLEAN";

    for (var i = 0; i < peqCount; i++) {
        if (typeof source.peq[i].enable != "boolean")
            return "PEQ" + i + " ENABLE NOT BOOLEAN";
        if (source.peq[i].type < typeScaleMinPEQ || source.peq[i].type > typeScaleMaxPEQ)
            return "TYPE PEQ" + i + " OUT OF RANGE";
        if (source.peq[i].freq < freqScaleMinPEQ || source.peq[i].freq > freqScaleMaxPEQ)
            return "FREQ PEQ" + i + " OUT OF RANGE";
        if (source.peq[i].gain < gainScaleMinPEQ || source.peq[i].gain > gainScaleMaxPEQ)
            return "GAIN PEQ" + i + "VALUE OUT OF RANGE";
        if (source.peq[i].q < qScaleMinPEQ || source.peq[i].q > qScaleMaxPEQ)
            return "Q PEQ" + i + "VALUE OUT OF RANGE ";
    }

    if (typeof source.xover_hp_filter.xover_hp_enable != "boolean")
        return "XOVER HP ENABLE NOT BOOLEAN";
    if (source.xover_hp_filter.xover_hp_type < typeScaleMinXOVER || source.xover_hp_filter.xover_hp_type > typeScaleMaxXOVER)
        return "XOVER HP TYPE OUT OF RANGE";
    if (source.xover_hp_filter.xover_hp_freq < freqScaleMinPEQ || source.xover_hp_filter.xover_hp_freq > freqScaleMaxPEQ)
        return "XOVER HP FREQ OUT OF RANGE";

    if (typeof source.xover_lp_filter.xover_lp_enable != "boolean")
        return "XOVER LP ENABLE NOT BOOLEAN";
    if (source.xover_lp_filter.xover_lp_type < typeScaleMinXOVER || source.xover_lp_filter.xover_lp_type > typeScaleMaxXOVER)
        return "XOVER LP TYPE OUT OF RANGE";
    if (source.xover_lp_filter.xover_lp_freq < freqScaleMinPEQ || source.xover_lp_filter.xover_lp_freq > freqScaleMaxPEQ)
        return "XOVER LP FREQ OUT OF RANGE";

    if (source.fir_table.length < firLengthMin || source.fir_table.length > firLengthMax)
        return "FIR TABLE WRONG SIZE";
    for (var i = 0; i < source.fir_table.length; i++) {
        if (source.fir_table[i] < firScaleMin || source.fir_table[i] > firScaleMax)
            return "FIR VALUE " + i + " OUT OF RANGE";
    }

    if (source.lim_rms.lim_rms_thres < rmsThresScaleMinPreset || source.lim_rms.lim_rms_thres > rmsThresScaleMaxPreset)
        return "LIM RMS THRES OUT OF RANGE";
    if (source.lim_rms.lim_rms_attack < rmsAttackScaleMin || source.lim_rms.lim_rms_attack > rmsAttackScaleMax)
        return "LIM RMS ATTACK OUT OF RANGE";
    if (source.lim_rms.lim_rms_release < rmsReleaseScaleMin || source.lim_rms.lim_rms_release > rmsReleaseScaleMax)
        return "LIM RMS RELEASE OUT OF RANGE";

    if (source.lim_peak.lim_peak_thres < peakThresScaleMinPreset || source.lim_peak.lim_peak_thres > peakThresScaleMaxPreset)
        return "LIM PEAK THRES OUT OF RANGE";
    if (source.lim_peak.lim_peak_release < peakReleaseScaleMin || source.lim_peak.lim_peak_release > peakReleaseScaleMax)
        return "LIM PEAK RELEASE OUT OF RANGE";

    return 0;
}

//RUN ONCE AFTER RECEIVING THE FIRST SUBSCRIPTION PACKET
$.fn.runAfterFirstSubscription = function(index) {
    if (discoveryWorker[index].subscription === 0) {
        discoveryWorker[index].subscription = 1;
        let arCmd = new Array();
        arCmd.push($.fn.getCommandFromArgs("start_readback", 0, "null", "null", "null"));
        arCmd.push($.fn.getCommandFromArgs(cmd_get_global_preset_folder_names, 0, "null", "null", "null"));
        arCmd.push($.fn.getCommandFromArgs(cmd_get_about, 0, "null", "null", "null"));
        arCmd.push($.fn.getCommandFromArgs(cmd_get_lan_config, 0, "null", "null", "null"));
        let obj = new Object();
        obj.data = commandsToJSON(arCmd);
        discoveryWorker[index].worker.postMessage(obj);

        // $.fn.setupChannelButton();

        // $.fn.setupDiscoverySolo();
        if (index == 0)
            $.fn.poolDiscovery();
        // if (arrayAmplifier[soloAmplifierSelected].label.length > 0)
        $(".topMenuTitle").html("" + arrayAmplifier[soloAmplifierSelected].label + " : " + arrayAmplifier[soloAmplifierSelected].network.lan.ip);
        setTimeout(function() {
            $("#openHomeButton").trigger("click");
        }, 1000);
    }

}

//RUN ONCE AFTER RECEIVING THE FIRST MONITOR PACKET
$.fn.runAfterFirstDiscovery = function() {
    if (runDiscovery === false) {
        runDiscovery = true;
        $.fn.setupGroupAssign();
        $.fn.createDiscoveryWorker();
    }
}

jQuery(function() {

    screenHeight = window.innerHeight;
    screenWidth = window.innerWidth;
    screenScrollHeight = document.documentElement.scrollHeight;

    readBackLimiter[0] = new Array(readBackLimiterCount);
    readBackLimiter[1] = new Array(readBackLimiterCount);
    readBackLimiter[2] = new Array(readBackLimiterCount);
    readBackLimiter[3] = new Array(readBackLimiterCount);

    $("body").on("dblclick", "span", function(e) {
        // console.log("double click");
        var id = e.target.parentNode.id;
        // console.log(id);
        if (id.indexOf("sliderVerticalGainGroup") > -1) {
            //GAIN GROUP
            arrayGroup[groupGroupSelected].gain.gain = 0.0;
            $.fn.setDataGroupGain(groupGroupSelected, 1);
        } else if (id.indexOf("sliderVerticalDelayGroup") > -1) {
            //GAIN GROUP
            arrayGroup[groupGroupSelected].delay.delay = 0.0;
            $.fn.setDataGroupDelay(groupGroupSelected, 1);
        } else if (id.indexOf("sliderVertical") > -1) {
            //GAIN SLIDER
            var num = parseInt(id.match(/(\d+)/g).map(Number));
            arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = 0.0;
            $.fn.setDataSoloGain(num, 1);
        } else if (id.indexOf("sliderMixerVertical") > -1) {
            var num = parseInt(id.match(/(\d+)/g).map(Number));
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = 0.0;
            $.fn.setDataSoloMixer(0, num);
        } else if (id.indexOf("sliderDelayVertical") > -1) {
            //DELAY SLIDER
            var num = parseInt(id.match(/(\d+)/g).map(Number));
            arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = 0.0;
            $.fn.setDataSoloDelay(num, 1);
        } else if (id.indexOf("sliderHorizontalFreq") > -1) {
            var num = parseInt(id.match(/(\d+)/g).map(Number));
            if (displaySoloGroup === 0)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency = eqFreqDefaultInit[num];
            else
                arrayGroup[groupGroupSelected].peq[num].frequency = eqFreqDefaultInit[num];
            $.fn.setDataSoloPEQ(num, 2);
        } else if (id.indexOf("sliderHorizontalGain") > -1) {
            var num = parseInt(id.match(/(\d+)/g).map(Number));
            if (displaySoloGroup === 0)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain = 0.0;
            else
                arrayGroup[groupGroupSelected].peq[num].gain = 0.0;
            $.fn.setDataSoloPEQ(num, 3);
        } else if (id.indexOf("sliderHorizontalQ") > -1) {
            var num = parseInt(id.match(/(\d+)/g).map(Number));
            if (displaySoloGroup === 0)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q = eqQDefault;
            else
                arrayGroup[groupGroupSelected].peq[num].q = eqQDefault;
            $.fn.setDataSoloPEQ(num, 4);
        }
    });

    //SIGNAL GENERATOR FREQUENCY GENERATOR FREQUENCY FIELD
    $("body").on("change", "#siggenSineFreqInput", function(e) {
        if (!$.isNumeric(this.value)) {
            alert("FREQUENCY VALUE BETWEEN " + freqGenFrequencyMin + " and " + freqGenFrequencyMax + "Hz");
            $("#siggenSineFreqInput").val(arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.frequency);
        } else {
            if (this.value <= freqGenFrequencyMin)
                arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.frequency = freqGenFrequencyMin;
            else if (this.value > freqGenFrequencyMax)
                arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.frequency = freqGenFrequencyMax;
            else
                arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.frequency = parseInt(parseInt(this.value).toFixed(0));
            $.fn.setDataSoloSigGen(0, 99);
        }
    });

    //SIGNAL GENERATOR FREQUENCY GENERATOR GAIN FIELD
    $("body").on("change", "#siggenSineGainInput", function(e) {
        if (!$.isNumeric(this.value)) {
            alert("GAIN VALUE BETWEEN " + freqGenGainMin + " and " + freqGenGainMax + "Hz")
            $("#siggenSineGainInput").val(arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.gain);
        } else {
            if (this.value <= freqGenGainMin)
                arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.gain = freqGenGainMin;
            else if (this.value > freqGenGainMax)
                arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.gain = freqGenGainMax;
            else
                arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.gain = parseInt(parseInt(this.value).toFixed(0));
            $.fn.setDataSoloSigGen(1, 99);
        }
    });

    //SIGNAL GENERATOR PINK NOISE GAIN FIELD
    $("body").on("change", "#siggenPinkGainInput", function(e) {
        if (!$.isNumeric(this.value)) {
            alert("GAIN VALUE BETWEEN " + pinkNoiseGainMin + " and " + pinkNoiseGainMax + "Hz")
            $("#siggenPinkGainInput").val(arrayAmplifier[soloAmplifierSelected].signalGenerator.pinkNoise.gain);
        } else {
            if (this.value <= pinkNoiseGainMin)
                arrayAmplifier[soloAmplifierSelected].signalGenerator.pinkNoise.gain = pinkNoiseGainMin;
            else if (this.value > pinkNoiseGainMax)
                arrayAmplifier[soloAmplifierSelected].signalGenerator.pinkNoise.gain = pinkNoiseGainMax;
            else
                arrayAmplifier[soloAmplifierSelected].signalGenerator.pinkNoise.gain = parseInt(parseInt(this.value).toFixed(0));
            $.fn.setDataSoloSigGen(2, 99);
        }
    });

    $("body").on("click", "#peqFlatApply", function(e) {
        // console.log("flat apply");
        var sendArray = new Array(0)
        var peqArray = new Array(0);
        for (var i = 0; i < peqCount; i++) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain = eqGainDefault;
            peqArray.push(i);
        }
        sendArray.push(soloChannelSelected);

        $.fn.setDataSoloPEQGain(sendArray, peqArray);

        $.fn.setDataSoloPEQ(101, 99);
    });

    $("body").on("click", "#peqDefaultApply", function(e) {
        // console.log("peq default apply");
        var sendArray = new Array(0)
        var peqArray = new Array(0);
        for (var i = 0; i < peqCount; i++) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].ena = eqEnaDefault;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].type = eqTypeDefault;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency = eqFreqDefaultInit[i];
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain = eqGainDefault;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q = eqQDefault;
            peqArray.push(i);
        }
        sendArray.push(soloChannelSelected);
        $.fn.setDataSoloPEQCopy(sendArray, peqArray);

        $.fn.setDataSoloPEQ(101, 99);
    });

    $("body").on("click", "#peqDefaultAllApply", function(e) {
        // console.log("peq default all apply");
        var sendArray = new Array(0)
        var peqArray = new Array(0);
        var amountOfChannel = channelCount;
        if ($.fn.getModel() == 7 || $.fn.getModel() == 8) {
            amountOfChannel = channel16Count;
        } else if ($.fn.getModel() == 5 || $.fn.getModel() == 6) {
            amountOfChannel = channel1Count;
        }
        for (var j = 0; j < amountOfChannel; j++) {
            for (var i = 0; i < peqCount; i++) {
                arrayAmplifier[soloAmplifierSelected].channel[j].peq.peq[i].ena = eqEnaDefault;
                arrayAmplifier[soloAmplifierSelected].channel[j].peq.peq[i].type = eqTypeDefault;
                arrayAmplifier[soloAmplifierSelected].channel[j].peq.peq[i].frequency = eqFreqDefaultInit[i];
                arrayAmplifier[soloAmplifierSelected].channel[j].peq.peq[i].gain = eqGainDefault;
                arrayAmplifier[soloAmplifierSelected].channel[j].peq.peq[i].q = eqQDefault;
                if (peqArray.length < peqCount)
                    peqArray.push(i);
            }
            sendArray.push(j);
        }
        $.fn.setDataSoloPEQCopy(sendArray, peqArray);

        $.fn.setDataSoloPEQ(101, 99);
    });

    $("body").on("click", "#peqCopySelectAll", function(e) {
        if ($(".peqCopySelected:checked").length === peqCount) {
            $(".peqCopySelected").attr("checked", false);
        } else {
            $(".peqCopySelected").attr("checked", true);
        }
    });

    $("body").on("click", "#peqCopyApply", function(e) {
        // console.log("Copy apply");
        var src = dest = peq = -1;
        var sendArray = new Array(0);
        var peqArray = new Array(0);

        // COPY FROM CHECKBOX PEQ
        $(".peqCopySelected:checked").each(function() {
            peq = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            peqArray.push(peq);
        });
        //COPY FROM RADIOBUTTON CHANNEL
        $(".peqCopyChannelSourceRadio:checked").each(function() {
            src = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        });
        // COPY TO CHECKBOX CHANNEL
        $(".peqCopyChannelDest:checked").each(function() {
            dest = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            sendArray.push(dest);
        });

        sendArray.forEach(function(copyTo) {
            peqArray.forEach(function(copyPeqFrom) {
                // console.log("copy peq" + copyPeqFrom + " to channel" + copyTo + " from channel" + src);
                arrayAmplifier[soloAmplifierSelected].channel[copyTo].peq.peq[copyPeqFrom] = arrayAmplifier[soloAmplifierSelected].channel[src].peq.peq[copyPeqFrom];
            });
        });

        $.fn.setDataSoloPEQ(101, 99);

        if (sendArray.length > 0 && peqArray.length > 0)
            $.fn.setDataSoloPEQCopy(sendArray, peqArray);

    });

    $("body").on("change", "input[type=radio][name=peqCopyOptions]", function(e) {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // console.log("source:" + num);
        $(".peqCopyChannelSourceRadio").attr("checked", false);
        $("#inlineRadio" + num).attr("checked", true);
    });

    //SET GROUP PEQS TO DEFAULT
    $("body").on("click", "#peqGroupResetCurrentApply", function(e) {
        // console.log("peq default apply");
        var sendArray = new Array(0)
        var peqArray = new Array(0);
        for (var i = 0; i < peqCount; i++) {
            arrayGroup[groupGroupSelected].peq[i].ena = eqEnaDefault;
            arrayGroup[groupGroupSelected].peq[i].type = eqTypeDefault;
            arrayGroup[groupGroupSelected].peq[i].frequency = eqFreqDefaultInit[i];
            arrayGroup[groupGroupSelected].peq[i].gain = eqGainDefault;
            arrayGroup[groupGroupSelected].peq[i].q = eqQDefault;
            peqArray.push(i);
        }
        sendArray.push(groupGroupSelected);

        $.fn.setDataGroupPEQCopy(sendArray, peqArray);

        $.fn.setDataSoloPEQ(101, 99);
    });

    $("body").on("change", "input[type=radio][name=peqCopyGroupOptions]", function(e) {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $(".peqCopyGroupSourceRadio").attr("checked", false);
        $("#inlineRadio" + num).attr("checked", true);
    });


    $("body").on("click", "#peqCopyGroupSelectAll", function(e) {
        if ($(".peqCopyGroupSelected:checked").length === peqCount) {
            $(".peqCopyGroupSelected").attr("checked", false);
        } else {
            $(".peqCopyGroupSelected").attr("checked", true);
        }
    });

    //COPY GROUP PEQ APPLY BUTTON
    $("body").on("click", "#peqCopyGroupApply", function(e) {
        // console.log("Copy apply");
        var src = dest = peq = -1;
        var sendArray = new Array(0);
        var peqArray = new Array(0);

        // COPY FROM CHECKBOX PEQ
        $(".peqCopyGroupSelected:checked").each(function() {
            peq = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            peqArray.push(peq);
        });
        //COPY FROM RADIOBUTTON CHANNEL
        $(".peqCopyGroupSourceRadio:checked").each(function() {
            src = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        });
        // COPY TO CHECKBOX CHANNEL
        $(".peqCopyGroupDest:checked").each(function() {
            dest = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            sendArray.push(dest);
        });

        sendArray.forEach(function(copyTo) {
            peqArray.forEach(function(copyPeqFrom) {
                arrayGroup[copyTo].peq[copyPeqFrom] = arrayGroup[src].peq[copyPeqFrom];
            });
        });

        if (sendArray.length > 0 && peqArray.length > 0)
            $.fn.setDataGroupPEQCopy(sendArray, peqArray);

        $.fn.setDataSoloPEQ(101, 99);
    });

    //MANAGE RMS CALCULATOR BUTTON
    $("body").on("click", "#rmsCalculator", function(e) {
        // console.log("rms calculator");
        $("#hpfRmsInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq);
        $("#hpfRmsInput").trigger("change");
        var voltRms = 0.0;
        voltRms = Math.pow(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres), 2) / loadTable[$("#rmsCalculatorOutputLoadSelect option:selected").val()];
        $("#maxRmsOutputPowerValue").val(parseFloat(voltRms.toFixed(1)));
        $("#maxRmsOutputPowerValue").trigger("change");
        $("#maxVRmsInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres);
        $("#rmsCalculatorOutputLoadSelect").val(3);
        $("#rmsCalculatorOutputLoadSelect").trigger("change");
        $("#rmsCalculatorModal").modal("show");
    });

    $("body").on("change", "#rmsCalculatorOutputLoadSelect", function(e) {
        var power = 0.0;
        if ($("#rmsCalculatorOutputLoadSelect option:selected").val() === "5") {
            $('#maxRmsOutputPowerValue').hide();
            power = 70.0;
        } else if ($("#rmsCalculatorOutputLoadSelect option:selected").val() === "6") {
            $('#maxRmsOutputPowerValue').hide();
            power = 100.0;
        } else {
            $('#maxRmsOutputPowerValue').show();
            power = parseFloat($("#maxRmsOutputPowerValue").val()) * loadTable[$("#rmsCalculatorOutputLoadSelect").val()];
            power = Math.sqrt(power)
        }
        $("#maxVRmsInput").val(power.toFixed(1));
    });

    $("body").on("change", "#maxRmsOutputPowerValue", function(e) {
        if ($.isNumeric($("#maxRmsOutputPowerValue").val())) {
            $("#maxRmsOutputPowerValue").removeClass("is-invalid");
            var power = 0.0;
            if ($("#rmsCalculatorOutputLoadSelect option:selected").val() != 5 && $("#rmsCalculatorOutputLoadSelect option:selected").val() != 6) {
                power = parseFloat($("#maxRmsOutputPowerValue").val()) * loadTable[$("#rmsCalculatorOutputLoadSelect").val()];
                power = Math.sqrt(power);
                if (power > rmsThresScaleMax) {
                    power = rmsThresScaleMax;
                    var voltRms = 0.0;
                    voltRms = Math.pow(rmsThresScaleMax, 2) / loadTable[$("#rmsCalculatorOutputLoadSelect option:selected").val()];
                    $("#maxRmsOutputPowerValue").val(parseFloat(voltRms.toFixed(1)));
                } else if (power < rmsThresScaleMin) {
                    power = rmsThresScaleMin;
                    var voltPeak = 0.0;
                    voltPeak = Math.pow(rmsThresScaleMin, 2) / loadTable[$("#peakCalculatorOutputLoadSelect option:selected").val()];
                    $("#maxRmsOutputPowerValue").val(parseFloat(voltPeak.toFixed(1)));
                }
                $("#maxVRmsInput").val(power.toFixed(1));
            }
        } else {
            $("#maxRmsOutputPowerValue").addClass("is-invalid");
        }
    });

    $("body").on("change", "#hpfRmsInput", function(e) {
        if ($.isNumeric($("#hpfRmsInput").val())) {
            $("#hpfRmsInput").removeClass("is-invalid");
            if (parseInt($("#hpfRmsInput").val()) < freqScaleMinPEQ)
                $("#hpfRmsInput").val(freqScaleMinPEQ);
            if (parseInt($("#hpfRmsInput").val()) > freqScaleMaxPEQ)
                $("#hpfRmsInput").val(freqScaleMaxPEQ);

            var atT = 0.0;
            var reT = 0.0;
            atT = 1000 / (parseInt($("#hpfRmsInput").val()));
            reT = 16 * atT;
            if (parseFloat(atT) > rmsAttackScaleMax)
                atT = rmsAttackScaleMax;
            if (parseFloat(reT) > rmsReleaseScaleMax)
                reT = rmsReleaseScaleMax;
            $("#attackRmsInput").val(atT.toFixed(1));
            $("#releaseRmsInput").val(reT.toFixed(1));
        } else {
            $("#hpfRmsInput").addClass("is-invalid");
        }
    });

    $("body").on("click", "#rmsModalSave", function(e) {
        if (parseFloat($("#maxVRmsInput").val()) < rmsThresScaleMin)
            $("#maxVRmsInput").val(rmsThresScaleMin);
        if (parseFloat($("#maxVRmsInput").val()) > rmsThresScaleMax)
            $("#maxVRmsInput").val(rmsThresScaleMax);

        if (parseFloat($("#attackRmsInput").val()) < rmsAttackScaleMin)
            $("#attackRmsInput").val(rmsAttackScaleMin);
        if (parseFloat($("#attackRmsInput").val()) > rmsAttackScaleMax)
            $("#attackRmsInput").val(rmsAttackScaleMax);

        if (parseFloat($("#releaseRmsInput").val()) < rmsReleaseScaleMin)
            $("#releaseRmsInput").val(rmsReleaseScaleMin);
        if (parseFloat($("#releaseRmsInput").val()) > rmsReleaseScaleMax)
            $("#releaseRmsInput").val(rmsReleaseScaleMax);

        var val = 0.0;
        val = parseFloat($("#maxVRmsInput").val());
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres = parseFloat(val.toFixed(1));
        val = parseFloat($("#attackRmsInput").val());
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack = parseFloat(val.toFixed(1));
        val = parseFloat($("#releaseRmsInput").val());
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease = parseFloat(val.toFixed(1));

        $.fn.setDataSoloLimiter(0, 5);

        $("#rmsCalculatorModal").modal("hide");
    });

    //MANAGE PEAK CALCULATOR BUTTON
    $("body").on("click", "#peakCalculator", function(e) {
        // console.log("peak calculator");
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna)
            $("#hpfPeakInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq);
        else
            $("#hpfPeakInput").val(highPassDefaultFrequency)
        $("#hpfPeakInput").trigger("change");
        var voltRms = 0.0;
        voltRms = Math.pow(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres), 2) / loadTable[$("#peakCalculatorOutputLoadSelect option:selected").val()];
        $("#maxPeakOutputPowerValue").val(parseFloat(voltRms.toFixed(1)));
        $("#maxPeakOutputPowerValue").trigger("change");
        $("#maxVPeakInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres);
        $("#peakCalculatorOutputLoadSelect").val(3);
        $("#peakCalculatorOutputLoadSelect").trigger("change");
        $("#peakCalculatorModal").modal("show");
    });

    $("body").on("change", "#peakCalculatorOutputLoadSelect", function(e) {
        var power = 0.0;
        if ($("#peakCalculatorOutputLoadSelect option:selected").val() === "5") {
            $('#maxPeakOutputPowerValue').hide();
            power = 98.9;
        } else if ($("#peakCalculatorOutputLoadSelect option:selected").val() === "6") {
            $('#maxPeakOutputPowerValue').hide();
            power = 141.4;
        } else {
            $('#maxPeakOutputPowerValue').show();
            power = parseFloat($("#maxPeakOutputPowerValue").val()) * loadTable[$("#peakCalculatorOutputLoadSelect").val()];
            power = Math.sqrt(power)
        }
        $("#maxVPeakInput").val(power.toFixed(1));
    });

    $("body").on("change", "#maxPeakOutputPowerValue", function(e) {
        if ($.isNumeric($("#maxPeakOutputPowerValue").val())) {
            $("#maxPeakOutputPowerValue").removeClass("is-invalid");
            var power = 0.0;
            if ($("#peakCalculatorOutputLoadSelect option:selected").val() != 5 && $("#peakCalculatorOutputLoadSelect option:selected").val() != 6) {
                power = parseFloat($("#maxPeakOutputPowerValue").val()) * loadTable[$("#peakCalculatorOutputLoadSelect").val()];
                power = Math.sqrt(power);
                if (power > peakThresScaleMax) {
                    power = peakThresScaleMax;
                    var voltPeak = 0.0;
                    voltPeak = Math.pow(peakThresScaleMax, 2) / loadTable[$("#peakCalculatorOutputLoadSelect option:selected").val()];
                    $("#maxPeakOutputPowerValue").val(parseFloat(voltPeak.toFixed(1)));
                } else if (power < peakThresScaleMin) {
                    power = peakThresScaleMin;
                    var voltPeak = 0.0;
                    voltPeak = Math.pow(peakThresScaleMin, 2) / loadTable[$("#peakCalculatorOutputLoadSelect option:selected").val()];
                    $("#maxPeakOutputPowerValue").val(parseFloat(voltPeak.toFixed(1)));
                }
                $("#maxVPeakInput").val(power.toFixed(1));
            }
        } else {
            $("#maxPeakOutputPowerValue").addClass("is-invalid");
        }
    });

    $("body").on("change", "#hpfPeakInput", function(e) {
        if ($.isNumeric($("#hpfPeakInput").val())) {
            $("#hpfPeakInput").removeClass("is-invalid");
            if (parseInt($("#hpfPeakInput").val()) < freqScaleMinPEQ)
                $("#hpfPeakInput").val(freqScaleMinPEQ);
            if (parseInt($("#hpfPeakInput").val()) > freqScaleMaxPEQ)
                $("#hpfPeakInput").val(freqScaleMaxPEQ);

            var atT = 0.0;
            var reT = 0.0;
            atT = 1000 / (parseInt($("#hpfPeakInput").val()));
            reT = 16 * atT;
            if (parseFloat(reT) > peakReleaseScaleMax)
                reT = peakReleaseScaleMax;
            $("#releasePeakInput").val(reT.toFixed(1));
        } else {
            $("#hpfPeakInput").addClass("is-invalid");
        }
    });

    $("body").on("click", "#peakModalSave", function(e) {
        if (parseFloat($("#maxVPeakInput").val()) < peakThresScaleMin)
            $("#maxVPeakInput").val(peakThresScaleMin);
        if (parseFloat($("#maxVPeakInput").val()) > peakThresScaleMax)
            $("#maxVPeakInput").val(peakThresScaleMax);

        if (parseFloat($("#releasePeakInput").val()) < peakReleaseScaleMin)
            $("#releasePeakInput").val(peakReleaseScaleMin);
        if (parseFloat($("#releasePeakInput").val()) > peakReleaseScaleMax)
            $("#releasePeakInput").val(peakReleaseScaleMax);

        var val = 0.0;
        val = parseFloat($("#maxVPeakInput").val());
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres = parseFloat(val.toFixed(1));
        val = parseFloat($("#releasePeakInput").val());
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease = parseFloat(val.toFixed(1));

        $.fn.setDataSoloLimiter(0, 6);

        $("#peakCalculatorModal").modal("hide");
    });

    //MANAGE BRIDGE 12 BUTTON
    $("body").on("click", "#bridge12Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge12) {
            $("#bridge12Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge12 = false;
        } else {
            $("#bridge12Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge12 = true;
        }
        $.fn.setDataSoloOutput(0);
    });

    //MANAGE BRIDGE 34 BUTTON
    $("body").on("click", "#bridge34Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge34) {
            $("#bridge34Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge34 = false;
        } else {
            $("#bridge34Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge34 = true;
        }
        $.fn.setDataSoloOutput(1);
    });

    //MANAGE BRIDGE 56 BUTTON
    $("body").on("click", "#bridge56Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge56) {
            $("#bridge56Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge56 = false;
        } else {
            $("#bridge56Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge56 = true;
        }
        $.fn.setDataSoloOutput(2);
    });

    //MANAGE BRIDGE 78 BUTTON
    $("body").on("click", "#bridge78Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge78) {
            $("#bridge78Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge78 = false;
        } else {
            $("#bridge78Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge78 = true;
        }
        $.fn.setDataSoloOutput(3);
    });

    //MANAGE BRIDGE 910 BUTTON
    $("body").on("click", "#bridge910Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge910) {
            $("#bridge910Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge910 = false;
        } else {
            $("#bridge910Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge910 = true;
        }
        $.fn.setDataSoloOutput(4);
    });

    //MANAGE BRIDGE 1112 BUTTON
    $("body").on("click", "#bridge1112Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1112) {
            $("#bridge1112Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge1112 = false;
        } else {
            $("#bridge1112Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge1112 = true;
        }
        $.fn.setDataSoloOutput(5);
    });

    //MANAGE BRIDGE 1314 BUTTON
    $("body").on("click", "#bridge1314Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1314) {
            $("#bridge1314Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge1314 = false;
        } else {
            $("#bridge1314Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge1314 = true;
        }
        $.fn.setDataSoloOutput(6);
    });

    //MANAGE BRIDGE 1516 BUTTON
    $("body").on("click", "#bridge1516Button", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1516) {
            $("#bridge1516Button").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge1516 = false;
        } else {
            $("#bridge1516Button").addClass("active");
            arrayAmplifier[soloAmplifierSelected].bridge.bridge1516 = true;
        }
        $.fn.setDataSoloOutput(7);
    });

    //MANAGE AMP STAGE POWER BUTTON
    $("body").on("click", "#powerStageButton", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].amp_stage_disabled) {
            arrayAmplifier[soloAmplifierSelected].amp_stage_disabled = false;
        } else {
            arrayAmplifier[soloAmplifierSelected].amp_stage_disabled = true;
        }
        $.fn.setDataSoloOutput(8);
    });

    //MANAGE HiZ BUTTON
    $("body").on("click", ".hiZButton", function(e) {
        // console.log("click HiZ");
        dest = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // console.log("id source = " + dest);
        if (arrayAmplifier[soloAmplifierSelected].hiZ[dest]) {
            arrayAmplifier[soloAmplifierSelected].hiZ[dest] = false;
        } else {
            arrayAmplifier[soloAmplifierSelected].hiZ[dest] = true;
        }

        $.fn.setDataSoloHiZ(dest, 0);
    })

    //MANAGE STEREO 12 BUTTON
    $("body").on("click", "#stereo12", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12) {
            $("#stereo12").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].stereo.stereo12 = false;
        } else {
            $("#stereo12").addClass("active");
            arrayAmplifier[soloAmplifierSelected].stereo.stereo12 = true;
        }
    });

    //MANAGE STEREO 34 BUTTON
    $("body").on("click", "#stereo34", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34) {
            $("#stereo34").removeClass("active");
            arrayAmplifier[soloAmplifierSelected].stereo.stereo34 = false;
        } else {
            $("#stereo34").addClass("active");
            arrayAmplifier[soloAmplifierSelected].stereo.stereo34 = true;
        }
    });

    //MANAGE LOGIN BUTTON
    $("body").on("click", "#loginButton", function(e) {
        $("#loginStatus").html("");
        $("#passwordStatus").html("");
        var loginForm = $("#loginEmail").val();
        var passForm = $("#loginPassword").val();
        //USERNAME AND PASSWORD ARE OK
        if (loginForm.toString() === arrayAmplifier[0].cloud.username && passForm.toString() === arrayAmplifier[0].cloud.password) {
            $("#loginPanel").removeClass("is-active");
            $.fn.loadAmpOnScreen();
        }
        if (loginForm.toString().length === 0) {
            // EMPTY LOGIN FIELD
            $("#loginStatus").html("username empty");
        }
        if (loginForm.toString().length > 0 && loginForm.toString() != arrayAmplifier[0].cloud.username) {
            // WRONG LOGIN
            $("#loginStatus").html("wrong username");
        }
        if (passForm.toString().length === 0) {
            // EMPTY PASSWORD FIELD
            $("#passwordStatus").html("password empty");
        }
        if (passForm.toString().length > 0 && passForm.toString() != arrayAmplifier[0].cloud.password) {
            // WRONG PASSWORD
            $("#passwordStatus").html("wrong password");
        }
        if (loginForm.toString() === defautPresetLogin && passForm.toString() === defautPresetPassword) {
            window.open("./preset.html", "_blank");
        }
    });

    document.getElementById('loginPassword').addEventListener('keypress', function(event) {
        if (event.keyCode == 13) {
            $("#loginButton").trigger("click");
        }
    });

    //MANAGE EVENT ON GLOBAL PRESET LOAD PRESET BUTTON : BUTTON NAME : Load Preset
    $("body").on("click", "#loadPresetGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Load Global Device Audio Preset File");
        var modalContent = "";
        if (typeof arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected] === "undefined") {
            modalContent += "Please select a preset file first";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].oem === true && arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderName && arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name === protectedPresetName) {
            modalContent += "OEM amplifier. Cannot recall Default Preset";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else {
            modalContent += "Load " + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name + " ?";
            $("#globalPresetActionButton").html(globalPresetLoadPresetAction);
        }
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET EDIT PRESET BUTTON : BUTTON NAME : Save Preset
    $("body").on("click", "#editPresetGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Save Global Device Audio Preset File");
        var modalContent = "";
        if (typeof arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected] === "undefined") {
            modalContent += "Please select a preset file first";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderName && arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name === protectedPresetName) {
            modalContent += protectedPresetName + " is protected";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderOEMName && arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name === protectedPresetOEMName) {
            modalContent += protectedPresetOEMName + " is OEM protected";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else {
            modalContent += "Save " + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name + " ?";
            $("#globalPresetActionButton").html(globalPresetEditPresetAction);
        }
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET RENAME PRESET BUTTON : BUTTON NAME : Save As Preset
    $("body").on("click", "#renamePresetGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Save As Global Device Audio Preset File");
        var modalContent = "";
        if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name != protectedFolderName) {
            modalContent += "Save as <input id=\"saveAsFileNameModal\"  type=\"text\" class=\" form-control form-control-sm\" placeHolder=\"File name\"></input>";
            $("#globalPresetActionButton").html(globalPresetSaveAsPresetAction);
        } else {
            modalContent += protectedFolderName + " is protected";
            $("#globalPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        }
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET DELETE PRESET BUTTON : BUTTON NAME : Delete Preset
    $("body").on("click", "#deletePresetGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Delete Global Device Audio Preset file");
        var modalContent = "";
        if (typeof arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected] === "undefined") {
            modalContent += "Please select a preset file first";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderName && arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name === protectedPresetName) {
            modalContent += protectedPresetName + " is protected";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderOEMName && arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name === protectedPresetOEMName) {
            modalContent += protectedPresetOEMName + " is OEM protected";
            $("#globalPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else {
            modalContent += "Delete " + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name + " ?";
            $("#globalPresetActionButton").html(globalPresetDeletePresetAction);
        }
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET CREATE FOLDER BUTTON
    $("body").on("click", "#createFolderGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Create New Global Device Audio Preset Folder");
        var modalContent = "";
        modalContent += "Create <input id=\"createGlobalFolderNameValue\"  type=\"text\" class=\" form-control form-control-sm\" placeHolder=\"Folder name\"></input>";
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetActionButton").html(globalPresetCreateFolderAction);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET RENAME FOLDER BUTTON
    $("body").on("click", "#renameFolderGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Rename Global Device Audio Preset Folder");
        var modalContent = "";
        if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderName) {
            modalContent += protectedFolderName + " is protected";
            $("#globalPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderOEMName) {
            modalContent += protectedFolderOEMName + " is OEM protected";
            $("#globalPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        } else {
            modalContent += "Rename folder : " + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name + " <input id=\"renameFolderNameModal\"  type=\"text\" class=\" form-control form-control-sm\" placeHolder=\"New folder name\"></input>";
            $("#globalPresetActionButton").html(globalPresetRenameFolderAction);
        }
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET DELETE FOLDER BUTTON
    $("body").on("click", "#deleteFolderGlobalBtn", function(e) {
        $("#globalPresetModalTitle").html("Delete Global Device Audio Preset Folder");
        var modalContent = "";
        if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderName) {
            modalContent += protectedFolderName + " is protected";
            $("#globalPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name === protectedFolderOEMName) {
            modalContent += protectedFolderOEMName + " is OEM protected";
            $("#globalPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        } else {
            modalContent += "Delete " + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name + " ?";
            $("#globalPresetActionButton").html(globalPresetDeleteFolderAction);
        }
        $("#globalPresetModalContent").html(modalContent);
        $("#globalPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET DELETE FOLDER BUTTON
    $("body").on("click", "#refreshFolderGlobalBtn", function(e) {
        $.fn.sendCommandWS(cmd_get_global_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
    });

    $("body").on("click", "#globalPresetActionButton", function(e) {
        var noAction = 0;
        var folderName;
        if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList.length > 0) {
            if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name.length > 0)
                folderName = arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name;
            var fileName;
            if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList.length > 0)
                fileName = arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name;
        }
        switch (e.target.innerHTML) {
            case globalPresetCreateFolderAction:
                if ($("#createGlobalFolderNameValue").val().length > 0)
                    $.fn.sendStringWS(cmd_create_global_preset_folder, soloAmplifierSelected, $("#createGlobalFolderNameValue").val(), "null", "null");
                break;

            case globalPresetRenameFolderAction:
                if ($("#renameFolderNameModal").val().length > 0) {
                    $.fn.sendStringWS(cmd_rename_global_preset_folder, soloAmplifierSelected, folderName, "null", $("#renameFolderNameModal").val());
                }
                break;

            case globalPresetDeleteFolderAction:
                // console.log("delete global preset folder : " + folderName);
                $.fn.sendStringWS(cmd_delete_global_preset_folder, soloAmplifierSelected, folderName, "null", "null");
                soloFolderGlobalSelected = 0;
                break;

            case globalPresetLoadPresetAction:
                $.fn.sendStringWS(cmd_set_global_preset_file, soloAmplifierSelected, folderName + "/" + fileName, "null", "null");
                $("#presetLoader").addClass("is-active");
                break;

            case globalPresetCreatePresetAction:
                if ($("#createGlobalFileNameModal").val().length > 0) {
                    $.fn.sendStringWS(cmd_create_global_preset_file, soloAmplifierSelected, folderName + "/" + $("#createGlobalFileNameModal").val(), "null", "null");
                }
                break;

            case globalPresetEditPresetAction:
                $.fn.sendStringWS(cmd_edit_global_preset_file, soloAmplifierSelected, folderName + "/" + fileName, "null", "null");
                break;

            case globalPresetSaveAsPresetAction:
                if ($("#saveAsFileNameModal").val().length > 0) {
                    $.fn.sendStringWS(cmd_create_global_preset_file, soloAmplifierSelected, folderName + "/" + $("#saveAsFileNameModal").val(), "null", "null");
                }
                break;

            case globalPresetDeletePresetAction:
                $.fn.sendStringWS(cmd_delete_global_preset_file, soloAmplifierSelected, folderName + "/" + fileName, "null", "null");
                break;

            default:
                noAction = 1;
                break;
        }
        $("#globalPresetModal").modal("hide");
        if (noAction === 0) {
            setTimeout(function() { $.fn.sendCommandWS(cmd_get_global_preset_folder_names, soloAmplifierSelected, "null", "null", "null"); }, 2000);
        }
    });


    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $("body").on("click", "#downloadPresetGlobalBtn", function(e) {
        var folderName = null;
        var fileName = null;
        if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList.length > 0) {
            if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name.length > 0)
                folderName = arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name;
            var fileName;
            if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList.length > 0)
                fileName = arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name;
        }

        if (fileName) {
            downloadSpeakerPresetName = fileName;
            $.fn.sendCommandWS(cmd_get_global_preset_file, soloAmplifierSelected, folderName + "/" + fileName, "null", "null");
        }
    });

    $("body").on("click", "#uploadPresetGlobalBtn", function(e) {
        if (soloFolderGlobalSelected != 0) {
            $("#globalPresetUploadFile").attr("accept", globalPresetExtension);
            $("#globalPresetUploadFile").val("");
            $("#globalPresetFileStatus").html("<div class=\"status progress\"></div>Select a speaker preset file");
            $("#globalPresetUploadActionButton").html("Upload");
            $("#globalPresetUploadModal").modal("show");
        } else {
            $("#globalPresetUploadFile").attr("accept", globalPresetExtension);
            $("#globalPresetUploadFile").val("");
            $("#globalPresetFileStatus").html("<div class=\"status dead\"></div><b>Factory Folder is protected</b>");
            $("#globalPresetUploadActionButton").html(globalPresetDeleteFolderProtectedAction);
            $("#globalPresetUploadModal").modal("show");
        }
    })

    $("body").on("change", "#globalPresetUploadFile", function(e) {
        updateJsonFile = "";
        updateJsonName = "";
        updateJsonStatus = 0;
        // console.log("click upload file");
        var fullPath = $("#globalPresetUploadFile").val();
        if (fullPath) {
            var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
            var filename = fullPath.substring(startIndex);
            if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
                filename = filename.substring(1);
            }
            filename = filename.replace(globalPresetExtension, '');
            updateJsonName = filename;
        }

        var files = e.target.files;
        // updateTempFile = files;
        var input = e.target;
        var reader = new FileReader();
        var retJson = "";
        reader.onload = function(event) {
            // console.log("on load");
            //IF OLD PRESET FAIL TRY NEW ONE
            try {
                var bytes = CryptoJS.AES.decrypt(reader.result.toString(), presetKey);
                var plaintext = bytes.toString(CryptoJS.enc.Utf8);
                retJson = plaintext;
                // console.log("json:" + retJson);
                retJson = JSON.parse(retJson);
                var ret = $.fn.checkGlobalSpeakerUploadFile(retJson);
                if (ret === 0) {
                    // OK OK UPLOAD CAN START
                    updateJsonFile = retJson;
                    updateJsonStatus = 1;
                    $("#globalPresetFileStatus").html("<div class=\"status open\"></div>File ok, ready to upload \"" + updateJsonName + "\" in " + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name);
                } else {
                    // DISPLAY ERROR
                    updateJsonFile = "";
                    updateJsonStatus = 0;
                    $("#globalPresetFileStatus").html("<div class=\"status dead\"></div>File error : " + ret);
                }
            } catch (e) {
                // console.log("Error file reading" + files[0].name + " : " + e.message);
                updateJsonFile = "";
                updateJsonStatus = 0;
                $("#globalPresetFileStatus").html("<div class=\"status dead\"></div>JSON parse error");
            }
        }
        reader.readAsText(files[0]);
    });

    $("body").on("click", "#globalPresetUploadActionButton", function(e) {
        if ($("#globalPresetUploadActionButton").html() === globalPresetDeleteFolderProtectedAction)
            $("#globalPresetUploadModal").modal("hide");
        else {
            let doubleName = 0;
            for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList.length; i++) {
                if (arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[i].file_name === updateJsonName)
                    doubleName++;
            }
            // CHECK IF FILE IS OK FOR UPLOAD
            if (updateJsonStatus === 1 && doubleName === 0) {
                // console.log("upload" + updateJsonName);
                $.fn.uploadGlobalPreset(updateJsonFile);
                $("#globalPresetUploadModal").modal("hide");
                $("#presetUploader").addClass("is-active");
            } else if (doubleName > 0) {
                $("#globalPresetFileStatus").html("<div class=\"status dead\"></div>This folder already contains a preset with the same name. <br> Please change name file before uploading it.")
                $(".warningUpload").html("");
            }
        }
    });
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    //MANAGE EVENT ON CLICK ON FOLDER ON FOLDER LISTS GLOBAL
    $("body").on("click", "#folderListGlobal>tbody>tr", function(e) {
        var idSource = this.firstChild.id;
        var num = this.firstChild.id.toString().match(/(\d+)/g).map(Number);

        //IF USER SELECT ANOTHER FOLDER
        if (num != soloFolderGlobalSelected) {
            // console.log("folder:" + idSource);
            soloFolderGlobalSelected = parseInt(num);
            soloFileGlobalSelected = 0;
            $.fn.setDataSoloGlobal(100);
        }
    });

    //MANAGE EVENT ON CLICK ON FILE ON FILES LISTS global
    $("body").on("click", "#fileListGlobal>tbody>tr", function(e) {
        var idSource = this.firstChild.id;
        var num = this.firstChild.id.toString().match(/(\d+)/g).map(Number);

        //IF USER SELECT ANOTHER FILE
        if (num != soloFileGlobalSelected) {
            // console.log("file:" + idSource);
            soloFileGlobalSelected = parseInt(num);
            $.fn.setDataSoloGlobal(100);
        }
    });

    //MANAGE EVENT ON OVERWRITE CHANNEL LABEL CHECKBOX ON LOAD PRESET MODAL
    $("body").on("change", "#overwriteChLabel", function(e) {
        if ($("#overwriteChLabel").is(':checked')) {
            $("#overwriteChLabel").attr('value', true);
        } else {
            $("#overwriteChLabel").attr('value', false);
        }
    });

    //MANAGE EVENT ON GLOBAL PRESET CREATE FOLDER BUTTON
    $("body").on("click", "#createFolderSpeakerBtn", function(e) {
        $("#speakerPresetModalTitle").html("Create New Speaker Preset Folder");
        var modalContent = "";

        modalContent += "Create <input id=\"createSpeakerFolderNameValue\"  type=\"text\" class=\" form-control form-control-sm\" placeHolder=\"Folder name\"></input><div class=\"invalid-feedback\">Folder name already used</div>";

        $("#speakerPresetModalContent").html(modalContent);
        $("#speakerPresetActionButton").html(globalPresetCreateFolderAction);
        $("#speakerPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET RENAME FOLDER BUTTON
    $("body").on("click", "#renameFolderSpeakerBtn", function(e) {
        $("#speakerPresetModalTitle").html("Rename Speaker Preset Folder");
        var modalContent = "";

        modalContent += "Rename " + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + " <input id=\"renameFolderNameModal\"  type=\"text\" class=\" form-control form-control-sm\" placeHolder=\"Folder name\"></input>";
        $("#speakerPresetModalContent").html(modalContent);

        $("#speakerPresetActionButton").html(globalPresetRenameFolderAction);
        $("#speakerPresetModal").modal("show");
    });

    //MANAGE EVENT ON GLOBAL PRESET DELETE FOLDER BUTTON
    $("body").on("click", "#deleteFolderSpeakerBtn", function(e) {
        $("#speakerPresetModalTitle").html("Delete Speaker Preset Folder");
        var modalContent = "";
        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name === protectedFolderName) {
            modalContent += protectedFolderName + " is protected";
            $("#speakerPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name === protectedFolderSpeakerOEMName) {
            modalContent += protectedFolderName + " is OEM protected";
            $("#speakerPresetActionButton").html(globalPresetDeleteFolderProtectedAction);
        } else {
            modalContent += "Delete " + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + " ?";
            $("#speakerPresetActionButton").html(globalPresetDeleteFolderAction);
        }
        $("#speakerPresetModalContent").html(modalContent);
        $("#speakerPresetModal").modal("show");
    });

    //MANAGE EVENT ON MODAL CONFIRM LOAD SPEAKER PRESET
    $("body").on("click", "#loadConfirmSpeakerPresetButton", function(e) {
        // console.log("load preset");
        // $.fn.setDataSoloSpeaker(0);
        $("#loadSoloSpeakerPresetModal").modal("hide");
        var path = "" + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + "/" + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name;
        if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
            $.fn.sendCommandWS(cmd_set_all_speaker_preset_file, soloAmplifierSelected, path, soloChannelSelected, null);
        } else {
            if ($("#overwriteChLabel").attr('value') == "true") {
                $.fn.sendCommandWS(cmd_set_label_speaker_preset_file, soloAmplifierSelected, path, soloChannelSelected, true);
                // arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].label = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name;
                // $.fn.setDataSoloSource(soloChannelSelected, 2);
            } else {
                $.fn.sendCommandWS(cmd_set_label_speaker_preset_file, soloAmplifierSelected, path, soloChannelSelected, false);
            }
        }
        $("#presetLoader").addClass("is-active");

    });

    //MANAGE EVENT ON LOAD SPEAKER PRESET BUTTON
    $("body").on("click", "#loadSpeakerPresetButton", function(e) {
        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected]) {
            var content = " Are you sure to load speaker file : ";
            //FOLDER NAME
            content += arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name;
            content += "\\";
            //FILE NAME
            content += arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name;
            if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                //specify channel or speaker destination for the preset
            } else {
                content += " on channel ";
                content += "<b>" + arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].label + "</b>";
            }
            content += " ?";
            content += "<br>";
            content += "Overwrite channel label with preset name <input id=\"overwriteChLabel\" type=\"checkbox\" checked value=\"true\">";
            $("#loadSoloSpeakerPresetModalContent").html(content);
            $("#loadSoloSpeakerPresetModal").modal("show");
        }
    });

    //MANAGE EVENT ON DELETE SPEAKER PRESET BUTTON
    $("body").on("click", "#deletePresetSpeakerBtn", function(e) {
        $("#speakerPresetModalTitle").html("Delete Speaker Preset file");
        var modalContent = "";
        if (typeof arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected] === "undefined") {
            modalContent += "Please select a preset file first";
            $("#speakerPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name == protectedSpeakerFolderName && arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].file_name == protectedSpeakerPresetName) {
            modalContent += protectedPresetName + " is protected";
            $("#speakerPresetActionButton").html(globalPresetDeletePresetProtectedAction);
            //CHECK IF OEM PRESET, SO USER CAN'T DELETE IT
        } else if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].protected === true) {
            modalContent += arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name + " is OEM protected";
            $("#speakerPresetActionButton").html(globalPresetDeletePresetProtectedAction);
        } else {
            modalContent += "Delete " + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name + " ?";
            $("#speakerPresetActionButton").html(globalPresetDeletePresetAction);
        }
        $("#speakerPresetModalContent").html(modalContent);
        $("#speakerPresetModal").modal("show");
    });

    $("body").on("click", "#speakerPresetActionButton", function(e) {
        var noAction = 0;
        var noHide = 0;
        var folderName;
        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList.length > 0) {
            if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name.length > 0)
                folderName = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name;
            var fileName;
            if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList.length > 0)
                fileName = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name;
        }
        switch (e.target.innerHTML) {
            //CREATE FOLDER
            case globalPresetCreateFolderAction:
                if ($("#createSpeakerFolderNameValue").val().length > 0) {
                    let doubleFolder = 0
                    for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList.length; i++) {
                        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[i].name === $("#createSpeakerFolderNameValue").val())
                            doubleFolder++;
                    }
                    if (doubleFolder === 0) {
                        if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                            $.fn.sendStringWS(cmd_create_all_speaker_preset_folder, 0, $("#createSpeakerFolderNameValue").val(), "null", "null");
                        } else {
                            $.fn.sendStringWS(cmd_create_speaker_preset_folder, 0, $("#createSpeakerFolderNameValue").val(), "null", "null");
                        }
                    } else {
                        $(".invalid-feedback").addClass("d-block");
                        setTimeout(function() { $(".invalid-feedback").removeClass("d-block") }, 5000);
                        return;
                    }
                }
                break;
                //RENAME FOLDER
            case globalPresetRenameFolderAction:
                if ($("#renameFolderNameModal").val().length > 0) {
                    if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                        $.fn.sendStringWS(cmd_rename_all_speaker_preset_folder, 0, folderName, "null", $("#renameFolderNameModal").val());
                    } else {
                        $.fn.sendStringWS(cmd_rename_speaker_preset_folder, 0, folderName, "null", $("#renameFolderNameModal").val());
                    }
                }
                break;
                //DELETE FOLDER
            case globalPresetDeleteFolderAction:
                // console.log("delete speaker preset folder : " + folderName);
                if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                    $.fn.sendStringWS(cmd_delete_all_speaker_preset_folder, 0, folderName, "null", "null");
                } else {
                    $.fn.sendStringWS(cmd_delete_speaker_preset_folder, 0, folderName, "null", "null");
                }
                if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList.length > 0)
                    soloFolderSpeakerSelected = 0;
                break;
                //DELETE PRESET
            case globalPresetDeletePresetAction:
                if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                    $.fn.sendStringWS(cmd_delete_all_speaker_preset_file, 0, folderName + "/" + fileName, "null", "null");
                } else {
                    $.fn.sendStringWS(cmd_delete_speaker_preset_file, 0, folderName + "/" + fileName, "null", "null");
                }
                if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList.length > 0)
                    soloFileSpeakerSelected = 0;
                break;

            default:
                noAction = 1;
                break;
        }
        if (noHide != 1)
            $("#speakerPresetModal").modal("hide");

        if (noAction === 0 && noHide === 0) {
            if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                setTimeout(function() { $.fn.sendCommandWS(cmd_get_all_speaker_preset_list_names, 0, "null", "null", "null"); }, 2000);
            } else {
                setTimeout(function() { $.fn.sendCommandWS(cmd_get_speaker_preset_list_names, 0, "null", "null", "null"); }, 2000);
            }
        }
    });

    // DOWNLOAD SPEAKER PRESET FILE
    $("body").on("click", "#downloadPresetSpeakerBtn", function(e) {
        var folderName = null;
        var fileName = null;
        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList.length > 0) {
            if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name.length > 0)
                folderName = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name;
            var fileName;
            if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList.length > 0)
                fileName = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name;
        }

        if (fileName) {
            downloadSpeakerPresetName = fileName;
            if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                $.fn.sendCommandWS(cmd_get_all_speaker_preset_file, 0, folderName + "/" + fileName, "null", "null");
            } else {
                $.fn.sendCommandWS(cmd_get_speaker_preset_file, 0, folderName + "/" + fileName, "null", "null");
            }
        } else {
            alert("Please set a Speaker File");
        }
    });

    $("body").on("click", "#uploadPresetSpeakerBtn", function(e) {
        if (soloFolderSpeakerSelected != 0) {
            $("#speakerPresetUpdateFile").attr("accept", speakerPresetExtension);
            $("#speakerPresetUpdateFile").val("");
            $("#speakerUploadFileStatus").html("<div class=\"status progress\"></div>Select a speaker preset file");
            $("#speakerPresetUpdateActionButton").html("Upload");
            $(".warningUpload").html("<h6>Warning:</h6> Channel 1 speaker preset will be muted and resetted during upload process");
            $("#speakerPresetUpdateModal").modal("show");
        } else {
            $("#speakerPresetUpdateFile").attr("accept", speakerPresetExtension);
            $("#speakerPresetUpdateFile").val("");
            $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div><b>Factory Folder is protected</b>");
            $("#speakerPresetUpdateActionButton").html(globalPresetDeleteFolderProtectedAction);
            $(".warningUpload").html("");
            $("#speakerPresetUpdateModal").modal("show");
        }
    });

    $("body").on("click", "#uploadFolderPresetSpeakerBtn", function(e) {
        if (soloFolderSpeakerSelected != 0) {
            $("#speakerPresetUpdateFile").attr("accept", speakerFolderPresetExtension);
            $("#speakerPresetUpdateFile").val("");
            $("#speakerUploadFileStatus").html("<div class=\"status progress\"></div>Select a folder speaker preset file");
            $("#speakerPresetUpdateActionButton").html("Upload in folder");
            $(".warningUpload").html("");
            $("#speakerPresetUpdateModal").modal("show");
        } else {
            $("#speakerPresetUpdateFile").attr("accept", speakerFolderPresetExtension);
            $("#speakerPresetUpdateFile").val("");
            $("#speakerUploadFileStatus").html("<div class=\"status progress\"></div>Factory Folder is protected");
            $("#speakerPresetUpdateActionButton").html(globalPresetDeleteFolderProtectedAction);
            $(".warningUpload").html("");
            $("#speakerPresetUpdateModal").modal("show");
        }
    })

    $("body").on("change", "#speakerPresetUpdateFile", function(e) {
        updateJsonFile = "";
        updateJsonName = "";
        updateJsonStatus = 0;
        // console.log("click upload file");
        var fullPath = $("#speakerPresetUpdateFile").val();
        if (fullPath) {
            var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
            var filename = fullPath.substring(startIndex);
            if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
                filename = filename.substring(1);
            }
            filename = filename.replace(speakerPresetExtension, '');
            updateJsonName = filename;
        }

        var files = e.target.files;
        var input = e.target;
        var reader = new FileReader();
        var retJson = "";

        reader.onload = function(event) {
            // console.log("test");
            try {
                retJson = JSON.parse(reader.result);
                var ret = $.fn.checkUpdateSpeakerPreset(retJson);
                if (ret === 0) {
                    updateJsonFile = retJson;
                    updateJsonStatus = 1;
                    oldPreset = { "file_name": updateJsonName, "author": "", "version": "", "note": "", "oem_code": "", "settings": updateJsonFile };
                    updateJsonFile = oldPreset;
                    $("#speakerUploadFileStatus").html("<div class=\"status open\"></div>File ok, ready to upload \"" + updateJsonName + "\" in " + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name);
                } else if (ret === 1) {
                    // 1 channel preset file for a plateamp -> error
                    console.log("1 channel preset");
                    updateJsonFile = "";
                    updateJsonStatus = 0;
                    $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : one channel preset could not be loaded on a plate amplifier");
                } else if (ret === 2) {
                    // 4 channels preset file for an amplifier channel -> error
                    console.log("4 channels preset");
                    updateJsonFile = "";
                    updateJsonStatus = 0;
                    $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : four channels preset could not be loaded on an amplifier");
                } else {
                    // DISPLAY ERROR
                    updateJsonFile = "";
                    updateJsonStatus = 0;
                    $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : " + ret);
                }

            } catch (e) {
                //IF OLD PRESET FAIL TRY NEW ONE
                try {
                    var bytes = CryptoJS.AES.decrypt(reader.result.toString(), presetKey);
                    var plaintext = bytes.toString(CryptoJS.enc.Utf8);
                    retJson = plaintext;
                    // console.log("json:" + retJson);
                    retJson = JSON.parse(retJson);
                    var ret
                    if (retJson.hasOwnProperty("settings")) {
                        ret = $.fn.checkUpdateSpeakerPreset(retJson.settings);
                        if (retJson.oem_code.length > 0 && retJson.oem_code != "0")
                            $.fn.sendStringWS(cmd_oem_check_code, 0, "null", "null", retJson.oem_code);
                    } else {
                        ret = $.fn.checkUpdateSpeakerPreset(retJson[0].settings);
                        if (retJson[0].oem_code.length > 0 && retJson[0].oem_code != "0")
                            $.fn.sendStringWS(cmd_oem_check_code, 0, "null", "null", retJson[0].oem_code);
                    }
                    if (ret === 0) {
                        // OK OK UPLOAD CAN START
                        updateJsonFile = retJson;
                        updateJsonStatus = 1;
                        $("#speakerUploadFileStatus").html("<div class=\"status open\"></div>File ok, ready to upload \"" + updateJsonName + "\" in " + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name);
                    } else if (ret === 1) {
                        console.log("1 channel preset");
                        updateJsonFile = "";
                        updateJsonStatus = 0;
                        $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : one channel preset could not be loaded on a plate amplifier");
                    } else if (ret === 2) {
                        console.log("4 channels preset");
                        updateJsonFile = "";
                        updateJsonStatus = 0;
                        $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : four channels preset could not be loaded on an amplifier");
                    } else {
                        // DISPLAY ERROR
                        updateJsonFile = "";
                        updateJsonStatus = 0;
                        $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : " + ret);
                    }


                    // var ret = $.fn.checkUpdateSpeakerPreset(retJson.settings);
                    // if (retJson.oem_code.length > 0)
                    //     $.fn.sendStringWS(cmd_oem_check_code, 0, "null", "null", retJson.oem_code);
                    // if (ret === 0) {
                    //     // OK OK UPLOAD CAN START
                    //     updateJsonFile = retJson;
                    //     updateJsonStatus = 1;
                    //     $("#speakerUploadFileStatus").html("<div class=\"status open\"></div>File ok, ready to upload \"" + updateJsonName + "\" in " + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name);
                    // } else if (ret === 1) {
                    //     console.log("1 channel preset");
                    //     updateJsonFile = "";
                    //     updateJsonStatus = 0;
                    //     $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : one channel preset could not be loaded on a plate amplifier");
                    // } else if (ret === 2) {
                    //     console.log("4 channels preset");
                    //     updateJsonFile = "";
                    //     updateJsonStatus = 0;
                    //     $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : four channels preset could not be loaded on an amplifier");
                    // } else {
                    //     // DISPLAY ERROR
                    //     updateJsonFile = "";
                    //     updateJsonStatus = 0;
                    //     $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>File error : " + ret);
                    // }
                } catch (e) {
                    // console.log("Error file reading" + files[0].name + " : " + e.message);
                    updateJsonFile = "";
                    updateJsonStatus = 0;
                    $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>JSON parse error");
                }
            }
        }

        reader.onerror = function(event) {
            console.log("reader error");
            console.log(reader.error);
        }

        reader.readAsText(files[0]);
    });

    $("body").on("click", "#speakerPresetUpdateActionButton", function(e) {
        if ($("#speakerPresetUpdateActionButton").html() === globalPresetDeleteFolderProtectedAction)
            $("#speakerPresetUpdateModal").modal("hide");
        else {
            let doubleName = 0;
            for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList.length; i++) {
                if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[i].name === updateJsonName)
                    doubleName++;
            }
            // CHECK IF FILE IS OK FOR UPLOAD
            if (updateJsonStatus === 1 && doubleName === 0) {
                // console.log("upload" + updateJsonName);
                // $.fn.uploadPreset(updateJsonFile);
                if ($("#speakerPresetUpdateActionButton").html() == "Upload")
                    $.fn.uploadPreset(updateJsonFile);
                else
                    $.fn.uploadFolderPreset(updateJsonFile);
                $("#speakerPresetUpdateModal").modal("hide");
                $("#presetUploader").addClass("is-active");
            } else if (doubleName > 0) {
                $("#speakerUploadFileStatus").html("<div class=\"status dead\"></div>This folder already contains a preset with the same name. <br> Please change name file before uploading it.")
                $(".warningUpload").html("");
            }
        }
    });

    //MANAGE EVENT ON SAVE NETWORK SETUP SETTINGS BUTTON
    $("body").on("click", "#saveNetworkSetup", function(e) {
        // console.log("network save");
        var ip, mask, gateway;
        var txt;
        var ipTest = maskTest = gatewayTest = false;

        //TEST DHCP CHECKBOX
        if ($("#lanDhcpEnable").is(':checked')) {
            $("#lanDhcpEnable").attr('value', true);
        } else {
            $("#lanDhcpEnable").attr('value', false);

            ipTest = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test($("#lanIpInput").val());
            if (ipTest === true) {
                $("#lanIpInput").css("border", "4px solid green");
            } else {
                $("#lanIpInput").css("border", "4px solid red");
            }

            maskTest = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test($("#lanGatewayInput").val());
            if (maskTest === true) {
                $("#lanGatewayInput").css("border", "4px solid green");
            } else {
                $("#lanGatewayInput").css("border", "4px solid red");
            }

            gatewayTest = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test($("#lanGatewayInput").val());
            if (ipTest === true) {
                $("#lanGatewayInput").css("border", "4px solid green");
            } else {
                $("#lanGatewayInput").css("border", "4px solid red");
            }
        }

        ip = $("#lanIpInput").val();
        mask = $("#lanMaskInput").val();
        gateway = $("#lanGatewayInput").val();
        dhcp = $("#lanDhcpEnable").attr("value");


        if (dhcp === 'true') {
            $.fn.sendCommandWS(cmd_eth_dhcp, soloAmplifierSelected, "null", "null", "null");
        } else if (ipTest === true && maskTest === true && gatewayTest === true) {
            txt = "{";
            txt += "\\\"ip_addr\\\":\\\"" + ip + "\\\",";
            txt += "\\\"netmask\\\":\\\"" + mask + "\\\",";
            txt += "\\\"gateway\\\":\\\"" + gateway + "\\\"}";
            $.fn.sendStringWS(cmd_eth_static, soloAmplifierSelected, txt, "null", "null", );
        }
    });

    //MANAGE EVENT ON SAVE HOTSPOT SETUP SETTINGS BUTTON
    $("body").on("click", "#saveHotspotSetup", function(e) {
        // console.log("hotspot save");
        var hotspotSSID, hotspotPass, hotspotEnable;
        var txt;
        $("#hotspotSsidInput").removeClass("is-invalid");
        $("#hotspotPasswordInput").removeClass("is-invalid");
        var ssidTest = passTest = false;

        ssidTest = /^[0-9a-zA-Z_]{5,}$/.test($("#hotspotSsidInput").val())
        if (ssidTest === true) {
            $("#hotspotSsidInput").css("border", "4px solid green");
        } else {
            $("#hotspotSsidInput").addClass("is-invalid");
        }

        passTest = /^[0-9a-zA-Z]{8,}$/.test($("#hotspotPasswordInput").val())
        if (passTest === true) {
            $("#hotspotPasswordInput").css("border", "4px solid green");
        } else {
            $("#hotspotPasswordInput").addClass("is-invalid");
        }
        if (ssidTest === true && passTest === true) {
            hotspotSSID = $("#hotspotSsidInput").val();
            hotspotPass = $("#hotspotPasswordInput").val();
            hotspotEnable = $("#hotspotEnableInput").attr("value");
            // if (hotspotSSID.length > 0 && hotspotPass.length > 0) {
            var config = new Object();
            config.ssid = hotspotSSID;
            config.wpa_version = parseInt(hotspotWpaVersionDefault);
            config.channel = parseInt(hotspotChannelVersionDefault);
            config.password = hotspotPass;
            var txt = JSON.stringify(config).toString();
            // console.log("sent text : " + txt);

            txt = "{";
            txt += "\\\"ssid\\\":\\\"" + config.ssid + "\\\",";
            txt += "\\\"wpa_version\\\":" + config.wpa_version + ",";
            txt += "\\\"channel\\\":" + config.channel + ",";
            txt += "\\\"password\\\":\\\"" + config.password + "\\\"}";
            $.fn.sendStringWS(cmd_set_hotspot_config, soloAmplifierSelected, txt, "null", "null");
            if (hotspotEnable === "true") {
                $.fn.sendCommandWS(cmd_hotspot_enable, soloAmplifierSelected, true, "null", "null");
            } else {
                $.fn.sendCommandWS(cmd_hotspot_enable, soloAmplifierSelected, false, "null", "null");
            }
        }
    });

    //CLASS FOR EVERY SETUP CHECKBOX TO SET TRUE FALSE VALUE
    $(".setupCheckbox").on('change', function() {
        if ($(this).is(':checked')) {
            $(this).attr('value', 'true');
        } else {
            $(this).attr('value', 'false');
        }
        // console.log("CB " + this.id + ":" + $(this).val());
    });

    //MANAGE EVENT ON SAVE CLOUD CONNECT SETUP SETTINGS BUTTON
    $("body").on("click", "#saveCloudConnectSetup", function(e) {
        // console.log("cloudconnect save");
        $("#cloudLoginInput").removeClass("is-invalid");
        $("#cloudPasswordInput").removeClass("is-invalid");
        $("#cloudNameInput").removeClass("is-invalid");
        var config = new Object();
        var txt;
        config.device_name = $("#cloudNameInput").val();
        config.login = $("#cloudLoginInput").val();
        config.pass = $("#cloudPasswordInput").val();
        config.enable = $("#cloudEnableInput").attr("value");

        var deviceNameRegex = /^[0-9a-zA-Z]{10,}$/;
        var loginRegex = /^[0-9a-zA-Z]{5,}$/;

        if (config.device_name.match(deviceNameRegex) || config.device_name.length === 0) {
            if (config.login.match(loginRegex)) {
                $("#cloudLoginInput").removeClass("is-invalid");
                if (config.pass.match(loginRegex)) {
                    $("#cloudPasswordInput").removeClass("is-invalid");
                    txt = "{";
                    txt += "\\\"device_name\\\":\\\"" + config.device_name + "\\\",";
                    txt += "\\\"username\\\":\\\"" + config.login + "\\\",";
                    txt += "\\\"password\\\":\\\"" + config.pass + "\\\",";
                    txt += "\\\"enable\\\":" + config.enable + "}";
                    $.fn.sendStringWS(cmd_set_apex_cloud, soloAmplifierSelected, "null", "null", txt);
                } else {
                    $("#cloudPasswordInput").addClass("is-invalid");
                }
            } else {
                $("#cloudLoginInput").addClass("is-invalid");
            }
        } else {
            $("#cloudNameInput").addClass("is-invalid");
        }
    });

    //MANAGE EVENT ON SAVE SPOTIFY SETUP SETTINGS BUTTON
    $("body").on("click", "#saveSpotifySetup", function(e) {
        // console.log("spotify save");
        var spotifyName, spotifyEmail, spotifyPass, spotifyEnable;
        var txt;
        var config = new Object();
        spotifyName = $("#spotifyNameInput").val();
        spotifyEmail = $("#spotifyEmailInput").val();
        spotifyPass = $("#spotifyPasswordInput").val();
        spotifyEnable = $("#spotifyEnableInput").val();
        if (spotifyEmail.length > 0) {
            config.device_name = spotifyName;
            config.email = spotifyEmail;
            config.password = spotifyPass;
            if (spotifyEnable === "true")
                config.enable = true;
            else
                config.enable = false;
        } else {
            config.device_name = spotifyName;
            config.email = "";
            config.password = "";
            if (spotifyEnable === "true")
                config.enable = true;
            else
                config.enable = false;
        }

        txt = "{";
        txt += "\\\"device_name\\\":\\\"" + config.device_name + "\\\",";
        txt += "\\\"email\\\":\\\"" + config.email + "\\\",";
        txt += "\\\"password\\\":\\\"" + config.password + "\\\",";
        txt += "\\\"enable\\\":" + config.enable + "}";

        $.fn.sendStringWS(cmd_set_spotify_config, soloAmplifierSelected, "null", "null", txt);
    });

    //MANAGE EVENT ON SAVE AIRPLAY SETUP SETTINGS BUTTON
    $("body").on("click", "#saveAirplaySetup", function(e) {
        // console.log("airplay save");
        var airplayName, airplayPass, airplayEnable;
        var txt;
        airplayName = $("#airplayNameInput").val();
        airplayPass = $("#airplayPasswordInput").val();
        airplayEnable = $("#airplayEnableInput").val();
        if (airplayPass.length > 0) {
            var config = new Object();
            config.device_name = airplayName;
            config.password = airplayPass;
            if (airplayEnable === "true")
                config.enable = true;
            else
                config.enable = false;
        } else {
            var config = new Object();
            config.device_name = airplayName;
            config.password = "";
            if (airplayEnable === "true")
                config.enable = true;
            else
                config.enable = false;
        }
        txt = "{";
        txt += "\\\"device_name\\\":\\\"" + config.device_name + "\\\",";
        txt += "\\\"password\\\":\\\"" + config.password + "\\\",";
        txt += "\\\"enable\\\":" + config.enable + "}";
        $.fn.sendStringWS(cmd_set_airplay_config, soloAmplifierSelected, "null", "null", txt);
    });

    $("body").on("change", "#softwareUpdateFile", function(e) {
        // console.log("click upload file");
        var files = e.target.files;
        updateTempFile = files;
        var reader = new FileReader();
        for (var i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();
            reader.onload = (function(theFile) {
                return function(e) {
                    try {
                        var zip = JSZip.loadAsync(e.target.result).then(function(zip) {
                            $.each(zip.files, function(index, zipEntry) {
                                // console.log("file name : " + zipEntry.name);
                                if (zipEntry.name.indexOf(fileChecker) != -1) {
                                    fileCheck = true;
                                    $.fn.setUpdateFile();
                                }
                            });
                        });
                    } catch (e) {
                        console.log("Error file readin" + theFile.name + " : " + e.message);
                    }
                }
            })(f);
            reader.readAsArrayBuffer(f);
        }
    });

    //UPLOAD SOFTWARE UPDATE
    $("body").on("click", "#uploadSoftwareUpdateButton", function(e) {
        // console.log("click software update");
        switch (fileCheck) {
            case true:
                // console.log("update will start soon");
                if (updateFile) {
                    $("#softwareLoader").addClass("is-active");
                    let reader = new FileReader();
                    reader.addEventListener('load', function() {
                        marker = ";base64,"
                        encodedstr = reader.result;
                        var arg2 = encodedstr.substring(encodedstr.indexOf(marker) + marker.length);
                        $.fn.sendCommandWS(cmd_software_update, soloAmplifierSelected, arg2, "null", "null");
                        // console.log(arg2)
                    }, false);
                    reader.readAsDataURL(updateFile);
                }
                fileCheck = false;
                break;
            case false:
                $("#softwareLoader").attr("data-text", "Wrong Zip File");
                $("#softwareLoader").addClass("is-active");
                setTimeout(function() {
                    $("#softwareLoader").removeClass("is-active");
                    $("#softwareLoader").attr("data-text", "Software updating");
                }, 5000);
                // console.log("wrong zip file");
                break;
        }
    });

    //CHECK GATEWAY ADDRESS IF IT FITS WITH IPv4 STANDARD
    $("body").on("change", "#lanIpInput", function(e) {
        var retIP = false;
        retIP = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test($("#lanIpInput").val());
        if (retIP === true) {
            $("#lanIpInput").css("border", "4px solid green");
        } else {
            $("#lanIpInput").css("border", "4px solid red");
        }
    });

    //CHECK GATEWAY ADDRESS IF IT FITS WITH IPv4 STANDARD
    $("body").on("change", "#lanGatewayInput", function(e) {
        var retGW = false;
        retGW = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test($("#lanGatewayInput").val());
        if (retGW === true) {
            $("#lanGatewayInput").css("border", "4px solid green");
        } else {
            $("#lanGatewayInput").css("border", "4px solid red");
        }
    });

    //MANAGE EVENT ON SAVE SETTINGS IN SETUP MENU
    $("body").on("click", "#saveDeviceNameSetup", function(e) {
        var value = $("#amplifierDescription").val();
        if (value.length > 0) {
            if (value.length < 16)
                arrayAmplifier[soloAmplifierSelected].label = value;
            else(value.length >= 16)
            arrayAmplifier[soloAmplifierSelected].label = value.substring(0, 15);
            $(".topMenuTitle").html("" + arrayAmplifier[soloAmplifierSelected].label + " : " + arrayAmplifier[soloAmplifierSelected].network.lan.ip);
            $.fn.sendCommandWS(cmd_set_local_description, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].label, "null", "null");
        } else
            alert("Please set a description");
    });

    //MANAGE EVENT ON CLICK FRONT PANEL LOCK APPLY
    $("body").on("click", "#frontPanelLockButton", function(e) {
        if ($("#frontPanelLockEnable").is(':checked')) {
            $("#frontPanelLockEnable").attr('value', true);
            arrayAmplifier[soloAmplifierSelected].front_lock = true;
        } else {
            $("#frontPanelLockEnable").attr('value', false);
            arrayAmplifier[soloAmplifierSelected].front_lock = false;
        }
        $.fn.sendCommandWS(cmd_set_front_lock, soloAmplifierSelected, "null", "null", arrayAmplifier[soloAmplifierSelected].front_lock);
    });

    //MANAGE EVENT ON CLICK LOCATE BUTTON
    $("body").on("click", "#locateButton", function(e) {
        $.fn.sendCommandWS(cmd_run_locate, soloAmplifierSelected, "null", "null", "null");
    });

    //MANAGE EVENT ON CLICK defaultResetButton BUTTON
    $("body").on("click", "#defaultResetButton", function(e) {
        $("#resetDefaultModal").modal('show');
    });

    //MANAGE EVENT ON CLICK RESET DEFAULT BUTTON
    $("body").on("click", "#defaultResetActionButton", function(e) {
        $("#resetDefaultModal").modal('hide');
        $("#resetDefaultConfirmModal").modal('show');
    });

    //MANAGE EVENT ON CLICK RESET DEFAULT CONFIRM BUTTON
    $("body").on("click", "#defaultResetConfirmActionButton", function(e) {
        console.log("reset amplifier");
        $("#resetDefaultConfirmModal").modal('hide');
        $("#resetDefaultModal").modal('hide');
        $("#resetAllLoader").addClass("is-active");
        $.fn.sendCommandWS(cmd_reset_factory, soloAmplifierSelected, "null", "null", "null");

        setTimeout(function() {
            $("#resetAllLoader").removeClass("is-active");
        }, resetAllTimeOut);
    });


    //MANAGE EVENT ON CLICK defaultResetButton BUTTON
    $("body").on("click", "#defaultResetAudioButton", function(e) {
        $("#resetAudioDefaultModal").modal('show');
    });

    //MANAGE EVENT ON CLICK RESET AUDIO BUTTON
    $("body").on("click", "#defaultResetAudioActionButton", function(e) {
        $("#resetAudioDefaultModal").modal('hide');
        $("#resetAudioDefaultConfirmModal").modal('show');
    });

    //MANAGE EVENT ON CLICK RESET AUDIO CONFIRM BUTTON
    $("body").on("click", "#defaultResetAudioConfirmActionButton", function(e) {
        console.log("reset amplifier");
        $("#resetAudioDefaultModal").modal('hide');
        $("#resetAudioDefaultConfirmModal").modal('hide');
        $("#resetAudioLoader").addClass("is-active");
        $.fn.sendCommandWS(cmd_reset_audio, soloAmplifierSelected, "null", "null", "null");

        setTimeout(function() {
            $("#resetAudioLoader").removeClass("is-active");
        }, 3000);
    });



    $("body").on("click", "#localDeviceButtonSelector", function(e) {
        $.fn.setupDiscoverySolo();
    });

    //MANAGE EVENT ON CLICK ON FOLDER ON FOLDER LISTS
    $("body").on("click", "#folderListSpeaker>tbody>tr", function(e) {
        var idSource = this.firstChild.id;
        var num = this.firstChild.id.toString().match(/(\d+)/g).map(Number);

        //IF USER SELECT ANOTHER FOLDER
        if (num != soloFolderSpeakerSelected) {
            // console.log("folder:" + idSource);
            soloFolderSpeakerSelected = parseInt(num);
            soloFileSpeakerSelected = 0;
            $.fn.setDataSoloSpeaker(100);
        }
    });

    //MANAGE EVENT ON CLICK ON FILE ON FILES LISTS
    $("body").on("click", "#fileListSpeaker>tbody>tr", function(e) {
        var idSource = this.firstChild.id;
        var num = this.firstChild.id.toString().match(/(\d+)/g).map(Number);

        //IF USER SELECT ANOTHER FILE
        if (num != soloFileSpeakerSelected) {
            // console.log("file:" + idSource);
            soloFileSpeakerSelected = parseInt(num);
            $.fn.setDataSoloSpeaker(100);
        }
    });

    //MANAGE EVENT ON THE ASSIGN GROUP TAB TABLE LIST
    $("body").on("click", "tbody.labels>tr>td", function(e) {
        //CHECK IF WE CLICK ON THE TAB AMPLIFIER LINE OR THE COLLAPSE BUTTON
        if (e.target.localName === "td" || e.target.localName === "label") {

            //PRESS ON THE AMPLIFIER LIST AND SELECT A DEVICE IN THE GROUP ASSIGN AMPLIFIER LIST
            // console.log("source amp");
            var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            groupAssignAmplifierSelected = num;
            // console.log("GATL:" + groupAssignAmplifierSelected);
            if (num === 0)
                $("#groupAssignAmpSelectedName").html(discoveryList[0].desc);
            else
                $("#groupAssignAmpSelectedName").html(discoveryList[num].desc);
            $("#groupAssignAmpSelectedAddress").html(discoveryList[num].ip_addr);


            let amountOfChannel = channelCount;
            switch ($.fn.getModel(num)) {
                case 9:
                    amountOfChannel = channel3Count;
                    break;
                case 8:
                    amountOfChannel = channel16Count;
                    break;
                case 7:
                    amountOfChannel = channel16Count;
                    break;
                case 6:
                    amountOfChannel = channel1Count;
                    break;
                case 5:
                    amountOfChannel = channel1Count;
                    break;
                default:
                    amountOfChannel = channelCount;
                    break;
            }

            $.fn.setGroupAssignAmplifierContentArea(amountOfChannel);


            for (var i = 0; i < amountOfChannel; i++) {
                if (amountOfChannel == 3 && i > 0)
                    $("#groupAssignAmpSelectedChannelLabel" + i).html(labelOverviewChannel3ch[i + 1]);
                else
                if (amountOfChannel == 3)
                    $("#groupAssignAmpSelectedChannelLabel" + i).html(labelOverviewChannel3ch[i]);
                else
                    $("#groupAssignAmpSelectedChannelLabel" + i).html(arrayAmplifier[num].channel[i].label.substring(0, groupAssigneChannelLabelMaxLength));
            }

            $("#groupAssignAmpGroupLabel0").html(arrayGroup[0].label.substring(0, groupLabelMaxLength));
            $("#groupAssignAmpGroupLabel1").html(arrayGroup[1].label.substring(0, groupLabelMaxLength));
            $("#groupAssignAmpGroupLabel2").html(arrayGroup[2].label.substring(0, groupLabelMaxLength));
            $("#groupAssignAmpGroupLabel3").html(arrayGroup[3].label.substring(0, groupLabelMaxLength));
            $("#groupAssignAmpGroupLabel4").html(arrayGroup[4].label.substring(0, groupLabelMaxLength));
            $("#groupAssignAmpGroupLabel5").html(arrayGroup[5].label.substring(0, groupLabelMaxLength));

            for (var i = 0; i < amountOfChannel; i++) {
                for (var j = 0; j < groupCount; j++) {
                    var id = "#GABtnCh" + i + "Gr" + j;
                    if (arrayAmplifier[num].channel[i].group[j] === 1)
                        $(id).addClass("active");
                    else
                        $(id).removeClass("active");
                }
            }

            let t1 = "#ampListIndex" + num;
            // displayValues("T1", t1, "PARENT", $(t1).parent(".tr"));
            $(".labels > .active").removeClass("active");
            $(t1).parent().addClass("active");

        } else {

            var num = e.target.id.toString().match(/(\d+)/g).map(Number);
            var id = "#collapseAmpList" + num;

            var t = $(id).parents().next('.hide').attr('id');

            if (!$(id).parents().next('.hide').is(':visible')) {
                $(id).parents().next('.hide').show();
                var id1 = "#groupCollapseImage" + num;
                $(id1).attr("src", "./img/Up.png");
            } else {
                $(id).parents().next('.hide').css("display", "none");
                var id1 = "#groupCollapseImage" + num;
                $(id1).attr("src", "./img/Down.png");
            }
        }
    });

    //MANAGE EVENT ON THE ALL UNCOLLAPSE BUTTON IN THE ASSIGN GROUP TAB TABLE LIST
    $("body").on("click", ".groupAssignAmpListAllUncollapse", function() {
        $("#assignGroupTabTable > .hide").show();
        $(".logoSetupSmallChevron").attr("src", "./img/Up.png");
    });

    //MANAGE EVENT ON THE ALL COLLAPSE BUTTON IN THE ASSIGN GROUP TAB TABLE LIST
    $("body").on("click", ".groupAssignAmpListAllCollapse", function() {
        $("#assignGroupTabTable > .hide").css("display", "none");
        $(".logoSetupSmallChevron").attr("src", "./img/Down.png");
    });

    //MANAGE EVENT ON ASSIGN CHANNEL TO GROUP BUTTON IN ASSIGN GROUP TAB CONTENT
    $("body").on("click", ".itemFullGroupAssignChannelBtn", function() {
        var id = this.id;
        var matches = id.match(/\d+/g);
        var cha = parseInt(matches[0]);
        var gr = parseInt(matches[1]);
        // var cha = parseInt(id.charAt(7));
        // var gr = parseInt(id.charAt(10));

        switch (arrayAmplifier[groupAssignAmplifierSelected].channel[cha].group[gr]) {
            case 0:
                //NOT ASSIGN => ASSIGN
                arrayAmplifier[groupAssignAmplifierSelected].channel[cha].group[gr] = 1;
                break;
            case 1:
                //ASSIGN => NOT ASSIGN
                arrayAmplifier[groupAssignAmplifierSelected].channel[cha].group[gr] = 0;
                break;
            default:
                break;
        }
        //console.log("BTN:" + groupAssignAmplifierSelected);
        $.fn.setDataGroupAssign(1, groupAssignAmplifierSelected, cha, gr);
    });

    //MANAGE EVENT ON DEFAULT ASSIGN CHANNEL TO GROUP TO 0
    $("body").on("click", ".groupAssignAmpListDefault", function() {
        // var ampIndex = amplifierFinder(arrayAmplifier, $("#groupAssignAmpSelectedName").text());
        let ampIdTest = $('table>tbody>tr[class=active]>td').prop('id')
        let ampIndex = ampIdTest.toString().match(/(\d+)/g).map(Number);
        // console.log("Selected amp index is : " + num);
        var arrCmd = new Array();
        let amountOfChannel = channelCount;
        switch ($.fn.getModel(ampIndex)) {
            case 9:
                amountOfChannel = channel3Count;
                break;
            case 8:
                amountOfChannel = channel16Count;
                break;
            case 7:
                amountOfChannel = channel16Count;
                break;
            case 6:
                amountOfChannel = channel1Count;
                break;
            case 5:
                amountOfChannel = channel1Count;
                break;
            default:
                amountOfChannel = channelCount;
                break;
        }
        for (var cha = 0; cha < amountOfChannel; cha++) {
            for (var gr = 0; gr < groupCount; gr++) {
                var dest = "#GABtnCh" + cha + "Gr" + gr;
                var tabId = "#groupAssignGroupAmp" + ampIndex + "Channel" + cha + "Group" + gr;
                arrayAmplifier[ampIndex].channel[cha].group[gr] = 0;
                $(dest).removeClass("active");
                $(tabId).removeClass("dotEnable");
                $(tabId).removeClass("dot");
                $(tabId).addClass("dot");
                arrCmd.push($.fn.getCommandFromArgs(cmd_set_assign_channel_to_group, ampIndex, cha, gr, 0))
            }
        }
        //console.log(arrCmd);
        $.fn.sendCommandsWS(arrCmd);
        $(".itemFullGroupAssignChannelBtn").removeClass("active");
    });

    //MANAGE EVENT ON SETUP GROUP ASSIGN AMPLIFIER
    $("body").on("click", ".groupAssignAmpListSoloSetup", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#groupAssignAmpSelectedName").html(arrayAmplifier[num].label);
        $("#groupAssignAmpSelectedAddress").html(arrayAmplifier[num].ip);

        let amountOfChannel = channelCount;
        switch ($.fn.getModel(num)) {
            case 9:
                amountOfChannel = channel3Count;
                break;
            case 8:
                amountOfChannel = channel16Count;
                break;
            case 7:
                amountOfChannel = channel16Count;
                break;
            case 6:
                amountOfChannel = channel1Count;
                break;
            case 5:
                amountOfChannel = channel1Count;
                break;
            default:
                amountOfChannel = channelCount;
                break;
        }

        $.fn.setGroupAssignAmplifierContentArea(amountOfChannel);

        for (var i = 0; i < amountOfChannel; i++) {
            $("#groupAssignAmpSelectedChannelLabel" + i).html(arrayAmplifier[num].channel[i].label);
        }


        // $("#groupAssignAmpSelectedChannelLabel0").html(arrayAmplifier[num].channel[0].label);
        // $("#groupAssignAmpSelectedChannelLabel1").html(arrayAmplifier[num].channel[1].label);
        // $("#groupAssignAmpSelectedChannelLabel2").html(arrayAmplifier[num].channel[2].label);
        // $("#groupAssignAmpSelectedChannelLabel3").html(arrayAmplifier[num].channel[3].label);

        $("#groupAssignAmpGroupLabel0").html(arrayGroup[0].label);
        $("#groupAssignAmpGroupLabel1").html(arrayGroup[1].label);
        $("#groupAssignAmpGroupLabel2").html(arrayGroup[2].label);
        $("#groupAssignAmpGroupLabel3").html(arrayGroup[3].label);
        $("#groupAssignAmpGroupLabel4").html(arrayGroup[4].label);
        $("#groupAssignAmpGroupLabel5").html(arrayGroup[5].label);

        for (var i = 0; i < amountOfChannel; i++) {
            for (var j = 0; j < groupCount; j++) {
                var id = "#GABtnCh" + i + "Gr" + j;
                if (arrayAmplifier[num].channel[i].group[j] === 1)
                    $(id).addClass("active");
                else
                    $(id).removeClass("active");
            }
        }
    });

    //MANAGE EVENT ON THE CHANNEL SELECTION "SELECT" BUTTON
    $("body").on("click", ".oBS", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $(".oBS").removeClass("active");
        $(".overviewButtonSelect").removeClass("active");
        $(".overviewButtonSelect16").removeClass("active");
        $(".bS").removeClass("active");
        $("#overviewBG" + num).addClass("active");
        $("#overviewButton" + num).addClass("active");
        soloChannelSelected = num;
        //change NWx name value if model is 16 channel
        $.fn.loadData();
    });

    //MANAGE EVENT ON SELECT SOURCE NAVBAR BUTTON
    $("body").on("click", "a[href=\"#source\"]", function() {

        //CHANNEL SELECTED (1->4)
        var selectedChannel = this.id.charAt(6);

        //SOURCE SELECTED (0->7)
        var selectedSource = this.id.charAt(10);

        //REDUNDANCY SELECTED (P/S)
        var selectedRedundancy = this.id.charAt(11);

        //REMOVE ACTIVE CLASS STYLE
        for (var i = 0; i < sourceCount; i++) {
            var dest = "#source" + selectedChannel + "nav" + i + selectedRedundancy;
            $(dest).removeClass("active");
        }

        if (selectedRedundancy === "P") {
            if (selectedSource > 7 && arrayAmplifier[soloAmplifierSelected].channel[selectedChannel].gain.gain > streamMinLevelWarning) {
                $("#sourceWarningModalTitle").html("Please check streaming output level !");
                let chanNum = parseInt(selectedChannel) + 1;
                $("#sourceWarningModalContent").html("Channel " + chanNum + " gain is at " + arrayAmplifier[soloAmplifierSelected].channel[selectedChannel].gain.gain + " dB, would you like to confirm the new source selection ?");
                $("#sourceWarningModalButton").attr("selectedChannel", selectedChannel);
                $("#sourceWarningModalButton").attr("selectedSource", selectedSource);
                $("#sourceWarningModalButton").attr("selectedRedundancy", selectedRedundancy);
                $("#sourceWarningModal").modal('show');
                // console.log("test modal");
                //ADD ACTIVE CLASS STYLE TO THE SELECTED INPUT
                var dest = "#source" + selectedChannel + "nav" + arrayAmplifier[soloAmplifierSelected].channel[selectedChannel].source.primary + selectedRedundancy;
                $(dest).addClass("active");
                return;
            }
            //SET LABEL IN THE OVERVIEW MENU
            // var labelId = "#overviewSourceLabel" + selectedChannel;
            // $(labelId).html(sourceOverviewLabel[selectedSource]);
            //SET VALUE IN ACTIVE AMPLIFIER
            arrayAmplifier[soloAmplifierSelected].channel[selectedChannel].source.primary = Number(selectedSource);
            $.fn.setDataSoloSource(selectedChannel, 0);
        }
        if (selectedRedundancy === "S") {
            //SET VALUE IN ACTIVE AMPLIFIER
            arrayAmplifier[soloAmplifierSelected].channel[selectedChannel].source.secondary = Number(selectedSource);
            $.fn.setDataSoloSource(selectedChannel, 1);
        }
        //ADD ACTIVE CLASS STYLE TO THE SELECTED INPUT
        var dest = "#source" + selectedChannel + "nav" + selectedSource + selectedRedundancy;
        $(dest).addClass("active");
    });

    $("body").on("click", "#sourceWarningModalButton", function(e) {
        $.fn.setStreamSource($("#" + this.id).attr("selectedChannel"), $("#" + this.id).attr("selectedSource"), $("#" + this.id).attr("selectedRedundancy"));
        $("#sourceWarningModal").modal('hide');
    });

    // MANAGE CHANNEL EVENT ON BUTTONVOLUP MIXER
    $("body").on("click", ".itemEighterButtonVolUp", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] < gainScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] + 0.1).toFixed(1));
            $.fn.setDataSoloMixer(0, num);
        }
    });

    // MANAGE CHANNEL EVENT ON BUTTONVOLDOWN MIXER
    $("body").on("click", ".itemEighterButtonVolDown", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] > gainScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] - 0.1).toFixed(1));
            $.fn.setDataSoloMixer(0, num);
        }
    });

    //CHECK VALUE ON THE MIXER GAIN TEXTFIELD
    $("body").on("change", ".itemEighterTextField", function(e) {
        if (!$.isNumeric(this.value)) {
            alert("GAIN VALUE BETWEEN -80 and 15 dB")
            var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            $("#mixer" + num).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num]);
        } else {
            var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            if (this.value <= gainScaleMin)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = gainScaleMin;
            else if (this.value > gainScaleMax)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = gainScaleMax;
            else
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = parseFloat(parseFloat(this.value).toFixed(1));
            $.fn.setDataSoloMixer(0, num);
        }
    });

    // MANAGE CHANNEL EVENT ON BUTTONVOLUP GAIN
    $("body").on("click", ".itemQuarterButtonVolUp, .itemQuarterButtonVolUp16", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain < gainScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain + 0.1).toFixed(1));
            $.fn.setDataSoloGain(num, 1);
        }
    });

    // MANAGE CHANNEL EVENT ON BUTTONVOLDOWN GAIN
    $("body").on("click", ".itemQuarterButtonVolDown, .itemQuarterButtonVolDown16", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain > gainScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain - 0.1).toFixed(1));
            $.fn.setDataSoloGain(num, 1);
        }
    });

    //CHANNEL PHASE ENABLE BUTTON
    $("body").on("click", ".itemQuarterButtonPhase, .itemQuarterButtonPhase16", function() {
        let num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        switch (arrayAmplifier[soloAmplifierSelected].channel[num].gain.polarityEna) {
            case true:
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.polarityEna = false;
                $.fn.setDataSoloGain(num, 2);
                break;
            case false:
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.polarityEna = true;
                $.fn.setDataSoloGain(num, 2);
                break;
        }
    });

    //CHECK VALUE ON THE INPUT GAIN TEXTFIELD
    $("body").on("change", ".itemQuarterTextField, .itemQuarterTextField16", function(e) {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (!$.isNumeric(this.value)) {
            alert("GAIN VALUE BETWEEN -80 and 15 dB")
            $("#gain" + num).val(arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain);
        } else {
            // $("#overviewButton" + num).trigger("click");
            var n = this.value;
            if (this.value < gainScaleMin)
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = gainScaleMin;
            else if (this.value > gainScaleMax)
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = gainScaleMax;
            else
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = parseFloat(parseFloat(this.value).toFixed(1));
            $.fn.setDataSoloGain(num, 1);
        }
    });

    // MANAGE EVENT ON CHANNEL ENABLE BUTTON DELAY
    $("body").on("click", ".itemQuarterButtonDelayEnable, .itemQuarter16ButtonDelayEnable", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna === true) {
            arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna = false;
        } else {
            arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna = true;
            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay >= parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2))) {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2));
            }
        }
        $.fn.setDataSoloDelay(num, 0);
    });

    // MANAGE EVENT ON CHANNEL BUTTONDELAYUP DELAY
    $("body").on("click", ".itemQuarterButtonDelayUp, .itemQuarter16ButtonDelayUp", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (num != soloChannelSelected)
            $("#overviewButton" + num).trigger("click");
        if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna) {
            if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (num === 0 || num === 1)) {
                var maxDelay = 0.0;
                if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 0) <= $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1))
                    maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1);
                else
                    maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0);
                if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay < maxDelay) {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay + 0.01).toFixed(2));
                } else {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = maxDelay;
                }
                $.fn.setDataSoloDelay(num, 1);
                return;
            }
            if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (num === 2 || num === 3)) {
                var maxDelay = 0.0;
                if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 2) <= $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3))
                    maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3);
                else
                    maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2);
                if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay < maxDelay) {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay + 0.01).toFixed(2));
                } else {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = maxDelay;
                }
                $.fn.setDataSoloDelay(num, 1);
                return;
            }
            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay < parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2))) {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay + 0.01).toFixed(2));
            } else {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2));
            }
            $.fn.setDataSoloDelay(num, 1);
        } else {
            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay < delayScaleMax) {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay + 0.01).toFixed(2));
                $.fn.setDataSoloDelay(num, 1);
            }
        }
    });

    // MANAGE EVENT ON CHANNEL BUTTONDELAYDOWN DELAY
    $("body").on("click", ".itemQuarterButtonDelayDown, .itemQuarter16ButtonDelayDown", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna) {
            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay > delayScaleMin && arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay <= parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2))) {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay - 0.01).toFixed(2));
                $("#itemQuarterTotalDelay" + num).removeClass("Max");
            } else if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay <= delayScaleMin) {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMin;
            } else {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2));

            }
            $.fn.setDataSoloDelay(num, 1);
        } else {
            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay > delayScaleMin) {
                arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay - 0.01).toFixed(2));
                $.fn.setDataSoloDelay(num, 1);
            }
        }
    });

    //CHECK VALUE ON THE INPUT DELAY TEXTFIELD
    $("body").on("change", ".itemQuarterDelayTextField, .itemQuarter16DelayTextField", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (!$.isNumeric(this.value)) {
            alert("DELAY VALUE BETWEEN 0 and " + delayScaleMax + "ms")
            $("#delay" + num).val(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay);
        } else {
            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna) {
                if (parseFloat(parseFloat(this.value).toFixed(2)) < parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2))) {
                    if (parseFloat(parseFloat(this.value).toFixed(2)) < delayScaleMin)
                        arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMin;
                    else if (this.value > delayScaleMax)
                        arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMax;
                    else
                        arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(this.value).toFixed(2));
                    $("#itemQuarterTotalDelay" + num).removeClass("Max");
                    $.fn.setDataSoloDelay(num, 1);
                } else {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2));
                    $.fn.setDataSoloDelay(num, 1);
                }
            } else {
                if (parseFloat(parseFloat(this.value).toFixed(2)) < delayScaleMin)
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMin;
                else if (parseFloat(parseFloat(this.value).toFixed(2)) > delayScaleMax)
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMax;
                else
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(parseFloat(this.value).toFixed(2));
                $.fn.setDataSoloDelay(num, 1);
            }
            $("#overviewButton" + num).trigger("click");
        }
    });

    //CHECK VALUE ON THE INPUT DELAY METER TEXTFIELD
    $("body").on("change", ".itemQuarterDelayMeterTextField, .itemQuarter16DelayMeterTextField", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        $("#overviewButton" + num).trigger("click");
        if (!$.isNumeric(this.value)) {
            alert("DELAY VALUE BETWEEN 0 and " + delayMeterScaleMax + "ms")
            $("#delay" + num).val(arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay);
        } else {
            var delayInMs = ((parseFloat(this.value).toFixed(2) * 1000) / speedOfSound).toFixed(2);

            if (arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna) {
                if (delayInMs < parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2))) {
                    if (delayInMs < delayScaleMin)
                        arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMin;
                    else if (delayInMs > delayScaleMax)
                        arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMax;
                    else
                        arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayInMs;
                    $("#itemQuarterTotalDelay" + num).removeClass("Max");
                    $.fn.setDataSoloDelay(num, 1);
                } else {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2));
                    $.fn.setDataSoloDelay(num, 1);
                }
            } else {
                if (delayInMs < delayScaleMin)
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMin;
                else if (delayInMs > delayScaleMax)
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMax;
                else
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayInMs;
                $.fn.setDataSoloDelay(num, 1);
            }
            $("#overviewButton" + num).trigger("click");
        }
    });

    //MANAGE EVENT ON SELECT PEQ NAVBAR BUTTON ALL OR SOLO EDIT
    $("body").on("click", "a[href=\"#peq\"]", function() {
        //INITIALIZE VALUE FOR SLIDERS
        for (var i = 0; i < eqCount; i++) {
            var freq = "#sliderHorizontalFreqPEQ" + i;
            var gain = "#sliderHorizontalGainPEQ" + i;
            var q = "#sliderHorizontalQPEQ" + i;
            if (displaySoloGroup === 0) {
                $(freq).slider("option", "value", Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency));
                $(gain).slider("option", "value", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);
                $(q).slider("option", "value", Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q));
            } else {
                $(freq).slider("option", "value", Math.log10(arrayGroup[groupGroupSelected].peq[i].frequency));
                $(gain).slider("option", "value", arrayGroup[groupGroupSelected].peq[i].gain);
                $(q).slider("option", "value", Math.log10(arrayGroup[groupGroupSelected].peq[i].q));
            }
        }
        $(".peqButtonNavBar").removeClass("active");
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // displayVal("id nav", num);
        var idS = "#peqAnav" + num;
        $(idS).addClass("active");
        var idEq = "#parametersAreaEQ" + num;
        $.fn.clearPEQParamArea();
        if (displaySoloGroup === 0 || displaySoloGroup === 1 && num < 100)
            $(idEq).show();

        if (num < eqCount) {
            peqSoloSelected = num;
            $.fn.drawPEQWidget(peqSoloSelected);
        }

        if (num === 100) {
            //TO DO SET SELECTED CHANNEL SOURCE
            $("#inlineRadio" + soloChannelSelected).attr("checked", true);
        }

        if (num === 200) {
            $("#inlineRadioGroup" + groupGroupSelected).attr("checked", true);
            $("#parametersAreaEQ200").show();
        }
    });

    //MANAGE EVENT ON ENABLE CHECKBOX PEQ PANEL
    $("body").on("change", ".enaInputPEQ", function() {
        //FIND NUMBER IN ID (FROM 0 TO 11);
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            var status = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].ena;
            switch (status) {
                case true:
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].ena = false;
                    break;
                case false:
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].ena = true;
                    break;
            }
            peqSoloSelected = num;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 0);
            $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
            $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
        } else {
            var status = arrayGroup[groupGroupSelected].peq[num].ena;
            switch (status) {
                case true:
                    arrayGroup[groupGroupSelected].peq[num].ena = false;
                    break;
                case false:
                    arrayGroup[groupGroupSelected].peq[num].ena = true;
                    break;
            }
            peqSoloSelected = num;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 0);
        }
    });

    //CHECK VALUE ON THE PEQ TYPE FIELD
    $("body").on("change", ".eqTypeSelect", function() {
        //FIND NUMBER IN ID (FROM 0 TO 11);
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].type = parseInt($(this).children("option:selected").val());
            $.fn.setDataSoloPEQ(num, 1);
            $.fn.initiatePEQDraggie();
            $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
            $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
        } else {
            arrayGroup[groupGroupSelected].peq[num].type = parseInt($(this).children("option:selected").val());
            $.fn.setDataSoloPEQ(num, 1);
            $.fn.initiatePEQDraggie();
        }
    });

    //CHECK VALUE ON THE PEQ FREQ FIELD
    $("body").on("change", ".freqInputPEQ", function() {
        //FIND NUMBER IN ID (FROM 0 TO 11);
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (!$.isNumeric(this.value)) {
            alert("DELAY VALUE BETWEEN 10 and 22000Hz");
            if (displaySoloGroup === 0)
                this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency;
            else
                this.value = arrayGroup[groupGroupSelected].peq[num].frequency;
            return;
        }
        var n = parseInt(this.value);
        if (n < freqScaleMinPEQ)
            n = freqScaleMinPEQ;
        if (n > freqScaleMaxPEQ)
            n = freqScaleMaxPEQ;
        // console.log("change " + num + " // freq " + this.value);
        if (displaySoloGroup === 0) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency = n;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 2);
            $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
            $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
        } else {
            arrayGroup[groupGroupSelected].peq[num].frequency = n;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 2);
        }
    });

    //CHECK VALUE ON THE PEQ GAIN FIELD
    $("body").on("change", ".gainInputPEQ", function() {
        //FIND NUMBER IN ID (FROM 0 TO 11);
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (!$.isNumeric(this.value)) {
            alert("GAIN BETWEEN -36.0dB to 18.0dB");
            if (displaySoloGroup === 0)
                this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain;
            else
                this.value = arrayGroup[groupGroupSelected].peq[num].gain;
            return;
        }
        var n = parseFloat(parseFloat(this.value).toFixed(1));
        if (n < gainScaleMinPEQ)
            n = gainScaleMinPEQ;
        if (n > gainScaleMaxPEQ)
            n = gainScaleMaxPEQ;
        if (displaySoloGroup === 0) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain = n;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 3);
        } else {
            arrayGroup[groupGroupSelected].peq[num].gain = n;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 3);
        }
    });

    //CHECK VALUE ON THE PEQ Q FIELD
    $("body").on("change", ".qInputPEQ", function() {
        //FIND NUMBER IN ID (FROM 0 TO 11);
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (!$.isNumeric(this.value)) {
            alert("Q BETWEEN 0.1 to 48");
            if (displaySoloGroup === 0)
                this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q;
            else
                this.value = arrayGroup[groupGroupSelected].peq[num].q;
            return;
        }
        var n = parseFloat(parseFloat(this.value).toFixed(2));
        if (n < qScaleMin)
            n = qScaleMin;
        if (n > qScaleMax)
            n = qScaleMax;
        if (displaySoloGroup === 0) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q = n;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 4);
            $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
            $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
        } else {
            arrayGroup[groupGroupSelected].peq[num].q = n;
            //SEND DATA TO AMPLIFIER
            $.fn.setDataSoloPEQ(num, 4);
        }
    });

    // MANAGE CHANNEL EVENT PEQ SOLO FREQUENCY BUTTON DOWN
    $("body").on("click", ".soloPEQFreqButtonDown", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency > freqScaleMinPEQ) {
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency - 1);
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 2);
                $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
            }
        } else {
            if (arrayGroup[groupGroupSelected].peq[num].frequency > freqScaleMinPEQ) {
                arrayGroup[groupGroupSelected].peq[num].frequency = parseFloat(parseFloat(arrayGroup[groupGroupSelected].peq[num].frequency - 1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 2);
            }
        }
    });

    // MANAGE CHANNEL EVENT PEQ SOLO FREQUENCY BUTTON UP
    $("body").on("click", ".soloPEQFreqButtonUp", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency < freqScaleMaxPEQ) {
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency + 1);
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 2);
                $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
            }
        } else {
            if (arrayGroup[groupGroupSelected].peq[num].frequency < freqScaleMaxPEQ) {
                arrayGroup[groupGroupSelected].peq[num].frequency = parseFloat(parseFloat(arrayGroup[groupGroupSelected].peq[num].frequency + 1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 2);
            }
        }
    });

    // MANAGE CHANNEL EVENT PEQ SOLO GAIN BUTTON DOWN
    $("body").on("click", ".soloPEQGainButtonDown", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            if (parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain) > gainScaleMinPEQ) {
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain - 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 3);
                $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
            }
        } else {
            if (arrayGroup[groupGroupSelected].peq[num].gain > gainScaleMinPEQ) {
                arrayGroup[groupGroupSelected].peq[num].gain = parseFloat(parseFloat(arrayGroup[groupGroupSelected].peq[num].gain - 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 3);
            }
        }
    });

    // MANAGE CHANNEL EVENT PEQ SOLO GAIN BUTTON UP
    $("body").on("click", ".soloPEQGainButtonUp", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            if (parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain) < gainScaleMaxPEQ) {
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain + 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 3);
                $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
            }
        } else {
            if (arrayGroup[groupGroupSelected].peq[num].gain < gainScaleMaxPEQ) {
                arrayGroup[groupGroupSelected].peq[num].gain = parseFloat(parseFloat(arrayGroup[groupGroupSelected].peq[num].gain + 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 3);
            }
        }
    });

    // MANAGE CHANNEL EVENT PEQ SOLO Q BUTTON DOWN
    $("body").on("click", ".soloPEQQButtonDown", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            if (parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q) > qScaleMin) {
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q - 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 4);
                $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
            }
        } else {
            if (arrayGroup[groupGroupSelected].peq[num].q > qScaleMin) {
                arrayGroup[groupGroupSelected].peq[num].q = parseFloat(parseFloat(arrayGroup[groupGroupSelected].peq[num].q - 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 4);
            }
        }
    });

    // MANAGE CHANNEL EVENT PEQ SOLO Q BUTTON UP
    $("body").on("click", ".soloPEQQButtonUp", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        if (displaySoloGroup === 0) {
            if (parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q) < qScaleMax) {
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q + 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 4);
                $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
            }
        } else {
            if (arrayGroup[groupGroupSelected].peq[num].q < qScaleMax) {
                arrayGroup[groupGroupSelected].peq[num].q = parseFloat(parseFloat(arrayGroup[groupGroupSelected].peq[num].q + 0.1).toFixed(1));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 4);
            }
        }
    });

    //OPEN MODAL VIEW FOR SOLO PEQ TYPE
    $("body").on("click", ".peqButtonTypeSolo", function() {
        peqSelectedModalType = $(this).data('id');
        // displayVal("modal  peq", $(this).data('id'))
        $("#cafeId").val($(this).data('id'));
        $('#modalPeqType').modal('show');
    });

    //ACTION WHEN SELECTED PEQ IS CLICKED ON MODAL
    $("body").on("click", ".peqModalTypeBtn", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // displayVal("selected type", peqLabel[num]);
        var dest = "#eqType" + peqSelectedModalType;
        $(dest).val(num);
        $(dest).trigger("change");
        $('#modalPeqType').modal('hide')
    });

    // MANAGE EVENT ON PEQ MAIN X LOCK MAGNITUDE
    $("body").on("click", "#eqLockMag", function() {
        this.classList.toggle('changed');
        if (this.classList.contains('changed'))
            widgetPEQMainXLock = true;
        else
            widgetPEQMainXLock = false;
        $.fn.initiatePEQDraggie();
    });

    // MANAGE EVENT ON PEQ MAIN Y LOCK FREQUENCY
    $("body").on("click", "#eqLockFreq", function() {
        this.classList.toggle('changed');
        if (this.classList.contains('changed'))
            widgetPEQMainYLock = true;
        else
            widgetPEQMainYLock = false;
        $.fn.initiatePEQDraggie();
    });

    // MANAGE EVENT ON PEQ MAIN Q LOCK Q
    $("body").on("click", "#eqLockQ", function() {
        this.classList.toggle('changed');
        if (this.classList.contains('changed'))
            widgetPEQMainQLock = true;
        else
            widgetPEQMainQLock = false;
        $.fn.initiatePEQDraggie();
    });

    // MANAGE EVENT ON PEQ MAIN VIEW OPTIONS MODAL
    $("body").on("click", "#peqModalSaveChange", function() {
        displayVal("save changes");
        // $.fn.initiatePEQDraggie();
    });

    //UPDATE GAIN SCALE PEQ
    $("body").on("change", ".peqGainScale", function() {
        var n = $(this).children("option:selected").val();
        // displayVal("val scale", n);
        peqGainScaleType = n;
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
        $.fn.drawPEQWidget(peqSoloSelected);

        for (var num = 0; num < eqCount; num++)
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].ena === true) {
                $.fn.setDataSoloPEQ(num);
            }
    });

    //UPDATE PHASE SCALE PEQ
    $("body").on("change", ".peqPhaseScale", function() {
        var n = $(this).children("option:selected").val();
        // displayVal("val scale", n);
        peqPhaseScaleType = n;
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
        $.fn.drawPEQWidget(peqSoloSelected);
        for (var num = 0; num < eqCount; num++)
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].ena === true) {
                $.fn.setDataSoloPEQ(num);
            }
    });

    //MANAGE EVENT WHEN VIEW MODE IS CHANGED
    $("body").on("change", "#peqViewMode", function() {
        var n = $(this).children("option:selected").val();
        peqViewMode = parseInt(n);
        // console.log("peqViewMode:" + peqViewMode);
        //SETUP PEQ GRAPH TO FOLLOW peqViewMode
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
        //REDRAW THE CURVE OF THE LATEST SELECTED PEQ
        $.fn.drawPEQWidget(peqSoloSelected);
        //ADJUST XOVER GRAPH TO FOLLOW peqViewMode
        $.fn.initXOVER(peqViewMode, xoverGainScaleType, xoverPhaseScaleType);
        //SETUP XOVER MODAL VALUE FOR VIEW MODE
        $("#xoverViewMode").val(peqViewMode);

        //PEQ SETUP
        // if ($("#peqMainPanel").is(":visible") && displaySoloGroup === 0)
        //     $("#overviewButtonMenuPeq").trigger("click");
        if ($("#peqMainPanel").is(":visible") && displaySoloGroup === 0)
            $("#overviewButtonMenuPeq").trigger("click");
        if (!$("#peqMainPanel").is(":visible") && displaySoloGroup === 1)
            $("#groupMenuButtonPeq").trigger("click");
        if ($("#xoverMainPanel").is(":visible"))
            $("#overviewButtonMenuXover").trigger("click");
    });

    // MANAGE EVENT ON XOVER MAIN VIEW OPTIONS MODAL
    $("body").on("click", "#xoverModalSaveChange", function() {
        displayVal("save changes");
    });

    //UPDATE GAIN SCALE XOVER
    $("body").on("change", ".xoverGainScale", function() {
        var n = $(this).children("option:selected").val();
        // displayVal("val scale", n);
        xoverGainScaleType = n;
        $.fn.initXOVER(peqViewMode, xoverGainScaleType, xoverPhaseScaleType);

        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true)
            $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true)
            $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
        $.fn.drawPEQWidget(peqSoloSelected);
    });

    //UPDATE PHASE SCALE XOVER
    $("body").on("change", ".xoverPhaseScale", function() {
        var n = $(this).children("option:selected").val();
        // displayVal("val scale", n);
        xoverPhaseScaleType = n;
        $.fn.initXOVER(peqViewMode, xoverGainScaleType, xoverPhaseScaleType);

        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true)
            $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true)
            $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
        $.fn.drawPEQWidget(peqSoloSelected);
    });

    //MANAGE EVENT WHEN VIEW MODE IS CHANGED XOVER
    $("body").on("change", "#xoverViewMode", function() {
        var n = $(this).children("option:selected").val();
        peqViewMode = n;
        $("#peqViewMode").val(peqViewMode);
        $("#peqViewMode").trigger("change");
    });

    //ACTION WHEN SELECTED XOVER IS CLICKED ON MODAL
    $("body").on("click", ".xoverModalTypeBtn", function() {

        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));

        if (this.id.indexOf("HighPass") >= 0) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType = num;
            $.fn.setDataSoloXover(0, 1);
        } else {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType = num;
            $.fn.setDataSoloXover(1, 4);
        }
        $.fn.drawPEQWidget(peqSoloSelected);
    });

    //CHECK VALUE ON THE HIGHPASS FREQ FIELD
    $("body").on("change", ".freqInputXOVER", function() {
        if (!$.isNumeric(this.value)) {
            alert("DELAY VALUE BETWEEN 10 and 22000Hz");
            if (this.id.indexOf("HighPass") >= 0) {
                this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq;
            } else {
                this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq;
            }
            return;
        }
        var n = parseInt(this.value);
        if (n < freqScaleMinPEQ)
            n = freqScaleMinPEQ;
        if (n > freqScaleMaxPEQ)
            n = freqScaleMaxPEQ;
        if (this.id.indexOf("HighPass") >= 0) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq = n;
            $.fn.setDataSoloXover(0, 2);
        } else {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq = n;
            $.fn.setDataSoloXover(1, 5);
        }
        $.fn.drawPEQWidget(peqSoloSelected);
    });

    //MANAGE EVENT ON ENABLE CHECKBOX XOVER PANEL
    $("body").on("change", ".enaXOVER", function() {
        //IF HIGHPASS CROSSOVER ENABLE BUTTON
        if (this.id.indexOf("HighPass") >= 0) {
            switch (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna) {
                case true:
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna = false;
                    break;
                case false:
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna = true;
                    break;
                default:
                    break;
            }
            $.fn.setDataSoloXover(0, 0);

            //IF LOWPASS CROSSOVER ENABLE BUTTON
        } else {
            switch (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna) {
                case true:
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna = false;
                    break;
                case false:
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna = true;
                    break;
                default:
                    break;
            }
            $.fn.setDataSoloXover(1, 3);
        }
        $.fn.drawPEQWidget(peqSoloSelected);
    });

    //MANAGE EVENT ON SPEAKER PRESET HIGH PASS FREQUENCY INPUT FIELD
    $("body").on("change", "#speakerPresetHPFrequency", function() {
        minSpeakerPresetVal = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpSpeakerPresetFreqLimit)
        if (!$.isNumeric(this.value)) {
            alert("FREQUENCY VALUE BETWEEN " + minSpeakerPresetVal + " AND 22000Hz");
            this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpSpeakerPresetFreq;
            return;
        }
        var n = parseInt(this.value);
        if (n < minSpeakerPresetVal) {
            n = minSpeakerPresetVal;
            alert("FREQUENCY VALUE BETWEEN " + minSpeakerPresetVal + " AND 22000Hz");
        }
        if (n > freqScaleMaxPEQ)
            n = freqScaleMaxPEQ;
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpSpeakerPresetFreq = n;
        $("#speakerPresetHPFrequency").val(n);
        $.fn.setDataSoloXover(9, 0);
    });

    //MANAGE EVENT ON SPEAKER PRESET LOW PASS FREQUENCY INPUT FIELD
    $("body").on("change", "#speakerPresetLPFrequency", function() {
        maxSpeakerPresetVal = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpSpeakerPresetFreqLimit)
        if (!$.isNumeric(this.value)) {
            alert("FREQUENCY VALUE BETWEEN 10 AND " + maxSpeakerPresetVal + "Hz");
            this.value = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpSpeakerPresetFreq;
            return;
        }
        var n = parseInt(this.value);
        if (n > maxSpeakerPresetVal) {
            n = maxSpeakerPresetVal;
            alert("FREQUENCY VALUE BETWEEN 10 AND " + maxSpeakerPresetVal + "Hz");
        }
        if (n < freqScaleMinPEQ)
            n = freqScaleMinPEQ;
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpSpeakerPresetFreq = n;
        $("#speakerPresetLPFrequency").val(n);
        $.fn.setDataSoloXover(10, 0);
    });

    //MANAGE EVENT ON XOVER FREQ DOWN HIGHPASS BUTTON
    $("body").on("click", "#xoverHPFreqDownButton", function() {
        displayVal("hpfreq", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq);
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq > freqScaleMinPEQ) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq) - 1;
            $.fn.setDataSoloXover(0, 2);
        }
    });

    //MANAGE EVENT ON XOVER FREQ UP HIGHPASS BUTTON
    $("body").on("click", "#xoverHPFreqUpButton", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq < freqScaleMaxPEQ) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq) + 1;
            $.fn.setDataSoloXover(0, 2);
        }
    });

    //MANAGE EVENT ON XOVER FREQ DOWN LOWPASS BUTTON
    $("body").on("click", "#xoverLPFreqDownButton", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq > freqScaleMinPEQ) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq) - 1;
            $.fn.setDataSoloXover(1, 5);
        }
    });

    //MANAGE EVENT ON XOVER FREQ UP LOWPASS BUTTON
    $("body").on("click", "#xoverLPFreqUpButton", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq < freqScaleMaxPEQ) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq = parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq) + 1;
            $.fn.setDataSoloXover(1, 5);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS THRESHOLD BUTTON DOWN
    $("body").on("click", ".thresRmsSoloLimiterBtnDown", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres > rmsThresScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres - 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 0);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS THRESHOLD BUTTON UP
    $("body").on("click", ".thresRmsSoloLimiterBtnUp", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres < rmsThresScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres + 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 0);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS THRESHOLD INPUT
    $("body").on("change", "#thresRmsSoloLimiterInput", function() {
        if (!$.isNumeric(this.value)) {
            alert("THRESHOLD VALUE BETWEEN " + rmsThresScaleMin + " and " + rmsThresScaleMax);
            $("#thresRmsSoloLimiterInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres);
        } else {
            var n = parseFloat(parseFloat(this.value).toFixed(1));
            if (n < rmsThresScaleMin)
                n = rmsThresScaleMin;
            if (n > rmsThresScaleMax)
                n = rmsThresScaleMax;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres = n;
            $.fn.setDataSoloLimiter(0, 0);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS ATTACK BUTTON DOWN
    $("body").on("click", ".attackRmsSoloLimiterBtnDown", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack > rmsAttackScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack - 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 1);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS ATTACK BUTTON UP
    $("body").on("click", ".attackRmsSoloLimiterBtnUp", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack < rmsAttackScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack + 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 1);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS ATTACK INPUT
    $("body").on("change", "#attackRmsSoloLimiterInput", function() {
        if (!$.isNumeric(this.value)) {
            alert("ATTACK VALUE BETWEEN " + rmsAttackScaleMin + " and " + rmsAttackScaleMax);
            $("#attackRmsSoloLimiterInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack);
        } else {
            var n = parseFloat(parseFloat(this.value).toFixed(1));
            if (n < rmsAttackScaleMin)
                n = rmsAttackScaleMin;
            if (n > rmsAttackScaleMax)
                n = rmsAttackScaleMax;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack = n;
            $.fn.setDataSoloLimiter(0, 1);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS RELEASE BUTTON DOWN
    $("body").on("click", ".releaseRmsSoloLimiterBtnDown", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease > rmsReleaseScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease - 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 2);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS RELEASE BUTTON UP
    $("body").on("click", ".releaseRmsSoloLimiterBtnUp", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease < rmsReleaseScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease + 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 2);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER RMS RELEASE INPUT
    $("body").on("change", "#releaseRmsSoloLimiterInput", function() {
        if (!$.isNumeric(this.value)) {
            alert("RELEASE VALUE BETWEEN " + rmsReleaseScaleMin + " and " + rmsReleaseScaleMax);
            $("#releaseRmsSoloLimiterInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease);
        } else {
            var n = parseFloat(parseFloat(this.value).toFixed(1));
            if (n < rmsReleaseScaleMin)
                n = rmsReleaseScaleMin;
            if (n > rmsReleaseScaleMax)
                n = rmsReleaseScaleMax;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease = n;
            $.fn.setDataSoloLimiter(0, 2);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER PEAK THRESHOLD BUTTON DOWN
    $("body").on("click", ".thresPeakSoloLimiterBtnDown", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres > peakThresScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres - 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 3);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER PEAK THRESHOLD BUTTON UP
    $("body").on("click", ".thresPeakSoloLimiterBtnUp", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres < peakThresScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres + 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 3);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER PEAK THRESHOLD RELEASE INPUT
    $("body").on("change", "#thresPeakSoloLimiterInput", function() {
        if (!$.isNumeric(this.value)) {
            alert("THRESHOLD VALUE BETWEEN " + peakThresScaleMin + " and " + peakThresScaleMax);
            $("#thresPeakSoloLimiterInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres);
        } else {
            var n = parseFloat(parseFloat(this.value).toFixed(1));
            if (n < peakThresScaleMin)
                n = peakThresScaleMin;
            if (n > peakThresScaleMax)
                n = peakThresScaleMax;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres = n;
            $.fn.setDataSoloLimiter(0, 3);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER PEAK RELEASE BUTTON DOWN
    $("body").on("click", ".releasePeakSoloLimiterBtnDown", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease > peakReleaseScaleMin) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease - 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 4);
        }
    });

    //MANAGE EVENT ON SOLO LIMITER PEAK RELEASE BUTTON UP
    $("body").on("click", ".releasePeakSoloLimiterBtnUp", function() {
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease < peakReleaseScaleMax) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease = parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease + 0.1).toFixed(1));
            $.fn.setDataSoloLimiter(0, 4);
        }
    });


    //MANAGE EVENT ON SOLO LIMITER PEAK RELEASE RELEASE INPUT
    $("body").on("change", "#releasePeakSoloLimiterInput", function() {
        if (!$.isNumeric(this.value)) {
            alert("RELEASE VALUE BETWEEN " + peakReleaseScaleMin + " and " + peakReleaseScaleMax);
            $("#releasePeakSoloLimiterInput").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease);
        } else {
            var n = parseFloat(parseFloat(this.value).toFixed(1));
            if (n < peakReleaseScaleMin)
                n = peakReleaseScaleMin;
            if (n > peakReleaseScaleMax)
                n = peakReleaseScaleMax;
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease = n;
            $.fn.setDataSoloLimiter(0, 4);
        }
    });

    //MANAGE EVENT ON PER CHANNEL GROUP ASSIGN
    $("body").on("click", "a[href=\"#groupAssign\"]", function() {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // console.log("hello world" + num);
    });

    //MANAGE EVENT ON TEXTFIELD GAIN GROUP PANEL
    $("body").on("change", "#gainGroup", function() {
        if (!$.isNumeric(this.value)) {
            alert("DELAY VALUE BETWEEN " + gainScaleMin + "dB and " + gainScaleMax + "dB")
            this.value = arrayGroup[groupGroupSelected].gain.gain;
            return;
        } else {
            if (this.value < gainScaleMin)
                arrayGroup[groupGroupSelected].gain.gain = gainScaleMin;
            else if (this.value > gainScaleMax)
                arrayGroup[groupGroupSelected].gain.gain = gainScaleMax;
            else
                arrayGroup[groupGroupSelected].gain.gain = parseFloat(parseFloat(this.value).toFixed(1));
            $.fn.setDataGroupGain(groupGroupSelected, 1);
        }
    });

    // MANAGE EVENT ON BUTTON VOL UP GAIN GROUP PANEL
    $("body").on("click", "#gainGroupVolUp", function() {
        if (arrayGroup[groupGroupSelected].gain.gain < gainScaleMax) {
            arrayGroup[groupGroupSelected].gain.gain = parseFloat(parseFloat(arrayGroup[groupGroupSelected].gain.gain + 0.1).toFixed(1));
            $.fn.setDataGroupGain(groupGroupSelected, 1);
        }
    });

    // MANAGE EVENT ON BUTTONVOLDOWN GAIN GROUP PANEL
    $("body").on("click", "#gainGroupVolDown", function() {
        if (arrayGroup[groupGroupSelected].gain.gain > gainScaleMin) {
            arrayGroup[groupGroupSelected].gain.gain = parseFloat(parseFloat(arrayGroup[groupGroupSelected].gain.gain - 0.1).toFixed(1));
            $.fn.setDataGroupGain(groupGroupSelected, 1);
        }
    });

    //MANAGE EVENT ON TEXTFIELD DELAY GROUP PANEL
    $("body").on("change", "#delayGroup", function() {
        if (!$.isNumeric(this.value)) {
            alert("DELAY VALUE BETWEEN 0 and 250 ms")
            this.value = arrayGroup[groupGroupSelected].delay.delay;
        } else {
            if (this.value < delayScaleMin)
                arrayGroup[groupGroupSelected].delay.delay = delayScaleMin;
            else if (this.value > delayScaleMax)
                arrayGroup[groupGroupSelected].delay.delay = delayScaleMax;
            else
                arrayGroup[groupGroupSelected].delay.delay = parseFloat(parseFloat(this.value).toFixed(1));
            $.fn.setDataGroupDelay(groupGroupSelected, 1);
        }
    });

    // MANAGE EVENT ON BUTTONDELAYUP DELAY GROUP PANEL
    $("body").on("click", "#delayGroupUp", function() {
        if (arrayGroup[groupGroupSelected].delay.delay < delayScaleMax) {
            arrayGroup[groupGroupSelected].delay.delay = parseFloat(parseFloat(arrayGroup[groupGroupSelected].delay.delay + 0.1).toFixed(1));
            $.fn.setDataGroupDelay(groupGroupSelected, 1);
        }
    });

    // MANAGE EVENT ON BUTTONDELAYDOWN DELAY GROUP PANEL
    $("body").on("click", "#delayGroupDown", function() {
        if (arrayGroup[groupGroupSelected].delay.delay > delayScaleMin) {
            arrayGroup[groupGroupSelected].delay.delay = parseFloat(parseFloat(arrayGroup[groupGroupSelected].delay.delay - 0.1).toFixed(1));
            $.fn.setDataGroupDelay(groupGroupSelected, 1);
        }
    });

    // GROUP NAME TEXTFIELD
    $("body").on("change", ".inputGroupNameTextField", function() {
        // var id = "#" + $(this).attr("id");
        // var numGroup = id.substr(id.length - 1);
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        arrayGroup[num].label = $("#groupName" + num).val().toString();
        $.fn.setDataGroupLabel(1, num);
    });

    //SHOW SOURCE MAIN PANEL
    $("body").on("click", "#overviewButtonMenuSource", function() {
        $.fn.hideMainPanels();
        $("#sourceMainPanel").show();
        $.fn.setDataSoloSource(99, 99);
        $.fn.setDataSoloMixer(99, 99);
        $.fn.setDataSoloSigGenUpdate();
        if ($.fn.getModel() === 7) {
            var nCL = "NW " + (soloChannelSelected + 1);
            $("#mixerLabel4").html(nCL);
        }
        if ($.fn.getModel() === 9) {
            $("#mixerLabel2").html(sourceOverviewLabel[1]);
        }
    });

    //SHOW GAIN MAIN PANEL
    $("body").on("click", "#overviewButtonMenuGain", function() {
        $.fn.hideMainPanels();
        //model type should be the argument
        $.fn.setupGainSolo($.fn.getModel());
        resize();
        $("#gainMainPanel").show();
        $.fn.setDataSoloGain(99, 99);
    });

    //SHOW DELAY MAIN PANEL
    $("body").on("click", "#overviewButtonMenuDelay", function() {
        $.fn.hideMainPanels();
        //model type should be the argument
        $.fn.setupDelaySolo($.fn.getModel());
        resize();
        $("#delayMainPanel").show();
        $.fn.setDataSoloDelay(99, 99);
    });

    //SHOW PEQ MAIN PANEL
    $("body").on("click", "#overviewButtonMenuPeq", function() {
        displaySoloGroup = 0;

        //LOAD DATA FROM SELECTED CHANNEL
        switch (soloChannelSelected) {
            case 0:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq;
                break;
            case 1:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq;
                break;
            case 2:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq;
                break;
            case 3:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq;
                break;
            default:
                break;
        }

        $.fn.hideMainPanels();
        $.fn.setupPeqSolo(0);
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);

        $.fn.setupXOVERSolo();
        $.fn.initXOVER(peqViewMode, peqGainScaleType, peqPhaseScaleType);

        $.fn.drawPEQWidget(99);
        $("#peqMainPanel").show();
        $.fn.drawPEQWidget(peqSoloSelected);

        $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
        $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);

        $.fn.initSliderPEQ();
        $.fn.setDataSoloPEQ(99, 99);
    });

    //SHOW XOVER MAIN PANEL
    $("body").on("click", "#overviewButtonMenuXover", function() {
        //LOAD DATA FROM SELECTED CHANNEL
        switch (soloChannelSelected) {
            case 0:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq;
                break;
            case 1:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq;
                break;
            case 2:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq;
                break;
            case 3:
                arrayEqParam = arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq;
                break;
            default:
                break;
        }
        $.fn.setupPeqSolo(0);
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
        $.fn.drawPEQWidget(99);
        $.fn.setupXOVERSolo();
        $.fn.initXOVER(peqViewMode, peqGainScaleType, peqPhaseScaleType);
        $.fn.hideMainPanels();
        $("#xoverMainPanel").show();
        $.fn.setDataSoloXover(4, 99);
    });

    //SHOW LIMITER MAIN PANEL
    $("body").on("click", "#overviewButtonMenuLimiter", function() {
        $.fn.hideMainPanels();
        $("#limiterMainPanel").show();
        resize();
        $.fn.resizeLimiter();
        $.fn.setDataSoloLimiter(1, 99);
    });

    //SHOW OUTPUT MAIN PANEL
    $("body").on("click", "#overviewButtonMenuOutput", function() {
        $.fn.hideMainPanels();
        $("#outputMainPanel").show();
        $.fn.setDataSoloOutputUpdate();
    });

    //SHOW SPEAKER MAIN PANEL
    $("body").on("click", "#overviewButtonMenuSpeaker", function() {
        $(".overviewMenuDiv > .btnOverview").removeClass("active");
        $(this).addClass("active")
        $.fn.hideMainPanels();
        $("#speakerMainPanel").show();
        $.fn.setDataSoloSpeaker(99);
        $.fn.setDataSoloXover(7, 0);
        $.fn.setDataSoloXover(8, 0);
        setTimeout(function() { $.fn.setDataSoloSpeaker(100); }, 2000);
    });

    //SHOW GROUP VIEW MAIN PANEL
    $("body").on("click", "#buttonGroup", function() {
        $(".openSetupButton > img").attr("src", "./img/parameter.png");
        $("#iconSetup").removeClass("active");
        $(".btnSelector").removeClass("active");
        $("#buttonGroup").addClass("active");
        $.fn.openGroupsView();
        $("#groupMenuButtonGain").trigger("click");
    });

    //SHOW BACK TO AMP VIEW WITH GAIN PANEL
    $("body").on("click", ".btnSelector", function(e) {
        // if click on "i" button to get info from the device
        if (e.target.id.indexOf("dldmbi") != -1 || e.target.id.indexOf("dldmi") != -1) {
            var source = parseInt(e.target.id.toString().match(/(\d+)/g).map(Number));
            $("#networkStatusModalTitle").html("Status of " + discoveryList[source].cloud_device_name);
            //CLOUD DEVICE NAME
            $("#networkModalCDN").html("<i>Cloud device name : </i>" + discoveryList[source].cloud_device_name);
            if (discoveryList[source].cloud_device_name.length == 0)
                $("#networkModalCDN").html("<i>Cloud device name : </i> <b>set cloud device name to remote access</b>");
            //IP ADDRESS
            $("#networkModalIP").html("<i>IP address : </i>" + discoveryList[source].ip_addr);
            //MAC ADDRESS (HARDWARE)
            $("#networkModalMAC").html("<i>MAC address : </i>" + discoveryList[source].hw_addr);
            //MODEL
            $("#networkModalModel").html("<i>Model : </i>" + discoveryList[source].model);
            //SERIAL
            $("#networkModalSerial").html("<i>Serial number : </i>" + arrayAmplifier[source].serial);
            //IF DEVICE IS NOT LOCAL THEN DISPLAY LAST REPORTED TIME
            if (discoveryList[source].last_report_time != 0)
                $("#networkModalSerial").html("<i>Last seen : </i>" + toDateTime(discoveryList[source].last_report_time));
            //ALIVE
            if (discoveryList[source].alive)
                $("#networkModalA").html("<i>Device alive : </i> OK");
            else
                $("#networkModalA").html("<i>Device alive : </i> not OK");
            //WS
            if (discoveryWorker[source].ws)
                $("#networkModalWS").html("<i>Websocket status : </i> OK");
            else
                $("#networkModalWS").html("<i>Websocket status : </i> not OK");

            $("#networkStatusModal").modal("show");
            // if click on the button itself, makes the software choose this amp as loaded data amp
        } else {
            soloAmplifierSelected = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            $.fn.setupOverviewSolo($.fn.getModel());
            $.fn.setupSourceSolo($.fn.getModel());

            $(".openSetupButton > img").attr("src", "./img/parameter.png");
            $(".openCopyButton > img").attr("src", "./img/copy.png");
            $("#iconSetup").removeClass("active");
            $(".btnSelector").removeClass("active");
            $(this).addClass("active");
            $("#buttonGroup").removeClass("active");
            $.fn.openAmpView();

            // if (arrayAmplifier[soloAmplifierSelected].label.length > 0)
            $(".topMenuTitle").html("" + arrayAmplifier[soloAmplifierSelected].label + " : " + arrayAmplifier[soloAmplifierSelected].network.lan.ip);
            $.fn.setDataSoloOutputUpdate();

            // $("#overviewButtonMenuSource").trigger("click");

            // $("#overviewButton0").trigger("click");
            // $.fn.setVisualBridge();

            $.fn.loadAmpOnScreen();
            setTimeout(function() {
                $("#overviewButton0").trigger("click");
            }, 500);
        }
    });

    //SHOW BACK TO AMP VIEW WITH GAIN PANEL
    $("body").on("click", ".btnSelectorOffline", function(e) {
        // console.log("target:" + e.target.localName);
        if (e.target.id.indexOf("dldmbi") != -1 || e.target.id.indexOf("dldmi") != -1) {
            var source = parseInt(e.target.id.toString().match(/(\d+)/g).map(Number));
            $("#networkStatusModalTitle").html("Status of " + discoveryList[source].cloud_device_name);
            //CLOUD DEVICE NAME
            $("#networkModalCDN").html("<i>Cloud device name : </i>" + discoveryList[source].cloud_device_name);
            if (discoveryList[source].cloud_device_name.length == 0)
                $("#networkModalCDN").html("<i>Cloud device name : </i> <b>set cloud device name to remote access</b>");
            //IP ADDRESS
            $("#networkModalIP").html("<i>IP address : </i>" + discoveryList[source].ip_addr);
            //MAC ADDRESS (HARDWARE)
            $("#networkModalMAC").html("<i>MAC address : </i>" + discoveryList[source].hw_addr);
            //MODEL
            $("#networkModalModel").html("<i>Model : </i>" + discoveryList[source].model);
            //SERIAL
            $("#networkModalSerial").html("<i>Serial number : </i>" + arrayAmplifier[source].serial);
            //IF DEVICE IS NOT LOCAL THEN DISPLAY LAST REPORTED TIME
            if (discoveryList[source].last_report_time != 0)
                $("#networkModalSerial").html("<i>Last seen : </i>" + toDateTime(discoveryList[source].last_report_time));
            //ALIVE
            $("#networkModalA").html("<i>Device alive : </i>" + discoveryList[source].alive);
            //WS
            $("#networkModalWS").html("<i>Websocket status : </i>" + discoveryWorker[source].ws);

            $("#networkStatusModal").modal("show");
        }
    });

    //REFRESH NETWORK LIST
    $("body").on("click", "#buttonClear", function(e) {
        $("#discoveryListDevice0").trigger("click");
        for (var i = 1; i < discoveryList.length; i++) {
            $.fn.closeDiscoveryWS(i);
        }
        setTimeout(function() {

            discoveryList.splice(1);
            discoveryWorker.splice(1);
            request_pool.splice(1);
            arrayAmplifier.splice(1);
            arrayGroupData.splice(1);
            //CLEAR CONTENT OF NETWORK DEVICES LIST (EXCEPT THE LOCAL ONE)
            $("#networkDeviceList").html("");
            $.fn.sendCommandWS(cmd_set_clear_neighbour_list, 0, "null", "null", "null");

        }, 2000);

    });

    $("body").on('hidden.bs.popover', function(e) {
        $(e.target).data("bs.popover")._activeTrigger.click = false;
    });

    //SHOW GAIN GROUP PANEL
    $("body").on("click", "#groupMenuButtonGain", function() {
        $.fn.hideGroupPanels();
        groupGroupPanel = 0;
        $("#gainGroupPanel").show();
    });

    //SHOW DELAY GROUP PANEL
    $("body").on("click", "#groupMenuButtonDelay", function() {
        $.fn.hideGroupPanels();
        groupGroupPanel = 1;
        $("#delayGroupPanel").show();
    });

    //SHOW PEQ GROUP PANEL
    $("body").on("click", "#groupMenuButtonPeq", function() {
        groupGroupPanel = 2;
        displaySoloGroup = 1;

        switch (groupGroupSelected) {
            case 0:
                arrayEqParam = arrayGroup[0].peq;
                break;
            case 1:
                arrayEqParam = arrayGroup[1].peq;
                break;
            case 2:
                arrayEqParam = arrayGroup[2].peq;
                break;
            case 3:
                arrayEqParam = arrayGroup[3].peq;
                break;
            case 4:
                arrayEqParam = arrayGroup[4].peq;
                break;
            case 5:
                arrayEqParam = arrayGroup[5].peq;
                break;
            default:
                break;
        }
        $.fn.hideGroupPanels();
        $.fn.setupPeqSolo(1);
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
        $.fn.drawPEQWidget(99);
        $.fn.initSliderPEQ();

        $("#peqGroupPanel").show();
        $("#groupSelectButton" + groupGroupSelected).trigger("click");
    });

    // EDIT GROUP BUTTON
    $("body").on("click", "#groupMenuButtonRegister", function() {
        $.fn.hideGroupPanels();
        $("#groupRegisterPanel").show();
        $("#assignGroupTabTable > .hide").css("display", "none");
        $(".logoSetupSmallChevron").attr("src", "./img/Down.png");
        $.fn.setupGroupAssign();
        $("#ampListIndex0").trigger("click");
    });

    // EDIT GROUP BUTTON
    $("body").on("click", "#groupMenuButtonEdit", function() {
        $.fn.hideGroupPanels();
        $("#groupEditPanel").show();
    });

    // UPDATE SELECTED GROUP TITLE IN GAIN-DELAY-PEQ PANEL
    $("body").on("click", ".btnGroupManage", function() {
        var id = "#" + $(this).attr("id");
        // console.log("groupid:" + id);
        $(".btnGroupManage").removeClass("active");
        $(".inputRadioGroup").prop("checked", false);
        var numGroup = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        groupGroupSelected = numGroup;
        var txt = "#groupName" + numGroup;
        var tyt = "#groupButton" + numGroup;
        $("#gainPanelGroupName").text($(txt).val());
        $("#delayPanelGroupName").text($(txt).val());
        $("#peqPanelGroupName").text($(txt).val());
        $(tyt).prop("checked", true);

        switch (groupGroupPanel) {
            case 0:
                $.fn.setDataGroupGain(99, 99);
                break;
            case 1:
                $.fn.setDataGroupDelay(99, 99);
                break;
            case 2:
                $.fn.setDataSoloPEQ(99, 99);
                break;
            default:
                break;
        }
    });


    //CHANNEL MUTE ENABLE BUTTON
    $("body").on("click", ".overviewButtonMute", function() {
        let num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        switch (arrayAmplifier[soloAmplifierSelected].channel[num].gain.muteEna) {
            case true:
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.muteEna = false;
                $.fn.setDataSoloGain(num, 0);
                break;
            case false:
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.muteEna = true;
                $.fn.setDataSoloGain(num, 0);
                break;
        }
    });

    //CHANNEL MUTE ENABLE BUTTON
    $("body").on("click", ".overviewButtonMute16", function() {
        let num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        switch (arrayAmplifier[soloAmplifierSelected].channel[num].gain.muteEna) {
            case true:
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.muteEna = false;
                $.fn.setDataSoloGain(num, 0);
                break;
            case false:
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.muteEna = true;
                $.fn.setDataSoloGain(num, 0);
                break;
        }
    });

    //CHANNEL BUTTON OVERVIEW STYLE
    $("body").on("click", ".overviewMenuDiv > .btnOverview", function() {
        $("#overviewButtonMenuSpeaker").removeClass("active");
        $(".overviewMenuDiv > .btnOverview").removeClass("active");
        $(this).addClass("active");
    });

    //GROUP BUTTON OVERVIEW STYLE
    $("body").on("click", ".backgroundGroupButton > .btnOverview", function() {
        $(".backgroundGroupButton > .btnOverview").removeClass("active");
        $(this).addClass("active");
    });

    // GROUPS MUTE ENABLE BUTTON
    $("body").on("click", ".itemQuarterGroupButtonMute", function() {
        switch (arrayGroup[groupGroupSelected].gain.muteEna) {
            case true:
                arrayGroup[groupGroupSelected].gain.muteEna = false;
                break;
            case false:
                arrayGroup[groupGroupSelected].gain.muteEna = true;
                break;
            default:
                break;
        }
        $.fn.setDataGroupGain(groupGroupSelected, 0);
    });

    // GROUPS PHASE ENABLE BUTTON
    $("body").on("click", ".itemQuarterGroupButtonPhase", function() {
        switch (arrayGroup[groupGroupSelected].gain.polarityEna) {
            case true:
                arrayGroup[groupGroupSelected].gain.polarityEna = false;
                break;
            case false:
                arrayGroup[groupGroupSelected].gain.polarityEna = true;
                break;
        }
        $.fn.setDataGroupGain(groupGroupSelected, 2);
    });

    // GROUPS DELAY ENABLE BUTTON
    $("body").on("click", ".itemQuarterGroupButtonDelay", function() {
        switch (arrayGroup[groupGroupSelected].delay.delayEna) {
            case true:
                arrayGroup[groupGroupSelected].delay.delayEna = false;
                break;
            case false:
                arrayGroup[groupGroupSelected].delay.delayEna = true;
                break;
        }
        $.fn.setDataGroupDelay(groupGroupSelected, 0);
    });

    //  OPEN NAV BAR BUTTON
    $("body").on("click", ".openNavButton", function() {
        $('#mySidenav').toggleClass('active');
        if ($('#mySidenav').hasClass("active")) {
            widgetPEQX = widgetPEQX + 250;
            widgetXOVERX = widgetXOVERX + 250;
        } else {
            widgetPEQX = widgetPEQX - 250;
            widgetXOVERX = widgetXOVERX - 250;
        }
        $.fn.setupPeqSolo(0);
        $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);

        $.fn.setupXOVERSolo();
        $.fn.initXOVER(xoverDefaultViewMode, peqGainScaleType, peqPhaseScaleType);

        $.fn.drawPEQWidget(99);
        $.fn.drawPEQWidget(peqSoloSelected);

        $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
        $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);

        $.fn.initSliderPEQ();
        $.fn.setDataSoloPEQ(99, 99);
    });

    // SELECT FOLDER IN SPEAKER PRESET AREA
    $("body").on("change", "#folderListSpeakerPreset", function() {
        $("#fileListSpeakerPreset").html("");
        // displayVal("folder list speaker preset", this.value);
        var str = "";
        for (var i = 0; i < 10; i++) {
            str += "<option value=" + (i + 1) + ">Folder " + this.value + " - Files " + (i + 1) + "</option>";
        }
        $("#fileListSpeakerPreset").append(str);
    });

    //MANAGE EVENT ON CHANGE CHANNEL LABEL
    $("body").on("change", ".itemEighterChannelLabelTextField", function() {
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].label = $(".itemEighterChannelLabelTextField").val();
        $.fn.setDataSoloSource(soloChannelSelected, 2);
    });

    $("body").on("click", ".itemEighterMuteAllButton", function() {
        for (var i = 0; i < maxMixerInput; i++) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[i] = -80.0;
        }
        $.fn.setDataSoloMixer(3, soloChannelSelected);
    });

    //MANAGE EVENT ON APPLY COPY CHANNEL PARAMETERS
    $("body").on("click", "#copyChannelContentApply", function() {
        var arrCmd = new Array(0);
        var src = -1;
        var destArray = new Array(0);
        var copyContent = new Object();
        copyContent.mixer = false;
        copyContent.gain = false;
        copyContent.delay = false;
        copyContent.peq = false;
        copyContent.xover = false;
        copyContent.limiter = false;
        copyContent.preset = false;

        //SOURCE
        $(".copyChannelSourceRadio:checked").each(function() {
            src = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        });

        //COPY
        if ($(copyChannelContentMixerCB).is(':checked')) {
            copyContent.mixer = true;
            // console.log("Copy : mixer")
        }
        if ($(copyChannelContentGainCB).is(':checked')) {
            copyContent.gain = true;
            // console.log("Copy : gain")
        }
        if ($(copyChannelContentDelayCB).is(':checked')) {
            copyContent.delay = true;
            // console.log("Copy : delay")
        }
        if ($(copyChannelContentPEQCB).is(':checked')) {
            copyContent.peq = true;
            // console.log("Copy : peq")
        }
        if ($(copyChannelContentXOVERCB).is(':checked')) {
            copyContent.xover = true;
            // console.log("Copy : xover")
        }
        if ($(copyChannelContentLimiterCB).is(':checked')) {
            copyContent.limiter = true;
            // console.log("Copy : limiter")
        }
        if ($(copyChannelContentPresetCB).is(':checked')) {
            copyContent.preset = true;
            // console.log("Copy : preset")
        }

        //DESTINATION
        $(".copyChannelDest:checked").each(function() {
            dest = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            destArray.push(dest);
        });

        console.log("source = " + src + " // content = " + JSON.stringify(copyContent) + " // destination = " + destArray);

        if (destArray.length > 0) {
            var copyContentTxt = JSON.stringify(copyContent)
            let resultTxt = copyContentTxt.replaceAll("\"", "\\\"");
            arrCmd.push($.fn.getCommandFromArgs(cmd_set_copy_channel_parameters, soloAmplifierSelected, parseInt(src), "\"" + destArray + "\"", resultTxt));
        }

        if (arrCmd.length > 0)
            $.fn.sendCommandsWS(arrCmd);
    });

    $("body").on("change", "input[type=radio][name=copyChannelOptions]", function(e) {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // console.log("source:" + num);
        $(".copyChannelSourceRadio").attr("checked", false);
        $("#inlineSourceRadio" + num).attr("checked", true);
    });

    $("body").on("change", ".copyChannelDest", function(e) {
        var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
        // console.log("source:" + num);
        $(".copyChannelDest").attr("checked", false);
        $("#copyChannelDest" + num).attr("checked", true);
    });

    $("#iconWifi").addClass("iconWifiOn");
    $("#iconEthernet").addClass("iconEtherOn");
    $("#iconCloud").addClass("iconCloudOn");
    $("#iconCloud").addClass("iconCloudOn");

    //MANAGE EVENT ON OPEN HOME BUTTON
    $("body").on("click", ".openHomeButton", function() {
        $(".openSetupButton > img").attr("src", "./img/parameter.png");
        $(".openCopyButton > img").attr("src", "./img/copy.png");
        $("#iconSetup").removeClass("active");
        $(".btnSelector").removeClass("active");
        $("#buttonGroup").removeClass("active");
        $.fn.openAmpView();
        $("#discoveryListDevice0").addClass("active");
        $("#discoveryListDevice0").trigger("click");
        $("#overviewButtonMenuSource").trigger("click");
        // $("#overviewButton0").trigger("click");
        setTimeout(function() {
            $("#overviewButton0").trigger("click");
        }, 500);
    });

    //MANAGE EVENT ON OPEN SETUP BUTTON
    $("body").on("click", ".openSetupButton", function() {
        $.fn.openSetupView();
        $(".btnSelector").removeClass("active");
        $("#discoveryListDevice" + soloAmplifierSelected).addClass("active");
        $("#buttonGroup").removeClass("active");
        $("#iconSetup").addClass("active");
        $(".openSetupButton > img").attr("src", "./img/parameter_active.png");
        $(".openCopyButton > img").attr("src", "./img/copy.png");
        $.fn.sendCommandWS(cmd_get_global_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
        $.fn.loadSettings();
    });

    //MANAGE EVENT ON OPEN COPY BUTTON
    $("body").on("click", ".openCopyButton", function() {
        $.fn.openCopyView();
        $(".btnSelector").removeClass("active");
        $("#discoveryListDevice" + soloAmplifierSelected).addClass("active");
        $("#buttonGroup").removeClass("active");
        // $("#iconSetup").addClass("active");
        $(".openSetupButton > img").attr("src", "./img/parameter.png");
        $(".openCopyButton > img").attr("src", "./img/copy_active.png");
        $.fn.setupCopyChannelParam($.fn.getModel());
        $(".copyChannelSourceRadio").attr("checked", false);
        $("#inlineSourceRadio" + soloChannelSelected).attr("checked", true);
    });

    //MANAGE EVENT ON OPEN LOCK BUTTON
    $("body").on("click", ".openLockButton", function(e) {
        $(".openSetupButton > img").attr("src", "./img/parameter.png");
        $(".openCopyButton > img").attr("src", "./img/copy.png");
        $("#loginPanel").addClass("is-active");
        $("#loginEmail").val("");
        $("#loginPassword").val("");
        // $.fn.setupGainSolo(0);
    });
    //MANAGE EVENT ON OPEN STATUS BUTTON
    $("body").on("click", ".openStatusButton", function(e) {
        $(".openSetupButton > img").attr("src", "./img/parameter.png");
        $(".openCopyButton > img").attr("src", "./img/copy.png");
        $(".openSetupButton").trigger("click");
        $("#status-tab").trigger("click");
    });

    window.addEventListener("resize", resize);

    // INITIALIZE VUE AT STARTUP
    // $.fn.setupOverviewSolo(6);

    $.fn.hideGroupPanels();

    $.fn.hideMainPanels();

    $.fn.openAmpView();

    $.fn.initData();

    // $.fn.setupSourceSolo(6);

    $.fn.createWebSocket();

    $.fn.setupLimiterSolo();

    $.fn.initSlider();

    // $.fn.setupPeqSolo();

    // $.fn.setupXOVERSolo();

    // $.fn.initXOVER(peqViewMode, peqGainScaleType, peqPhaseScaleType);

    // $.fn.setDataSoloXover(4, 99);

    // $.fn.drawXOVERWidget(0, highPassEqParam.type);
    // $.fn.drawXOVERWidget(1, lowPassEqParam.type);

    $.fn.updateClock();



    //SELECT THE CHANNEL 1 AS DEFAULT SELECTED CHANNEL
    setTimeout(function() {
        $("#overviewButtonMenuSource").trigger("click");
        $("#overviewButton0").trigger("click");
        $(window).resize();

        $.fn.resizeLimiter();


        $.fn.setupPeqSolo();

        $.fn.setupXOVERSolo();

        $.fn.initXOVER(peqViewMode, peqGainScaleType, peqPhaseScaleType);

        $.fn.setDataSoloXover(4, 99);

        $.fn.drawXOVERWidget(0, highPassEqParam.type);
        $.fn.drawXOVERWidget(1, lowPassEqParam.type);


    }, 4000);

    for (var i = 0; i < 10; i++) {
        var id = "#closeAmp" + i;
        $(id).trigger("click");
    }

    $.fn.resizeWindows();


    if (demoMode === 1) {
        $.fn.dataLoaded();
    }

    $.fn.displayTime();

    $("#backgroundOverviewButton").width($("#overviewChannelArea").scrollWidth);


    //CLEAR VU METER
    for (var i = 0; i < channel16Count; i++) {
        // for (var i = 0; i < channelCount; i++) {
        $(".rectangleInput" + i).css("transform", 'scaleY(0)');
        $("#overviewVuMeterInput" + i).css("transform", 'scaleY(0)');
        $("#overviewCompMeterInput" + i).css("transform", 'scaleY(0)');
    }
});


$.fn.loadAmpOnScreen = function() {
    setTimeout(function() {
        $("#overviewButton0").trigger("click");
        $("#overviewButtonMenuSource").trigger("click");

        $.fn.initSlider();
        resize();
    }, 300);

}

//RETURN MODEL OF "INDEX" OR "SOLOAMPLIFIERSELECTED" AMPLIFIER ON THE NEIGHBOURLIST
$.fn.getModel = function(index) {
    var ret = 0;
    var indexAmp = 0;
    //IF INDEX VALUE IS PROVIDED WHEN CALLING THE FUNCTION
    if (index === undefined)
        indexAmp = soloAmplifierSelected;
    else
        indexAmp = index;

    switch (discoveryList[indexAmp].model) {
        case "CP354":
            ret = 1;
            break;
        case "CP704":
            ret = 2;
            break;
        case "CP1504":
            ret = 3;
            break;
        case "CP3004":
            ret = 4;
            break;
        case "CP0701":
            ret = 5;
            break;
        case "CP0702":
            ret = 6;
            break;
        case "CP0716":
            ret = 7;
            break;
        case "CP7164":
            ret = 8;
            break;
        case "CP0703":
            ret = 9;
            break;
        default:
            ret = 0;
            break;
    }
    // displayVal("getModel", ret);
    return ret;
}

//RETURN PLATE AMP TRUE // FALSE OF "INDEX" OR "SOLOAMPLIFIERSELECTED" AMPLIFIER ON THE NEIGHBOURLIST
$.fn.getPlateAmp = function(index) {
    var ret = false;
    var indexAmp = 0;
    //IF INDEX VALUE IS PROVIDED WHEN CALLING THE FUNCTION
    if (index === undefined)
        indexAmp = soloAmplifierSelected;
    else
        indexAmp = index;

    switch (discoveryList[indexAmp].model) {
        case "CP354":
            ret = false;
            break;
        case "CP704":
            ret = false;
            break;
        case "CP1504":
            ret = false;
            break;
        case "CP3004":
            ret = false;
            break;
        case "CP0701":
            ret = true;
            break;
        case "CP0702":
            ret = true;
            break;
        case "CP0716":
            ret = false;
            break;
        case "CP7164":
            ret = false;
            break;
        case "CP0703":
            ret = true;
            break;
        default:
            ret = false;
            break;
    }
    // displayVal("getModel", ret);
    return ret;
}

$.fn.getChannelCount = function(index) {
    var ret = 0;
    var indexAmp = 0;
    //IF INDEX VALUE IS PROVIDED WHEN CALLING THE FUNCTION
    if (index === undefined)
        indexAmp = soloAmplifierSelected;
    else
        indexAmp = index;
    switch (discoveryList[indexAmp].model) {
        case "CP354":
            ret = 4;
            break;
        case "CP704":
            ret = 4;
            break;
        case "CP1504":
            ret = 4;
            break;
        case "CP3004":
            ret = 4;
            break;
        case "CPAF":
            ret = 1;
            break;
        case "CP0716":
            ret = 16;
            break;
        default:
            ret = 4;
            break;
    }
    return ret;
}

$.fn.checkGlobalSpeakerUploadFile = function(source) {
    // TEST CONTAIN KEYS ON JSON
    if (!source.hasOwnProperty("file_name"))
        return "file_name FIELD IS MISSING";
    if (!source.hasOwnProperty("bridge_mode_12"))
        return "bridge_mode_12 FIELD IS MISSING";
    if (!source.hasOwnProperty("bridge_mode_34"))
        return "bridge_mode_12 FIELD IS MISSING";
    if (!source.hasOwnProperty("user_settings"))
        return "user_settings FIELD IS MISSING";
    if (!source.hasOwnProperty("groups"))
        return "groups FIELD IS MISSING";
    if (!source.hasOwnProperty("speaker_presets"))
        return "speaker_presets FIELD IS MISSING";

    // USER_SETTINGS
    for (var i = 0; i < channelCount; i++) {
        if (!source.user_settings[i].hasOwnProperty("name"))
            return "user_settings[" + i + "].name FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("mute"))
            return "user_settings[" + i + "].mute FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("fault"))
            return "user_settings[" + i + "].fault FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("delay_value"))
            return "user_settings[" + i + "].delay_value FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("delay_enable"))
            return "user_settings[" + i + "].delay_enable FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("gain"))
            return "user_settings[" + i + "].gain FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("polarity"))
            return "user_settings[" + i + "].polarity FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("active_source"))
            return "user_settings[" + i + "].active_source FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("source_pri"))
            return "user_settings[" + i + "].source_pri FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("source_sec"))
            return "user_settings[" + i + "].source_sec FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("group_delay_value"))
            return "user_settings[" + i + "].group_delay_value FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("assigned_to_group"))
            return "user_settings[" + i + "].assigned_to_group FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("peq"))
            return "user_settings[" + i + "].peq FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("xover_hp_filter"))
            return "user_settings[" + i + "].xover_hp_filter FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("xover_lp_filter"))
            return "user_settings[" + i + "].xover_lp_filter FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("lim_rms"))
            return "user_settings[" + i + "].lim_rms FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("lim_peak"))
            return "user_settings[" + i + "].lim_peak FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("mixer"))
            return "user_settings[" + i + "].mixer FIELD IS MISSING";
        if (!source.user_settings[i].hasOwnProperty("preset"))
            return "user_settings[" + i + "].preset FIELD IS MISSING";

        if (!source.user_settings[i].assigned_to_group.length == groupCount)
            return "user_settings[" + i + "].assigned_to_group COUNT IS WRONG";
        if (!source.user_settings[i].peq.length == peqCount)
            return "user_settings[" + i + "].peq COUNT IS WRONG";
        if (!source.user_settings[i].xover_hp_filter.length == 4)
            return "user_settings[" + i + "].xover_hp_filter COUNT IS WRONG";
        if (!source.user_settings[i].xover_lp_filter.length == 4)
            return "user_settings[" + i + "].xover_lp_filter COUNT IS WRONG";
        if (!source.user_settings[i].lim_rms.length == 3)
            return "user_settings[" + i + "].lim_rms COUNT IS WRONG";
        if (!source.user_settings[i].lim_peak.length == 2)
            return "user_settings[" + i + "].lim_peak COUNT IS WRONG";
        if (!source.user_settings[i].mixer.length == maxMixerInput)
            return "user_settings[" + i + "].mixer COUNT IS WRONG";

        for (var j = 0; j < peqCount; j++) {
            if (!source.user_settings[i].peq[j].hasOwnProperty("enable"))
                return "user_settings[" + i + "].enable PEQ" + i + " FIELD IS MISSING";
            if (!source.user_settings[i].peq[j].hasOwnProperty("type"))
                return "user_settings[" + i + "].type PEQ" + i + " FIELD IS MISSING";
            if (!source.user_settings[i].peq[j].hasOwnProperty("freq"))
                return "user_settings[" + i + "].freq PEQ" + i + " FIELD  IS MISSING";
            if (!source.user_settings[i].peq[j].hasOwnProperty("gain"))
                return "user_settings[" + i + "].gain PEQ" + i + " FIELD  IS MISSING";
            if (!source.user_settings[i].peq[j].hasOwnProperty("q"))
                return "user_settings[" + i + "].q PEQ" + i + " FIELD IS MISSING";
        }

        if (!source.user_settings[i].xover_hp_filter.hasOwnProperty("xover_hp_enable"))
            return "user_settings[" + i + "].xover_hp_filter.xover_hp_enable FIELD IS MISSING";
        if (!source.user_settings[i].xover_hp_filter.hasOwnProperty("xover_hp_type"))
            return "user_settings[" + i + "].xover_hp_filter.xover_hp_type FIELD IS MISSING";
        if (!source.user_settings[i].xover_hp_filter.hasOwnProperty("xover_hp_freq"))
            return "user_settings[" + i + "].xover_hp_filter.xover_hp_freq FIELD IS MISSING";
        // if (!source.user_settings[i].xover_hp_filter.hasOwnProperty("xover_hp_overide"))
        //     return "user_settings[" + i + "].xover_hp_filter.xover_hp_overide FIELD IS MISSING";

        if (!source.user_settings[i].xover_lp_filter.hasOwnProperty("xover_lp_enable"))
            return "user_settings[" + i + "].xover_lp_filter.xover_lp_enable FIELD IS MISSING";
        if (!source.user_settings[i].xover_lp_filter.hasOwnProperty("xover_lp_type"))
            return "user_settings[" + i + "].xover_lp_filter.xover_lp_type FIELD IS MISSING";
        if (!source.user_settings[i].xover_lp_filter.hasOwnProperty("xover_lp_freq"))
            return "user_settings[" + i + "].xover_lp_filter.xover_lp_freq FIELD IS MISSING";
        // if (!source.user_settings[i].xover_lp_filter.hasOwnProperty("xover_lp_overide"))
        //     return "user_settings[" + i + "].xover_lp_filter.xover_lp_overide FIELD IS MISSING";

        if (!source.user_settings[i].lim_rms.hasOwnProperty("lim_rms_thres"))
            return "user_settings[" + i + "].lim_rms.lim_rms_thres FIELD IS MISSING";
        if (!source.user_settings[i].lim_rms.hasOwnProperty("lim_rms_attack"))
            return "user_settings[" + i + "].lim_rms.lim_rms_attack FIELD IS MISSING";
        if (!source.user_settings[i].lim_rms.hasOwnProperty("lim_rms_release"))
            return "user_settings[" + i + "].lim_rms.lim_rms_release FIELD IS MISSING";

        if (!source.user_settings[i].lim_peak.hasOwnProperty("lim_peak_thres"))
            return "user_settings[" + i + "].lim_peak.lim_peak_thres FIELD IS MISSING";
        if (!source.user_settings[i].lim_peak.hasOwnProperty("lim_peak_release"))
            return "user_settings[" + i + "].lim_peak.lim_peak_release FIELD IS MISSING";

        for (var j = 0; j < maxMixerInput; j++) {
            if (!source.user_settings[i].mixer[j].hasOwnProperty("gain"))
                return "user_settings[" + i + "].mixer[" + j + "].gain FIELD IS MISSING";
        }
    }

    // GROUP_SETTINGS
    for (var i = 0; i < groupCount; i++) {

        if (!source.groups[i].hasOwnProperty("name"))
            return "groups[" + i + "].name FIELD IS MISSING";
        if (!source.groups[i].hasOwnProperty("mute"))
            return "groups[" + i + "].mute FIELD IS MISSING";
        if (!source.groups[i].hasOwnProperty("delay_value"))
            return "groups[" + i + "].delay_value FIELD IS MISSING";
        if (!source.groups[i].hasOwnProperty("delay_enable"))
            return "groups[" + i + "].delay_enable FIELD IS MISSING";
        if (!source.groups[i].hasOwnProperty("gain"))
            return "groups[" + i + "].gain FIELD IS MISSING";
        if (!source.groups[i].hasOwnProperty("polarity"))
            return "groups[" + i + "].polarity FIELD IS MISSING";

        for (var j = 0; j < peqCount; j++) {
            if (!source.groups[i].peq[j].hasOwnProperty("enable"))
                return "groups[" + i + "].enable PEQ" + j + " FIELD IS MISSING";
            if (!source.groups[i].peq[j].hasOwnProperty("type"))
                return "groups[" + i + "].type PEQ" + j + " FIELD IS MISSING";
            if (!source.groups[i].peq[j].hasOwnProperty("freq"))
                return "groups[" + i + "].freq PEQ" + j + " FIELD  IS MISSING";
            if (!source.groups[i].peq[j].hasOwnProperty("gain"))
                return "groups[" + i + "].gain PEQ" + j + " FIELD  IS MISSING";
            if (!source.groups[i].peq[j].hasOwnProperty("q"))
                return "groups[" + i + "].q PEQ" + j + " FIELD IS MISSING";
        }
    }

    // SPEAKER_SETTINGS
    for (var i = 0; i < channelCount; i++) {
        if (!source.speaker_presets[i].hasOwnProperty("gain"))
            return "GAIN FIELD IS MISSING";
        if (!source.speaker_presets[i].hasOwnProperty("polarity"))
            return "POLARITY FIELD IS MISSING";

        if (!source.speaker_presets[i].hasOwnProperty("delay_enable"))
            return "DELAYENABLE FIELD IS MISSING";
        if (!source.speaker_presets[i].hasOwnProperty("delay_value"))
            return "DELAY VALUE FIELD IS MISSING";

        if (!source.speaker_presets[i].hasOwnProperty("peq"))
            return "PEQS FIELD IS MISSING";
        if (source.speaker_presets[i].peq.length != peqCount)
            return "PEQs COUNT VALUE ERROR";

        for (var j = 0; j < peqCount; j++) {
            if (!source.speaker_presets[i].peq[j].hasOwnProperty("enable"))
                return "speaker_presets[" + i + "].enable PEQ" + j + " FIELD IS MISSING";
            if (!source.speaker_presets[i].peq[j].hasOwnProperty("type"))
                return "speaker_presets[" + i + "].type PEQ" + j + " FIELD IS MISSING";
            if (!source.speaker_presets[i].peq[j].hasOwnProperty("freq"))
                return "speaker_presets[" + i + "].freq PEQ" + j + " FIELD  IS MISSING";
            if (!source.speaker_presets[i].peq[j].hasOwnProperty("gain"))
                return "speaker_presets[" + i + "].gain PEQ" + j + " FIELD  IS MISSING";
            if (!source.speaker_presets[i].peq[j].hasOwnProperty("q"))
                return "speaker_presets[" + i + "].q PEQ" + j + " FIELD IS MISSING";
        }

        if (!source.speaker_presets[i].hasOwnProperty("xover_hp_filter"))
            return "XOVER HP FILTER FIELDs IS MISSING";
        if (!source.speaker_presets[i].xover_hp_filter.hasOwnProperty("xover_hp_enable"))
            return "XOVER HP ENABLE FIELD IS MISSING";
        if (!source.speaker_presets[i].xover_hp_filter.hasOwnProperty("xover_hp_type"))
            return "XOVER HP TYPE FIELD IS MISSING";
        if (!source.speaker_presets[i].xover_hp_filter.hasOwnProperty("xover_hp_freq"))
            return "XOVER HP FREQ FIELD IS MISSING";
        if (!source.speaker_presets[i].xover_hp_filter.hasOwnProperty("xover_hp_overide"))
            return "speaker_presets[" + i + "].xover_hp_filter.xover_hp_overide FIELD IS MISSING";


        if (!source.speaker_presets[i].hasOwnProperty("xover_lp_filter"))
            return "XOVER LP FIELDs IS MISSING";
        if (!source.speaker_presets[i].xover_lp_filter.hasOwnProperty("xover_lp_enable"))
            return "XOVER LP ENABLE FIELD IS MISSING";
        if (!source.speaker_presets[i].xover_lp_filter.hasOwnProperty("xover_lp_type"))
            return "XOVER LP TYPE FIELD IS MISSING";
        if (!source.speaker_presets[i].xover_lp_filter.hasOwnProperty("xover_lp_freq"))
            return "XOVER LP FREQ FIELD IS MISSING";
        if (!source.speaker_presets[i].xover_lp_filter.hasOwnProperty("xover_lp_overide"))
            return "speaker_presets[" + i + "].xover_hp_filter.xover_lp_overide FIELD IS MISSING";

        if (!source.speaker_presets[i].hasOwnProperty("fir_table"))
            return "FIR TABLE FIELD IS MISSING";

        if (!source.speaker_presets[i].hasOwnProperty("lim_rms"))
            return "LIMITER RMS FIELDS IS MISSING";
        if (!source.speaker_presets[i].lim_rms.hasOwnProperty("lim_rms_thres"))
            return "LIMITER RMS THRES FIELD IS MISSING";
        if (!source.speaker_presets[i].lim_rms.hasOwnProperty("lim_rms_attack"))
            return "LIMITER RMS ATTACK FIELD IS MISSING";
        if (!source.speaker_presets[i].lim_rms.hasOwnProperty("lim_rms_release"))
            return "LIMITER RMS RELEASE FIELD IS MISSING";

        if (!source.speaker_presets[i].hasOwnProperty("lim_peak"))
            return "LIMITER FIELDS IS MISSING";
        if (!source.speaker_presets[i].lim_peak.hasOwnProperty("lim_peak_thres"))
            return "LIMITER PEAK THRES FIELD IS MISSING";
        if (!source.speaker_presets[i].lim_peak.hasOwnProperty("lim_peak_release"))
            return "LIMITER PEAK RELEASE FIELD IS MISSING";
    }

    return 0;
}


function toDateTime(input) {
    var x = new Date();
    var time = input - ((x.getTimezoneOffset() + 60) * 60);
    var epoch = new Date(0);
    epoch.setSeconds(parseInt(time));
    var date = epoch.toISOString();
    date = date.replace('T', ' ');
    var x = new Date();
    return date.split('.')[0].split(' ')[0] + ' ' + epoch.toLocaleTimeString();
}

$.fn.setVisualBridge = function() {

    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge12) {
        $("#bridge12Button").addClass("active");
        $("#overviewBG1").hide();
        $("#itemQuarter1").hide();
        $("#itemQuarterDelay1").hide();
        $("#stereo12").hide();
        $("#stereo34").css("margin-left", "54px");
        $("#overviewBG0 .overviewButtonChannelNumber").html("A - B");
        $("#overviewBG0 .overviewButtonChannelNumber16").html("A - B");
        $(".bridgeWiring12").html("<span class=\"pos\">OUT+ = A+ </span> || <span class=\"neg\">OUT- = B+ </span> ");
    } else {
        $("#bridge12Button").removeClass("active");
        $("#overviewBG1").show();
        $("#itemQuarter1").show();
        $("#itemQuarterDelay1").show();
        $("#stereo12").show();
        $("#stereo34").css("margin-left", "124px");
        if (this.getModel() == 9)
            $("#overviewBG0 .overviewButtonChannelNumber").html(labelOverviewChannel3ch[0]);
        else
            $("#overviewBG0 .overviewButtonChannelNumber").html("A");
        $("#overviewBG0 .overviewButtonChannelNumber16").html("A");
        $(".bridgeWiring12").html("Channels (+) (-)");
    }
    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge34) {
        $("#bridge34Button").addClass("active");
        $("#overviewBG3").hide();
        $("#itemQuarter3").hide();
        $("#itemQuarterDelay3").hide();
        $("#stereo34").hide();
        $("#stereo12").css("margin-left", "-87px");
        $("#overviewBG2 .overviewButtonChannelNumber").html("C - D");
        $("#overviewBG2 .overviewButtonChannelNumber16").html("C - D");
        $(".bridgeWiring34").html("<span class=\"pos\">OUT+ = C+ </span> || <span class=\"neg\">OUT- = D+ </span> ");
    } else {
        $("#bridge34Button").removeClass("active");
        $("#overviewBG3").show();
        $("#itemQuarter3").show();
        $("#itemQuarterDelay3").show();
        $("#stereo34").show();
        $("#stereo12").css("margin-left", "-157px");
        if (this.getModel() == 9)
            $("#overviewBG2 .overviewButtonChannelNumber").html(labelOverviewChannel3ch[2]);
        else
            $("#overviewBG2 .overviewButtonChannelNumber").html("C");
        $("#overviewBG2 .overviewButtonChannelNumber16").html("C");
        $(".bridgeWiring34").html("Channels (+) (-)");
    }

    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge56) {
        $("#bridge56Button").addClass("active");
        $("#overviewBG5").hide();
        $("#itemQuarter5").hide();
        $("#itemQuarterDelay5").hide();
        $("#overviewBG4 .overviewButtonChannelNumber16").html("E - F");
        $(".bridgeWiring56").html("<span class=\"pos\">OUT+ = E+ </span> || <span class=\"neg\">OUT- = F+ </span> ");
    } else {
        $("#bridge56Button").removeClass("active");
        $("#overviewBG5").show();
        $("#itemQuarter5").show();
        $("#itemQuarterDelay5").show();
        $("#overviewBG4 .overviewButtonChannelNumber16").html("E");
        $(".bridgeWiring56").html("Channels (+) (-)");
    }
    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge78) {
        $("#bridge78Button").addClass("active");
        $("#overviewBG7").hide();
        $("#itemQuarter7").hide();
        $("#itemQuarterDelay7").hide();
        $("#overviewBG6 .overviewButtonChannelNumber16").html("G - H");
        $(".bridgeWiring78").html("<span class=\"pos\">OUT+ = G+ </span> || <span class=\"neg\">OUT- = H+ </span> ");
    } else {
        $("#bridge78Button").removeClass("active");
        $("#overviewBG7").show();
        $("#itemQuarter7").show();
        $("#itemQuarterDelay7").show();
        $("#overviewBG6 .overviewButtonChannelNumber16").html("G");
        $(".bridgeWiring78").html("Channels (+) (-)");
    }

    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge910) {
        $("#bridge910Button").addClass("active");
        $("#overviewBG9").hide();
        $("#itemQuarter9").hide();
        $("#itemQuarterDelay9").hide();
        $("#overviewBG8 .overviewButtonChannelNumber16").html("I - J");
        $(".bridgeWiring910").html("<span class=\"pos\">OUT+ = I+ </span> || <span class=\"neg\">OUT- = J+ </span> ");
    } else {
        $("#bridge910Button").removeClass("active");
        $("#overviewBG9").show();
        $("#itemQuarter9").show();
        $("#itemQuarterDelay9").show();
        $("#overviewBG8 .overviewButtonChannelNumber16").html("I");
        $(".bridgeWiring910").html("Channels (+) (-)");
    }
    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1112) {
        $("#bridge1112Button").addClass("active");
        $("#overviewBG11").hide();
        $("#itemQuarter11").hide();
        $("#itemQuarterDelay11").hide();
        $("#overviewBG10 .overviewButtonChannelNumber16").html("K - L");
        $(".bridgeWiring1112").html("<span class=\"pos\">OUT+ = K+ </span> || <span class=\"neg\">OUT- = L+ </span> ");
    } else {
        $("#bridge1112Button").removeClass("active");
        $("#overviewBG11").show();
        $("#itemQuarter11").show();
        $("#itemQuarterDelay11").show();
        $("#overviewBG10 .overviewButtonChannelNumber16").html("K");
        $(".bridgeWiring112").html("Channels (+) (-)");
    }

    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1314) {
        $("#bridge1314Button").addClass("active");
        $("#overviewBG13").hide();
        $("#itemQuarter13").hide();
        $("#itemQuarterDelay13").hide();
        $("#overviewBG12 .overviewButtonChannelNumber16").html("M - N");
        $(".bridgeWiring1314").html("<span class=\"pos\">OUT+ = M+ </span> || <span class=\"neg\">OUT- = N+ </span> ");
    } else {
        $("#bridge1314Button").removeClass("active");
        $("#overviewBG13").show();
        $("#itemQuarter13").show();
        $("#itemQuarterDelay13").show();
        $("#overviewBG12 .overviewButtonChannelNumber16").html("M");
        $(".bridgeWiring1314").html("Channels (+) (-)");
    }
    if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1516) {
        $("#bridge1516Button").addClass("active");
        $("#overviewBG15").hide();
        $("#itemQuarter15").hide();
        $("#itemQuarterDelay15").hide();
        $("#overviewBG14 .overviewButtonChannelNumber16").html("O - P");
        $(".bridgeWiring1516").html("<span class=\"pos\">OUT+ = O+ </span> || <span class=\"neg\">OUT- = P+ </span> ");
    } else {
        $("#bridge1516Button").removeClass("active");
        $("#overviewBG15").show();
        $("#itemQuarter15").show();
        $("#itemQuarterDelay15").show();
        $("#overviewBG14 .overviewButtonChannelNumber16").html("O");
        $(".bridgeWiring1516").html("Channels (+) (-)");
    }
}

$.fn.setVisualAmpStagePower = function() {
    if (arrayAmplifier[soloAmplifierSelected].amp_stage_disabled) {
        $("#powerStageButton").addClass("active");
        $("#powerStageButton").html("OFF");
    } else {
        $("#powerStageButton").removeClass("active");
        $("#powerStageButton").html("ON");
    }
}

$.fn.getLowestValue = function(arr) {
    var ret = 0;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] < ret)
            ret = arr[i];
    }
    // console.log("lowest value:" + ret)
    return ret;
}

$.fn.dataLoaded = function() {
    if (!refreshDataEnable) {
        setTimeout(function() {
            $("#mainLoader").removeClass("is-active");
        }, mainWaitingTime);
        $.fn.refreshData();
    }
}

$.fn.setStreamSource = function(selectedChannel, selectedSource, selectedRedundancy) {
    if (selectedRedundancy === "P") {
        // var labelId = "#overviewSourceLabel" + selectedChannel;
        // $(labelId).html(sourceOverviewLabel[selectedSource]);
        arrayAmplifier[soloAmplifierSelected].channel[selectedChannel].source.primary = Number(selectedSource);
        $.fn.setDataSoloSource(selectedChannel, 0);
        //ADD ACTIVE CLASS STYLE TO THE SELECTED INPUT
        var dest = "#source" + selectedChannel + "nav" + selectedSource + selectedRedundancy;
        $(dest).addClass("active");
    }
}

$.fn.loadSettings = function() {

    // Device Config : Display resets buttons ?
    if ($.fn.getPlateAmp()) {
        $("#resetArea").hide();
    } else {
        $("#resetArea").show();
    }

    $("#aboutModelValue").html(arrayAmplifier[soloAmplifierSelected].model);
    $("#aboutHardwareVersionValue").html(arrayAmplifier[soloAmplifierSelected].hardwareVersion);
    $("#aboutSerialValue").html(arrayAmplifier[soloAmplifierSelected].serial);
    $("#aboutMacValue").html(discoveryList[soloAmplifierSelected].hw_addr);
    $("#aboutWebVersionValue").html(softwareVersion);


    $("#lanIpInput").val(arrayAmplifier[soloAmplifierSelected].network.lan.ip);

    $("#lanMaskInput").val(arrayAmplifier[soloAmplifierSelected].network.lan.mask);

    $("#lanGatewayInput").val(arrayAmplifier[soloAmplifierSelected].network.lan.gw);

    if (arrayAmplifier[soloAmplifierSelected].network.lan.dhcp) {
        $("#lanDhcpEnable").prop("checked", true);
        $("#lanDhcpEnable").attr("value", true);
    } else {
        $("#lanDhcpEnable").prop("checked", false);
        $("#lanDhcpEnable").attr("value", false);
    }

    // WLAN CONFIG
    $("#hotspotSsidInput").val(arrayAmplifier[soloAmplifierSelected].network.wlan.ssid);
    $("#hotspotPasswordInput").val(arrayAmplifier[soloAmplifierSelected].network.wlan.password);
    $("#hotspotEnableInput").prop("checked", arrayAmplifier[soloAmplifierSelected].network.wlan.enable);
    $("#hotspotEnableInput").attr("value", arrayAmplifier[soloAmplifierSelected].network.wlan.enable);

    $("#cloudNameInput").val(arrayAmplifier[soloAmplifierSelected].cloud.device_name);

    $("#cloudLoginInput").val(arrayAmplifier[soloAmplifierSelected].cloud.username);

    $("#cloudPasswordInput").val(arrayAmplifier[soloAmplifierSelected].cloud.password);

    $("#cloudEnableInput").prop("checked", arrayAmplifier[soloAmplifierSelected].cloud.enable);
    $("#cloudEnableInput").attr("value", arrayAmplifier[soloAmplifierSelected].cloud.enable);

    $("#spotifyNameInput").val(arrayAmplifier[soloAmplifierSelected].streaming.spotify.device_name);

    $("#spotifyEmailInput").val(arrayAmplifier[soloAmplifierSelected].streaming.spotify.email);

    $("#spotifyPasswordInput").val(arrayAmplifier[soloAmplifierSelected].streaming.spotify.password);

    $("#spotifyEnableInput").prop("checked", arrayAmplifier[soloAmplifierSelected].streaming.spotify.enable);
    $("#spotifyEnableInput").attr("value", arrayAmplifier[soloAmplifierSelected].streaming.spotify.enable);

    $("#airplayNameInput").val(arrayAmplifier[soloAmplifierSelected].streaming.airplay.device_name);

    $("#airplayPasswordInput").val(arrayAmplifier[soloAmplifierSelected].streaming.airplay.password);

    $("#airplayEnableInput").prop("checked", arrayAmplifier[soloAmplifierSelected].streaming.airplay.enable);
    $("#airplayEnableInput").attr("value", arrayAmplifier[soloAmplifierSelected].streaming.airplay.enable);

    $("#amplifierDescription").val(arrayAmplifier[soloAmplifierSelected].label);

    $.fn.setDataSoloOutputUpdate();
    $.fn.setDataSoloStatusPanel();

    if (arrayAmplifier[soloAmplifierSelected].front_lock) {
        $("#frontPanelLockEnable").attr('value', true);
    } else {
        $("#frontPanelLockEnable").attr('value', false);
    }
}

// REFRESH DATA TO SIMULATE CONNECTION WITH REAL AMPLIFIER
$.fn.refreshData = function() {
    let temp_request = new commandConstructor();
    let message = new Object();

    //SET COMMAND OBJECT PARAMETERS
    temp_request.command = cmd_get_readback;
    temp_request.query_arg1 = 0;
    temp_request.query_arg2 = "null";
    temp_request.query_arg3 = "null";
    temp_request.query_arg4 = "null";

    let send_text = commandToJSON(temp_request);

    message.command = cmd_get_readback;
    message.data = send_text;
    //SEND COMMAND

    for (var i = 0; i < discoveryList.length; i++) {
        if (discoveryWorker[i]) {
            // TO UNCOMMENT
            if (discoveryWorker[i].worker)
                discoveryWorker[i].worker.postMessage(message);
        }
    }
    $.fn.drawRefreshedData();

    //TO UNCOMMENT
    setTimeout($.fn.refreshData, readbackRefresh);
}

$.fn.drawRefreshedDataDiscover = function() {
    //FOR EACH AMPLIFIER IN DISCOVERY LIST
    for (var j = 0; j < discoveryList.length; j++) {
        if (arrayAmplifier[j]) {
            let id4 = "#dldtds" + j;
            let id6 = "#dldcds" + j;
            let desc = $(id4).html()
            let ip = $(id6).html()
            if (desc != discoveryList[j].desc && j > 1)
                $(id4).prop("innerHTML", discoveryList[j].desc);
            if (ip != arrayAmplifier[j].network.lan.ip && j > 1)
                $(id6).prop("innerHTML", arrayAmplifier[j].network.lan.ip);
            // for (var i = 0; i < 4; i++) {

            // for (var i = 0; i < $.fn.getChannelCount(j); i++) {
            for (var i = 0; i < channel16Count; i++) {
                let miniHeight = 0;
                var minId = "#dlri" + i + "a" + j;
                if (readBackDiscovery[j]) {
                    if (parseFloat(readBackDiscovery[j][i]) > -60) {
                        miniHeight = (parseFloat(readBackDiscovery[j][i]) + 60) / 60;
                    } else
                        miniHeight = 0;
                } else
                    miniHeight = 0;
                $(minId).css("transform", 'scaleY(' + -miniHeight + ')');
                //check if limiter is reducing the output level, and change the vu meter in red 
                if (readBackLimiter[j][i][5] < 0)
                    $(minId).css("background-color", '#FF0000');
                else
                    $(minId).css("background-color", '#00FF00');
            }

            // AMPLIFIER STATUS UPDATE
            if (soloAmplifierSelected == j) {
                var moduleCount = 1
                if ($.fn.getModel() == 3)
                    moduleCount = 2;
                else if ($.fn.getModel() == 4 || $.fn.getModel() == 7 || $.fn.getModel() == 8)
                    moduleCount = 4;

                for (i = 0; i < moduleCount; i++) {
                    let idTempSpan = "tempModule" + (i + 1);
                    let idStageSpan = "stageModule" + (i + 1);
                    let idOvpSpan = "ovpModule" + (i + 1);
                    let idVoltageSpan = "inputVoltageModule" + (i + 1);

                    // TEMPERATURE
                    let modTempContent = readBackStatus[soloAmplifierSelected][i][0] + "°C";

                    if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempGood) {
                        $("#" + idTempSpan).removeClass("badge-warning");
                        $("#" + idTempSpan).removeClass("badge-danger");
                        $("#" + idTempSpan).addClass("badge-success");
                        $("#" + idTempSpan).html(modTempContent);
                    } else if (readBackStatus[soloAmplifierSelected][i][0] >= moduleTempGood && readBackStatus[soloAmplifierSelected][i][0] < moduleTempWarning) {
                        $("#" + idTempSpan).removeClass("badge-success");
                        $("#" + idTempSpan).removeClass("badge-danger");
                        $("#" + idTempSpan).addClass("badge-warning");
                        $("#" + idTempSpan).html(modTempContent);
                    } else if (readBackStatus[soloAmplifierSelected][i][0] >= moduleTempWarning) {
                        $("#" + idTempSpan).removeClass("badge-warning");
                        $("#" + idTempSpan).removeClass("badge-success");
                        $("#" + idTempSpan).addClass("badge-danger");
                        $("#" + idTempSpan).html(modTempContent);
                    }

                    // ACTIVE (AMPLIFIER ON)
                    if (readBackStatus[soloAmplifierSelected][i][1] == 0) {
                        $("#" + idStageSpan).removeClass("badge-success");
                        $("#" + idStageSpan).addClass("badge-light");
                        $("#" + idStageSpan).html("OFF");
                        // IF OVER TEMP PROTECTION IS OFF MEANS MODULE POWER SUPPLY IS OFF
                        if (readBackStatus[soloAmplifierSelected][i][2] == 0) {

                            if (moduleCount == 1) {
                                $('.backgroundSource').css("background-color", "#999999");
                            } else if (moduleCount == 2) {
                                if (i == 0) {
                                    $('.backgroundSource:eq(0)').css("background-color", "#999999");
                                    $('.backgroundSource:eq(1)').css("background-color", "#999999");
                                } else if (i == 1) {
                                    $('.backgroundSource:eq(2)').css("background-color", "#999999");
                                    $('.backgroundSource:eq(3)').css("background-color", "#999999");
                                }
                            } else if (moduleCount == 4) {
                                if (i == 0) {
                                    //AMP MODULE 1 OTP
                                    $('.backgroundSource16:eq(0)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(1)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(2)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(3)').css("background-color", "#999999");
                                    $('.backgroundSource:eq(0)').css("background-color", "#999999");
                                } else if (i == 1) {
                                    //AMP MODULE 2 OTP
                                    $('.backgroundSource16:eq(4)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(5)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(6)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(7)').css("background-color", "#999999");
                                    $('.backgroundSource:eq(1)').css("background-color", "#999999");
                                } else if (i == 2) {
                                    //AMP MODULE 3 OTP
                                    $('.backgroundSource16:eq(8)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(9)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(10)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(11)').css("background-color", "#999999");
                                    $('.backgroundSource:eq(2)').css("background-color", "#999999");
                                } else if (i == 3) {
                                    //AMP MODULE 4 OTP
                                    $('.backgroundSource16:eq(12)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(13)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(14)').css("background-color", "#999999");
                                    $('.backgroundSource16:eq(15)').css("background-color", "#999999");
                                    $('.backgroundSource:eq(3)').css("background-color", "#999999");
                                }
                            }
                        }
                    } else {
                        $("#" + idStageSpan).removeClass("badge-light");
                        $("#" + idStageSpan).addClass("badge-success");
                        $("#" + idStageSpan).html("ON");
                        // IF OVER TEMP PROTECTION IS OFF MEANS MODULE POWER SUPPLY IS ON
                        if (readBackStatus[soloAmplifierSelected][i][2] == 0) {

                            if (moduleCount == 1) {
                                $('.backgroundSource').css("background-color", "#4b4b55");
                            } else if (moduleCount == 2) {
                                if (i == 0) {
                                    $('.backgroundSource:eq(0)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(1)').css("background-color", "#4b4b55");
                                } else if (i == 1) {
                                    $('.backgroundSource:eq(2)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(3)').css("background-color", "#4b4b55");
                                }
                            } else if (moduleCount == 4) {
                                if (i == 0) {
                                    //AMP MODULE 1 OTP
                                    $('.backgroundSource16:eq(0)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(1)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(2)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(3)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(0)').css("background-color", "#4b4b55");
                                } else if (i == 1) {
                                    //AMP MODULE 2 OTP
                                    $('.backgroundSource16:eq(4)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(5)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(6)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(7)').css("background-color", "#6b6976");
                                    $('.backgroundSource:eq(1)').css("background-color", "#4b4b55");
                                } else if (i == 2) {
                                    //AMP MODULE 3 OTP
                                    $('.backgroundSource16:eq(8)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(9)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(10)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(11)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(2)').css("background-color", "#4b4b55");
                                } else if (i == 3) {
                                    //AMP MODULE 4 OTP
                                    $('.backgroundSource16:eq(12)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(13)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(14)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(15)').css("background-color", "#6b6976");
                                    $('.backgroundSource:eq(3)').css("background-color", "#4b4b55");
                                }
                            }
                        }
                    }

                    // OVER TEMPERATURE PROTECTION
                    if (readBackStatus[soloAmplifierSelected][i][2] == 0) {
                        $("#" + idOvpSpan).removeClass("badge-danger");
                        $("#" + idOvpSpan).addClass("badge-success");
                        $("#" + idOvpSpan).html("OK");
                        if (readBackStatus[soloAmplifierSelected][i][1] == 1) {

                            if (moduleCount == 1) {
                                $('.backgroundSource').css("background-color", "#4b4b55");
                            } else if (moduleCount == 2) {
                                if (i == 0) {
                                    $('.backgroundSource:eq(0)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(1)').css("background-color", "#4b4b55");
                                } else if (i == 1) {
                                    $('.backgroundSource:eq(2)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(3)').css("background-color", "#4b4b55");
                                }
                            } else if (moduleCount == 4) {
                                if (i == 0) {
                                    //AMP MODULE 1 OTP
                                    $('.backgroundSource16:eq(0)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(1)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(2)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(3)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(0)').css("background-color", "#4b4b55");
                                } else if (i == 1) {
                                    //AMP MODULE 2 OTP
                                    $('.backgroundSource16:eq(4)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(5)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(6)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(7)').css("background-color", "#6b6976");
                                    $('.backgroundSource:eq(1)').css("background-color", "#4b4b55");
                                } else if (i == 2) {
                                    //AMP MODULE 3 OTP
                                    $('.backgroundSource16:eq(8)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(9)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(10)').css("background-color", "#4b4b55");
                                    $('.backgroundSource16:eq(11)').css("background-color", "#4b4b55");
                                    $('.backgroundSource:eq(2)').css("background-color", "#4b4b55");
                                } else if (i == 3) {
                                    //AMP MODULE 4 OTP
                                    $('.backgroundSource16:eq(12)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(13)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(14)').css("background-color", "#6b6976");
                                    $('.backgroundSource16:eq(15)').css("background-color", "#6b6976");
                                    $('.backgroundSource:eq(3)').css("background-color", "#4b4b55");
                                }
                            }
                        }
                    } else if (readBackStatus[soloAmplifierSelected][i][2] == 1) {
                        $("#" + idOvpSpan).removeClass("badge-success");
                        $("#" + idOvpSpan).addClass("badge-danger");
                        $("#" + idOvpSpan).html("OTP");

                        if (moduleCount == 1) {
                            $('.backgroundSource').css("background-color", "#ff0000");
                        } else if (moduleCount == 2) {
                            if (i == 0) {
                                $('.backgroundSource:eq(0)').css("background-color", "#ff0000");
                                $('.backgroundSource:eq(1)').css("background-color", "#ff0000");
                            } else if (i == 1) {
                                $('.backgroundSource:eq(2)').css("background-color", "#ff0000");
                                $('.backgroundSource:eq(3)').css("background-color", "#ff0000");
                            }
                        } else if (moduleCount == 4) {
                            if (i == 0) {
                                //AMP MODULE 1 OTP
                                $('.backgroundSource16:eq(0)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(1)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(2)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(3)').css("background-color", "#ff0000");
                            } else if (i == 1) {
                                //AMP MODULE 2 OTP
                                $('.backgroundSource16:eq(4)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(5)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(6)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(7)').css("background-color", "#ff0000");
                            } else if (i == 2) {
                                //AMP MODULE 3 OTP
                                $('.backgroundSource16:eq(8)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(9)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(10)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(11)').css("background-color", "#ff0000");
                            } else if (i == 3) {
                                //AMP MODULE 4 OTP
                                $('.backgroundSource16:eq(12)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(13)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(14)').css("background-color", "#ff0000");
                                $('.backgroundSource16:eq(15)').css("background-color", "#ff0000");
                            }
                        }
                    }

                    //VOLTAGE
                    if (readBackStatus[soloAmplifierSelected][i][3] == outOfRangeVoltageValue) {
                        $("#" + idVoltageSpan).html("Out of range");
                        $("#" + idVoltageSpan).removeClass("badge-success")
                        $("#" + idVoltageSpan).addClass("badge-danger")
                    } else {
                        $("#" + idVoltageSpan).html(readBackStatus[soloAmplifierSelected][i][3] + "V");
                        $("#" + idVoltageSpan).removeClass("badge-danger")
                        $("#" + idVoltageSpan).addClass("badge-success")
                    }
                }
            }
        }
    }
}

$.fn.drawRefreshedData = function() {
    //DRAW MINI VU METER DISCOVERY
    $.fn.drawRefreshedDataDiscover();

    if (demoMode === 1) {
        for (var i = 0; i < channel16Count; i++) {
            readBackSolo[i] = (Math.floor(Math.random() * 60)) - 60;
        }
    }

    for (var i = 0; i < channel16Count; i++) {

        var classOverviewIn = "#overviewVuMeterInput" + i;
        var classOverviewComp = "#overviewCompMeterInput" + i;
        var classGainSolo = "#gainSoloVuMeterCh" + i;

        var miniHeight = 0;
        var tempHeight = 0;
        var gainHeight = 0;
        var limOverviewHeight = 0;

        // if (parseFloat(readBackSolo[i]) > -60 ) {
        miniHeight = (parseFloat(readBackDiscovery[0][i]) + 60) / 60;
        tempHeight = (parseFloat(readBackDiscovery[0][i]) + 60) / 60;
        gainHeight = (parseFloat(readBackDiscovery[0][i]) + 60) / 60;
        if (soloAmplifierSelected != 0) {
            // miniHeight = (parseFloat(readBackSolo[i]) + 60) / 60;
            tempHeight = (parseFloat(readBackDiscovery[soloAmplifierSelected][i]) + 60) / 60;
            gainHeight = (parseFloat(readBackDiscovery[soloAmplifierSelected][i]) + 60) / 60;
        }
        // }
        let l0 = l1 = l2 = l3 = l4 = 0;
        //USER LIMITER RMS
        if (parseFloat(readBackLimiter[soloAmplifierSelected][i][0]) != -60.0 && !isNaN(readBackLimiter[soloAmplifierSelected][i][0]))
            l0 = parseFloat(readBackLimiter[soloAmplifierSelected][i][0])
            //USER LIMITER PEAK
        if (parseFloat(readBackLimiter[soloAmplifierSelected][i][1]) != -60.0 && !isNaN(readBackLimiter[soloAmplifierSelected][i][1]))
            l1 = parseFloat(readBackLimiter[soloAmplifierSelected][i][1])
            //SPEAKER LIMITER RMS
        if (parseFloat(readBackLimiter[soloAmplifierSelected][i][2]) != -60.0 && !isNaN(readBackLimiter[soloAmplifierSelected][i][2]))
            l2 = parseFloat(readBackLimiter[soloAmplifierSelected][i][2])
            //SPEAKER LIMITER PEAK
        if (parseFloat(readBackLimiter[soloAmplifierSelected][i][3]) != -60.0 && !isNaN(readBackLimiter[soloAmplifierSelected][i][3]))
            l3 = parseFloat(readBackLimiter[soloAmplifierSelected][i][3])
            //AMPLIFIER LIMITER
        if (parseFloat(readBackLimiter[soloAmplifierSelected][i][4]) != -60.0 && !isNaN(readBackLimiter[soloAmplifierSelected][i][4]))
            l4 = parseFloat(readBackLimiter[soloAmplifierSelected][i][4])
        let usrSum = l0 + l1 + l2 + l3 + l4;
        if (usrSum < -60)
            usrSum = -60;

        limOverviewHeight = Math.abs(usrSum) / 60;

        var minId = "#dlri" + i + "a" + "0";
        $(minId).css("transform", 'scaleY(' + -miniHeight + ')');
        $(classOverviewIn).css("transform", 'scaleY(' + -tempHeight + ')');
        if (limOverviewHeight > 0)
            $(classOverviewComp).css("transform", 'scaleY(' + limOverviewHeight + ')');
        else
            $(classOverviewComp).css("transform", 'scaleY(0)');
        $(classGainSolo).css("transform", 'scaleY(' + -gainHeight + ')');
    }

    var classGRLimiterSolo = "#vuMeterGRBGLimiterCh";
    var classPeakLimiterSolo = "#vuMeterPeakBGLimiterCh";
    var classLimiterSolo = "#vuMeterOutputBGLimiterCh";

    var limHeight = 0;
    var peakHeight = 0;
    var outputHeight = 0;

    if (parseFloat(readBackDiscovery[soloAmplifierSelected][soloChannelSelected]) > -60) {
        limHeight = Math.abs(parseFloat(readBackLimiter[soloAmplifierSelected][soloChannelSelected][0])) / 60;

        peakHeight = Math.abs(parseFloat(readBackLimiter[soloAmplifierSelected][soloChannelSelected][1])) / 60;

        outputHeight = (parseFloat(readBackDiscovery[soloAmplifierSelected][soloChannelSelected]) + 60) / 60;

        $(classGRLimiterSolo).css("transform", 'scaleY(' + limHeight + ')');

        $(classPeakLimiterSolo).css("transform", 'scaleY(' + peakHeight + ')');

        $(classLimiterSolo).css("transform", 'scaleY(' + -outputHeight + ')');
    } else {
        $(classGRLimiterSolo).css("transform", 'scaleY(0)');

        $(classPeakLimiterSolo).css("transform", 'scaleY(0)');

        $(classLimiterSolo).css("transform", 'scaleY(0)');
    }
}

$.fn.displayTime = function() {
    let dt = new Date();
    let time = "";
    let second_text = "";
    let minute_text = "";
    if (dt.getSeconds() < 10)
        second_text = "0" + dt.getSeconds();
    else
        second_text = dt.getSeconds();

    if (dt.getMinutes() < 10)
        minute_text = "0" + dt.getMinutes();
    else
        minute_text = dt.getMinutes();

    time = dt.getHours() + ":" + minute_text + ":" + second_text;
    $("#localTimeValue").text(time);

    setTimeout($.fn.displayTime, timeRefresh);
}

//INIT ARRAY AND DATA AT THE LOADING OF THE PAGE
$.fn.initData = function() {
    //IF NO DEMO MODE ENABLE
    if (demoMode === 0) {

        //CREATE AT LEAST ONE AMPLIFIER WHICH IS LOCAL
        arrayAmplifier = new Array(1);
        for (var i = 0; i < 1; i++) {
            arrayAmplifier[i] = new amplifierConstructor();
        }
        arrayAmplifier[0].local = 1;

        //CREATE 6 GROUPS
        arrayGroup = new Array(groupCount);
        for (var i = 0; i < groupCount; i++) {
            arrayGroup[i] = new groupConstructor();
        }

        //ARRAY GROUP DATA
        arrayGroupData = new Array(1);
        arrayGroupData[0] = new Array(groupCount);
        for (var i = 0; i < groupCount; i++) {
            arrayGroupData[0][i] = new groupConstructor();
        }

        arrayEqParam = Array.from(arrayAmplifier[0].channel[0].peq.peq);
        //GROUP LABEL SETUP
        for (var g = 0; g < groupCount; g++) {
            var dest1 = "#labelGroupButton" + g;
            $(dest1).html(arrayGroup[g].label.substring(0, groupButtonLabelMaxLength));
            var dest2 = "#groupName" + g;
            $(dest2).val(arrayGroup[g].label);
        }

        $("#gainPanelGroupName").html(arrayGroup[0].label);
        $("#delayPanelGroupName").html(arrayGroup[0].label);
    } else {
        //CREATE AT LEAST ONE AMPLIFIER WHICH IS LOCAL
        arrayAmplifier = new Array(arrayAmpSizeDemo);
        for (var i = 0; i < arrayAmpSizeDemo; i++) {
            arrayAmplifier[i] = new amplifierConstructor();
        }
        arrayAmplifier[0].local = 1;

        //CREATE 6 GROUPS
        arrayGroup = new Array(groupCount);
        for (var i = 0; i < groupCount; i++) {
            arrayGroup[i] = new groupConstructor();
        }
        //ARRAY GROUP DATA
        arrayGroupData = new Array(1);
        arrayGroupData[0] = new Array(groupCount);
        for (var i = 0; i < groupCount; i++) {
            arrayGroupData[0][i] = new groupConstructor();
        }

        arrayEqParam = Array.from(arrayAmplifier[0].channel[0].peq.peq);

        //GROUP LABEL SETUP
        for (var g = 0; g < groupCount; g++) {
            var dest1 = "#labelGroupButton" + g;
            $(dest1).html(arrayGroup[g].label.substring(0, groupButtonLabelMaxLength));
            var dest2 = "#groupName" + g;
            $(dest2).val(arrayGroup[g].label);
        }

        $("#gainPanelGroupName").html(arrayGroup[0].label);
        $("#delayPanelGroupName").html(arrayGroup[0].label);

        $.fn.setupSpeakerSolo();
    }
}

$.fn.loadDataFromAmp = function() {
    var str = "[ \"channels\", \"groups\", \"settings\"]";
    $.fn.sendCommandWS("subscribe", "null", "null", "null", str);

    let arCmd = new Array();
    // arCmd.push($.fn.getCommandFromArgs(cmd_get_speaker_preset_folder_names, soloAmplifierSelected, "null", "null", "null")); 
    if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        arCmd.push($.fn.getCommandFromArgs(cmd_get_all_speaker_preset_list_names, soloAmplifierSelected, "null", "null", "null"));
    } else {
        arCmd.push($.fn.getCommandFromArgs(cmd_get_speaker_preset_list_names, soloAmplifierSelected, "null", "null", "null"));
    }
    arCmd.push($.fn.getCommandFromArgs(cmd_get_about, soloAmplifierSelected, "null", "null", "null"));
    $.fn.sendCommandsWS(arCmd);
}

$.fn.loadData = function() {
    if (displaySoloGroup === 0) {
        //CHANNEL VIEW : GET THE SELECTED CHANNEL AND LOAD DATE

        //UPDATE OVERVIEW PRESET LABEL
        $.fn.updateOverviewPresetLabel();

        //MIXER SETUP
        if ($("#sourceMainPanel").is(":visible"))
            $("#overviewButtonMenuSource").trigger("click");

        //GAIN SETUP
        if ($("#gainMainPanel").is(":visible"))
            $("#overviewButtonMenuGain").trigger("click");

        //DELAY SETUP
        if ($("#delayMainPanel").is(":visible"))
            $("#overviewButtonMenuDelay").trigger("click");

        //PEQ SETUP
        if ($("#peqMainPanel").is(":visible"))
            $("#overviewButtonMenuPeq").trigger("click");

        //XOVER SETUP
        if ($("#xoverMainPanel").is(":visible"))
            $("#overviewButtonMenuXover").trigger("click");

        //LIMITER SETUP
        if ($("#limiterMainPanel").is(":visible"))
            $("#overviewButtonMenuLimiter").trigger("click");

        //SPEAKER SETUP
        if ($("#speakerMainPanel").is(":visible"))
            $.fn.setDataSoloSpeaker(100);
    }
}

//UPDATE PRESET NAME ON OVERVIEW AREA
$.fn.updateOverviewPresetLabel = function() {
    str = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].preset;
    $("#overviewBackgroungSpeakerPresetLoaded").prop("innerHTML", str.slice(str.indexOf('/') + 1));
}

//DISCOVERY LIST SETUP
$.fn.setDiscoverySource = function() {
    var nameListDiscovery = new Array();

    //SYNCHRONIZE WITH THE WEBUI LOCAL ARRAY
    if (discoveryList.length > 1) {
        for (var i = 0; i < discoveryList.length; i++) {
            //CREATE NEW AMPLIFIER ON THE LIST FOR DISCOVERED DEVICES
            if (i > 0 && demoMode === 0 && arrayAmplifier.length != discoveryList.length)
                arrayAmplifier[i] = new amplifierConstructor();
            var tempArrayGroup = new Array(groupCount)
            for (var g = 0; g < groupCount; g++) {
                tempArrayGroup[g] = new groupConstructor();
            }
            arrayGroupData[i] = (tempArrayGroup);
            //UPDATE DISCOVERY FIELD FROM DISCOVERY LIST
            arrayAmplifier[i].discovery = discoveryList[i];
            if (demoMode === 1)
                arrayAmplifier[i].label = discoveryList[i].desc;
        }
    }

    //SETUP THE LOCAL DEVICE INFORMATION ON DISCOVERY LIST
    let label = $("#dldtds0").html()
    let ip = $("#dldcds0").html()
    if (label != arrayAmplifier[0].label)
        $("#dldtds0").prop("innerHTML", arrayAmplifier[0].label);
    if (ip != arrayAmplifier[0].network.lan.ip)
        $("#dldcds0").prop("innerHTML", arrayAmplifier[0].network.lan.ip);


    for (var i = 1; i < discoveryList.length; i++) {
        nameListDiscovery.push(discoveryList[i].desc.toString());
        var id1 = "discoveryListDevice" + i;
        var id2 = "dldm" + i;
        var id3 = "dldmmb" + i;
        var id4 = "dldtds" + i;
        var id5 = "dldvms" + i;
        var id6 = "dldcds" + i;

        var id15 = "dldmbi" + i
        var id16 = "dldmi" + i

        if (i > $(".discoveryButton").length) {
            //INIT LOCAL DEVICE

            if (discoveryList[i].alive === true) {
                if (discoveryWorker[i]) {
                    if (discoveryWorker[i].ws)
                        $("#networkDeviceList").append($("<button>").prop({ id: id1, className: "btn btn-default btnSelector discoveryButton" }));
                    else
                        $("#networkDeviceList").append($("<button>").prop({ id: id1, className: "btn btn-default btnSelectorOffline discoveryButton" }));
                    discoveryWorker[i].alive = true;
                    $.fn.openDiscoveryWS(i);
                }
            } else {
                $("#networkDeviceList").append($("<button>").prop({ id: id1, className: "btn btn-default btnSelectorOffline discoveryButton" }));
                if (discoveryWorker[i]) {
                    discoveryWorker[i].alive = false;
                    $.fn.closeDiscoveryWS(i);
                }
            }

            $("#" + id1).append($("<div>").prop({ id: id2, className: "media" }));

            switch (discoveryList[i].model) {
                case "CP354":
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP354.png", className: "logoSelector" }));
                    break;
                case "CP704":
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP704.png", className: "logoSelector" }));
                    break;
                case "CP1504":
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP1504.png", className: "logoSelector" }));
                    break;
                case "CP3004":
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP3004.png", className: "logoSelector" }));
                    break;
                case "CP0716":
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP716.png", className: "logoSelector" }));
                    break;
                case "CP7164":
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP716.png", className: "logoSelector" }));
                    break;
                default:
                    $("#" + id2).append($("<img>").prop({ src: "./img/CP.png", className: "logoSelector" }));
                    break;
            }

            $("#" + id2).append($("<div>").prop({ id: id3, className: "media-body" }));
            $("#" + id3).append($("<div>").prop({ id: id4, className: "titleDeviceSelector" }));

            let ua = "Unnamed Amp";
            if (discoveryList[i].desc.toString().length > 0)
                $("#" + id4).prop("innerHTML", discoveryList[i].desc);
            else
                $("#" + id4).prop("innerHTML", ua);

            $("#" + id3).append($("<div>").prop({ id: id6, className: "channelDeviceSelector" }));
            $("#" + id6).prop("innerHTML", arrayAmplifier[i].network.lan.ip);

            $("#" + id3).append($("<div>").prop({ id: id5, className: "vuMeterSelector" }));


            ///////////////////////////////////////////////////////////////

            if ($.fn.getModel(i) == 7 || $.fn.getModel(i) == 8) {
                //16 channels devices
                for (var j = 0; j < channel16Count; j++) {
                    let idA = "dldrB" + j + "a" + i;
                    let idB = "dlri" + j + "a" + i;
                    let classA = "bRI border16RectangleInput" + j;
                    let classB = "rI rectangleInput" + j;

                    $("#" + id5).append($("<div>").prop({ id: idA, className: classA }));
                    $("#" + idA).append($("<div>").prop({ id: idB, className: classB }));
                }
            } else if ($.fn.getModel(i) == 5 || $.fn.getModel(i) == 6) {
                //1 channel devices
                let idA = "dldrB0a" + i;
                let idB = "dlri0a" + i;
                $("#" + id5).append($("<div>").prop({ id: idA, className: "bRI borderRectangleInput0" }));
                $("#" + idA).append($("<div>").prop({ id: idB, className: "rI rectangleInput0" }));
            } else if ($.fn.getModel(i) == 9) {
                //3 channels devices
                for (var j = 0; j < channel3Count; j++) {
                    let idA = "dldrB" + j + "a" + i;
                    let idB = "dlri" + j + "a" + i;
                    let classA = "bRI borderRectangleInput" + j;
                    let classB = "rI rectangleInput" + j;

                    $("#" + id5).append($("<div>").prop({ id: idA, className: classA }));
                    $("#" + idA).append($("<div>").prop({ id: idB, className: classB }));
                }
            } else {
                //4 channels devices
                for (var j = 0; j < channelCount; j++) {
                    let idA = "dldrB" + j + "a" + i;
                    let idB = "dlri" + j + "a" + i;
                    let classA = "bRI borderRectangleInput" + j;
                    let classB = "rI rectangleInput" + j;

                    $("#" + id5).append($("<div>").prop({ id: idA, className: classA }));
                    $("#" + idA).append($("<div>").prop({ id: idB, className: classB }));
                }
            }

            $("#" + id2).append($("<button>").prop({ id: id15, className: "infoDiscovery" }))
            $("#" + id15).append($("<div>").prop({ id: id16, className: "infoDiscoveryContent popover-btn" }));
            $("#" + id16).prop("innerHTML", "i");

            $("#" + id15).attr("data-toggle", "popover");
            $("#" + id15).attr("data-placement", "bottom");
            $("#" + id15).attr("data-original-title", "Status :");
            $("#" + id15).attr("data-content", "More network info");
        } else {
            let ua = "Unnamed Amp";
            if (discoveryList[i].desc.toString().length > 0)
                $("#" + id4).prop("innerHTML", discoveryList[i].desc);
            else
                $("#" + id4).prop("innerHTML", ua);

            // $("#" + id3).append($("<div>").prop({ id: id6, className: "channelDeviceSelector" }));
            $("#" + id6).prop("innerHTML", arrayAmplifier[i].network.lan.ip);
            if (discoveryList[i].alive === true) {
                if (discoveryWorker[i]) {
                    if (discoveryWorker[i].ws) {
                        $("#discoveryListDevice" + i).removeClass("btnSelectorOffline");
                        $("#discoveryListDevice" + i).addClass("btnSelector");
                    } else
                        $.fn.openDiscoveryWS(i);
                    discoveryWorker[i].alive = true;

                }
            } else {
                $("#discoveryListDevice" + i).removeClass("btnSelector");
                $("#discoveryListDevice" + i).addClass("btnSelectorOffline");
                if (discoveryWorker[i]) {
                    discoveryWorker[i].alive = false;
                    $.fn.closeDiscoveryWS(i);
                }
            }
        }

    }

    for (var i = 0; i < ($(".discoveryButton").length - discoveryList.length + 1); i++) {
        var j = $(".discoveryButton").length - i;
        $("#discoveryListDevice" + j).remove();
    }

    var len = $(".discoveryButton").length;
    var j = 0;
    let item1, desc1, item2, desc2, x;
    let idS = ".titleDeviceSelector";

    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < (len - i - 1); j++) {
            item1 = $("#networkDeviceList").children().eq(j);
            item2 = $("#networkDeviceList").children().eq(j + 1);
            desc1 = $("#networkDeviceList").children().eq(j).find(idS).html();
            desc2 = $("#networkDeviceList").children().eq(j + 1).find(idS).html();
            if (desc1.localeCompare(desc2) > 0) {
                $(item2).insertBefore($(item1));
            }
        }
    }
}

//POOL EVERY 5 SECONDS LIST OF DEVICES
$.fn.poolDiscovery = function() {
    if (demoMode === 0) {
        let message = new Object();
        message.data = commandToJSON($.fn.getCommandFromArgs(cmd_get_lan_config, 0, "null", "null", "null"));

        //Send command "get lan config" to all the devices to get last update
        for (var i = 0; i < arrayAmplifier.length; i++) {
            if (discoveryWorker[i])
                discoveryWorker[i].worker.postMessage(message);
        }
        $.fn.sendCommandWS(cmd_get_neighbour_list, 0, "null", "null", "null");
        $.fn.setDiscoverySource();
    } else {
        for (var i = 0; i < arrayAmpSizeDemo; i++) {
            discoveryList[i] = new discoveredAmpDemoConstructor();
            discoveryList[i].desc = arrayAmplifier[i].label;
        }
        $.fn.setDiscoverySource();
    }
    setTimeout(function() { $.fn.poolDiscovery(); }, discoveryTimer);
}

//SOURCE SETUP
$.fn.setDataSoloSource = function(arg, src) {
    if (arg < 99) {
        //set primary
        if (src === 0) {
            $.fn.sendCommandWS(cmd_set_solo_channel_source_pri, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[arg].source.primary);
            $.fn.setDataSoloSourceUpdate(arg);
        }
        //set secondary
        else if (src === 1) {
            $.fn.sendCommandWS(cmd_set_solo_channel_source_sec, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[arg].source.secondary);
            $.fn.setDataSoloSourceUpdate(arg);
        }
        //set label
        else if (src === 2) {
            $.fn.sendCommandWS(cmd_set_solo_channel_name, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[arg].label);
            $.fn.setDataSoloSourceUpdate(arg);
        }
        //set mixer gain
        else if (src === 3) {

        }
        //set mixer gain mute all
        else if (src === 4) {
            var cmdArray = new Array(maxMixerInput);
            for (var i = 0; i < maxMixerInput; i++) {
                cmdArray[i] = $.fn.getCommandFromArgs(cmd_set_solo_channel_mixer_gain, soloAmplifierSelected, soloChannelSelected, i, -80.0);
            }
            $.fn.sendCommandsWS(cmdArray);
            $.fn.setDataSoloSourceUpdate(arg);
        }
    } else if (arg === 101) {
        $.fn.setDataSoloSourceUpdate(src);
    } else {
        switch (src) {
            case 0:
                $.fn.setDataSoloSourceUpdate(src);
                break;
            case 1:
                $.fn.setDataSoloSourceUpdate(src);
                break;
            case 2:
                $.fn.setDataSoloSourceUpdate(src);
                break;
            case 3:
                $.fn.setDataSoloSourceUpdate(src);
                break;
            case 99:
                for (var i = 0; i < channel16Count; i++) {
                    $.fn.setDataSoloSourceUpdate(i);
                };
                break;
        }
    }
}

$.fn.setDataSoloSourceUpdate = function(i) {
    let s6 = ".sourceCh" + i;
    $(s6).removeClass("active");
    //SOURCE SETUP
    let s1 = "#source" + i + "nav" + arrayAmplifier[soloAmplifierSelected].channel[i].source.primary + "P";
    let s2 = "#source" + i + "nav" + arrayAmplifier[soloAmplifierSelected].channel[i].source.secondary + "S";
    let s3 = "#soloChannelLabel";
    $(s1).addClass("active");
    $(s2).addClass("active");
    if (i === soloChannelSelected) {
        $(".itemEighterLabelTitle").prop("innerHTML", "OUTPUT " + labelOverviewChannel[i]);
        $(s3).val(arrayAmplifier[soloAmplifierSelected].channel[i].label);
    }

    //CHANNEL LABEL
    let s4 = "#overviewChLabel" + i;
    let s5 = "#registerGroupAmp1Ch" + i;
    $(s4).text(arrayAmplifier[soloAmplifierSelected].channel[i].label);
    $(s5).text(arrayAmplifier[soloAmplifierSelected].channel[i].label);

    //MUTE BUTTON STATUS
    let g3 = "#overviewButtonMute" + i;
    if (arrayAmplifier[soloAmplifierSelected].channel[i].gain.muteEna === true)
        $(g3).addClass("active");
    else
        $(g3).removeClass("active");
}

//SIGGEN SETUP
$.fn.setDataSoloSigGen = function(arg, src) {
    switch (arg) {
        //UPDATE FROM UI FREQ GEN FREQUENCY
        case 0:
            $.fn.sendCommandWS(cmd_set_freq_gen_frequency, soloAmplifierSelected, "null", "null", arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.frequency);
            $.fn.setDataSoloSigGenUpdate();
            break;
            //UPDATE FROM UI FREQ GEN GAIN
        case 1:
            $.fn.sendCommandWS(cmd_set_freq_gen_gain, soloAmplifierSelected, "null", "null", arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.gain);
            $.fn.setDataSoloSigGenUpdate();
            break;
            //UPDATE FROM UI PINK NOISE GAIN
        case 2:
            $.fn.sendCommandWS(cmd_set_pink_gen_gain, soloAmplifierSelected, "null", "null", arrayAmplifier[soloAmplifierSelected].signalGenerator.pinkNoise.gain);
            $.fn.setDataSoloSigGenUpdate();
            break;
            //UPDATE FROM WEBSOCKET
        case 3:
            $.fn.setDataSoloSigGenUpdate();
            break;
        default:
            break;
    }
}

$.fn.setDataSoloSigGenUpdate = function() {
    $("#siggenSineFreqInput").val(arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.frequency);
    $("#siggenSineGainInput").val(arrayAmplifier[soloAmplifierSelected].signalGenerator.frequencyGenerator.gain);
    $("#siggenPinkGainInput").val(arrayAmplifier[soloAmplifierSelected].signalGenerator.pinkNoise.gain);
}


//MIXER SETUP
$.fn.setDataSoloMixer = function(arg, src) {
    switch (arg) {
        //UPDATE FROM SLIDER
        case 0:
            $.fn.sendCommandWS(cmd_set_solo_channel_mixer_gain, soloAmplifierSelected, soloChannelSelected, src, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[src]);
            $.fn.setDataSoloMixerUpdate(soloChannelSelected);
            break;
        case 1:
            $.fn.sendCommandWS(cmd_set_solo_channel_mixer_gain, soloAmplifierSelected, soloChannelSelected, src, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[src]);
            $.fn.setDataSoloMixerUpdate(soloChannelSelected);
            break;
        case 2:
            break;
            //SET MIXER GAIN MUTE ALL
        case 3:
            var cmdArray = new Array(maxMixerInput);
            for (var i = 0; i < maxMixerInput; i++) {
                cmdArray[i] = $.fn.getCommandFromArgs(cmd_set_solo_channel_mixer_gain, soloAmplifierSelected, soloChannelSelected, i, -80.0);
            }
            $.fn.sendCommandsWS(cmdArray);
            $.fn.setDataSoloMixerUpdate(src);
            break;
        case 99:
            $.fn.setDataSoloMixerUpdate(soloChannelSelected);
            break;
        default:
            break;
    }
}

$.fn.setDataSoloMixerUpdate = function(arg) {
    // console.log("Updatemixer");
    if (arg === soloChannelSelected) {
        for (var i = 0; i < maxMixerInput; i++) {
            let m1 = "#mixer" + i;
            let m2 = "#sliderMixerVertical" + i;
            let infini = "\u221e";
            //GAIN VALUE TEXTFIELD
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[i] > -80.0)
                $(m1).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[i].toFixed(1));
            else {
                $(m1).val("OFF");
            }
            //SLIDER GAIN VALUE
            try {
                $(m2).slider("value", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[i]);
            } catch (error) {}
        }
    }
}

//GAIN SETUP
$.fn.setDataSoloGain = function(arg, src) {
    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (arg === 0 || arg === 1)) {
        if (arg === 0) {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[1].gain.muteEna = arrayAmplifier[soloAmplifierSelected].channel[0].gain.muteEna;
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[1].gain.gain = arrayAmplifier[soloAmplifierSelected].channel[0].gain.gain;
                    break;
                case 2:
                    arrayAmplifier[soloAmplifierSelected].channel[1].gain.polarityEna = arrayAmplifier[soloAmplifierSelected].channel[0].gain.polarityEna;
                    break;
            }
        } else {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[0].gain.muteEna = arrayAmplifier[soloAmplifierSelected].channel[1].gain.muteEna;
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[0].gain.gain = arrayAmplifier[soloAmplifierSelected].channel[1].gain.gain;
                    break;
                case 2:
                    arrayAmplifier[soloAmplifierSelected].channel[0].gain.polarityEna = arrayAmplifier[soloAmplifierSelected].channel[1].gain.polarityEna;
                    break;
            }
        }
        if (arg < 99) {
            $.fn.setDataSoloGainUpdate(0);
            $.fn.setDataSoloGainUpdate(1);
            var arrayCmd = new Array();
            switch (src) {
                case 0:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_mute, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[0].gain.muteEna));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_mute, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[1].gain.muteEna));
                    break;
                case 1:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_gain, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[0].gain.gain));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_gain, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[1].gain.gain));
                    break;
                case 2:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_polarity, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[0].gain.polarityEna));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_polarity, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[1].gain.polarityEna));
                    break;
                default:
                    break;
            }
            $.fn.sendCommandsWS(arrayCmd);
        }
        return;
    }
    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (arg === 2 || arg === 3)) {
        if (arg === 2) {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[3].gain.muteEna = arrayAmplifier[soloAmplifierSelected].channel[2].gain.muteEna;
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[3].gain.gain = arrayAmplifier[soloAmplifierSelected].channel[2].gain.gain;
                    break;
                case 2:
                    arrayAmplifier[soloAmplifierSelected].channel[3].gain.polarityEna = arrayAmplifier[soloAmplifierSelected].channel[2].gain.polarityEna;
                    break;
            }
        } else {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[2].gain.muteEna = arrayAmplifier[soloAmplifierSelected].channel[3].gain.muteEna;
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[2].gain.gain = arrayAmplifier[soloAmplifierSelected].channel[3].gain.gain;
                    break;
                case 2:
                    arrayAmplifier[soloAmplifierSelected].channel[2].gain.polarityEna = arrayAmplifier[soloAmplifierSelected].channel[3].gain.polarityEna;
                    break;
            }
        }
        if (arg < 99) {
            $.fn.setDataSoloGainUpdate(2);
            $.fn.setDataSoloGainUpdate(3);
            var arrayCmd = new Array();
            switch (src) {
                case 0:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_mute, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[2].gain.muteEna));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_mute, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[3].gain.muteEna));
                    break;
                case 1:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_gain, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[2].gain.gain));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_gain, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[3].gain.gain));
                    break;
                case 2:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_polarity, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[2].gain.polarityEna));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_polarity, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[3].gain.polarityEna));
                    break;
                default:
                    break;
            }
            $.fn.sendCommandsWS(arrayCmd);
        }
        return;
    }
    if (arg < 99) {
        $.fn.setDataSoloGainUpdate(arg);
        switch (src) {
            case 0:
                $.fn.sendCommandWS(cmd_set_solo_mute, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[Number(arg)].gain.muteEna);
                break;
            case 1:
                $.fn.sendCommandWS(cmd_set_solo_gain, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[Number(arg)].gain.gain);
                break;
            case 2:
                $.fn.sendCommandWS(cmd_set_solo_polarity, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[Number(arg)].gain.polarityEna);
                break;
            default:
                break;
        }
    } else if (arg === 101) {
        $.fn.setDataSoloGainUpdate(src);
    } else {
        for (var i = 0; i < channel16Count; i++) {
            $.fn.setDataSoloGainUpdate(i)
        }
    }
}

$.fn.setDataSoloGainUpdate = function(i) {
    let g1 = "#gain" + i;
    let g2 = "#sliderVertical" + i;
    let g3 = "#overviewButtonMute" + i;
    let g4 = "#buttonPhase" + i;
    let g5 = "#overviewSourceLabel" + i;

    //GAIN VALUE TEXTFIELD
    $(g1).val(arrayAmplifier[soloAmplifierSelected].channel[i].gain.gain.toFixed(1));
    //SLIDER GAIN VALUE
    $(g2).slider("value", arrayAmplifier[soloAmplifierSelected].channel[i].gain.gain);
    //MUTE BUTTON STATUS
    if (arrayAmplifier[soloAmplifierSelected].channel[i].gain.muteEna === true)
        $(g3).addClass("active");
    else
        $(g3).removeClass("active");
    //POLARITY BUTTON STATUS
    if (arrayAmplifier[soloAmplifierSelected].channel[i].gain.polarityEna === true)
        $(g4).addClass("active");
    else
        $(g4).removeClass("active");
    $(g5).html("" + arrayAmplifier[soloAmplifierSelected].channel[i].gain.gain.toFixed(1) + "dB");
}

//DELAY SETUP
$.fn.setDataSoloDelay = function(arg, src) {
    // $.fn.maxDelayCompute();
    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (arg === 0 || arg === 1)) {
        if (arg === 0) {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[1].delay.delayEna = arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna;
                    if (arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna === true) {
                        var maxDelay = 0.0;
                        if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 0) <= $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1))
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1);
                        else
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0);
                        if (arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay >= maxDelay) {
                            arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = maxDelay;
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay;
                        }
                    } else {
                        $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                        $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                    }
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay;
                    break;
            }
        } else {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna = arrayAmplifier[soloAmplifierSelected].channel[1].delay.delayEna;
                    if (arrayAmplifier[soloAmplifierSelected].channel[1].delay.delayEna === true) {
                        var maxDelay = 0.0;
                        if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 0) <= $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1))
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1);
                        else
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0);
                        if (arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay >= maxDelay) {
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = maxDelay;
                            arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay;
                        }
                    } else {
                        $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                        $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                    }
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay;
                    break;
            }
        }
        $.fn.maxDelayCompute();
        if (arg < 99) {
            $.fn.setDataSoloDelayUpdate(0);
            $.fn.setDataSoloDelayUpdate(1);
            var arrayCmd = new Array();
            switch (src) {
                case 0:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_enable, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_enable, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[1].delay.delayEna));
                    break;
                case 1:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_value, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_value, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay));
                    break;
                default:
                    break;
            }
            $.fn.sendCommandsWS(arrayCmd);
        }
        return;
    }
    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (arg === 2 || arg === 3)) {
        if (arg === 2) {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[3].delay.delayEna = arrayAmplifier[soloAmplifierSelected].channel[2].delay.delayEna;
                    if (arrayAmplifier[soloAmplifierSelected].channel[2].delay.delayEna === true) {
                        var maxDelay = 0.0;
                        if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 2) <= $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3))
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3);
                        else
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2);
                        if (arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay >= maxDelay) {
                            arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = maxDelay;
                            arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay;
                        }
                    } else {
                        $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                        $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                    }
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay;
                    break;
                case 2:
            }
        } else {
            switch (src) {
                case 0:
                    arrayAmplifier[soloAmplifierSelected].channel[2].delay.delayEna = arrayAmplifier[soloAmplifierSelected].channel[3].delay.delayEna;
                    if (arrayAmplifier[soloAmplifierSelected].channel[3].delay.delayEna === true) {
                        var maxDelay = 0.0;
                        if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 2) <= $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3))
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3);
                        else
                            maxDelay = delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2);
                        if (arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay >= maxDelay) {
                            arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = maxDelay;
                            arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay;
                        }
                    } else {
                        $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                        $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                    }
                    break;
                case 1:
                    arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay;
                    break;
            }
        }
        $.fn.maxDelayCompute();
        if (arg < 99) {
            $.fn.setDataSoloDelayUpdate(2);
            $.fn.setDataSoloDelayUpdate(3);
            var arrayCmd = new Array();
            switch (src) {
                case 0:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_enable, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[2].delay.delayEna));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_enable, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[3].delay.delayEna));
                    break;
                case 1:
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_value, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_delay_value, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay));
                    break;
                default:
                    break;
            }
            $.fn.sendCommandsWS(arrayCmd);
        }
        return;
    } else {
        $.fn.maxDelayCompute();
        if (arg < 99) {
            $.fn.setDataSoloDelayUpdate(arg);
            switch (src) {
                case 0:
                    $.fn.sendCommandWS(cmd_set_solo_delay_enable, soloAmplifierSelected, Number(arg), "null", Boolean(arrayAmplifier[soloAmplifierSelected].channel[Number(arg)].delay.delayEna));
                    if (arrayAmplifier[soloAmplifierSelected].channel[Number(arg)].delay.delayEna === false)
                        $("#itemQuarterTotalDelay" + arg).removeClass("Max");
                    break;
                case 1:
                    $.fn.sendCommandWS(cmd_set_solo_delay_value, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].channel[Number(arg)].delay.delay);
                    break;
                default:
                    break;
            }
        } else if (arg === 101) {
            $.fn.setDataSoloDelayUpdate(src);
        } else {
            for (var i = 0; i < channel16Count; i++) {
                $.fn.setDataSoloDelayUpdate(i);
            }
        }
    }
}

$.fn.setDataSoloDelayUpdate = function(i) {
    let d1 = "#delay" + i;
    let d2 = "#sliderDelayVertical" + i;
    let d3 = "#buttonDelay" + i;
    let d4 = "#delayMeter" + i;
    //DELAY VALUE TEXTFIELD
    $(d1).val(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[i].delay.delay));
    //SLIDER DELAY VALUE 
    $(d2).slider("value", Math.log10(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[i].delay.delay)));
    //DELAY BUTTON STATUS
    if (arrayAmplifier[soloAmplifierSelected].channel[i].delay.delayEna === true)
        $(d3).addClass("active");
    else
        $(d3).removeClass("active");
    //DELAY METER VALUE TEXTFIELD
    $(d4).val(Math.round((parseFloat(arrayAmplifier[soloAmplifierSelected].channel[i].delay.delay) * speedOfSound / 1000) * 100) / 100);
}

//PEQ SETUP
$.fn.setDataSoloPEQ = function(arg, src) {
    if (arg < 99) {
        //SEND COMMAND
        switch (src) {
            case 0:
                if (displaySoloGroup === 0) {
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_enable, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_enable, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_enable, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_enable, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_peq_enable, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].ena);
                } else {
                    for (var i = 0; i < arrayAmplifier.length; i++) {
                        $.fn.sendCommandWS(cmd_set_group_peq_enable, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].ena);
                    }
                }
                break;
            case 1:
                if (displaySoloGroup === 0) {
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_type, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_type, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_type, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_type, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_peq_type, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].type);
                } else {
                    for (var i = 0; i < arrayAmplifier.length; i++) {
                        $.fn.sendCommandWS(cmd_set_group_peq_type, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].type);
                    }
                }
                break;
            case 2:
                if (displaySoloGroup === 0) {
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_peq_freq, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency);
                } else {
                    for (var i = 0; i < arrayAmplifier.length; i++) {
                        $.fn.sendCommandWS(cmd_set_group_peq_freq, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].frequency);
                    }
                }
                break;
            case 3:
                if (displaySoloGroup === 0) {
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_peq_gain, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain);
                } else {
                    for (var i = 0; i < arrayAmplifier.length; i++) {
                        $.fn.sendCommandWS(cmd_set_group_peq_gain, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].gain);
                    }
                }
                break;
            case 4:
                if (displaySoloGroup === 0) {
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_q, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_q, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_q, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_q, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_peq_q, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].q);
                } else {
                    for (var i = 0; i < arrayAmplifier.length; i++) {
                        $.fn.sendCommandWS(cmd_set_group_peq_q, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].q);
                    }
                }
                break;
            case 5:
                var arrayCmd = new Array();
                if (displaySoloGroup === 0) {
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0) {
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                            arrayAmplifier[soloAmplifierSelected].channel[1].peq.peq[arg].gain = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        } else {
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                            arrayAmplifier[soloAmplifierSelected].channel[0].peq.peq[arg].gain = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        }
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 0, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 1, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2) {
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                            arrayAmplifier[soloAmplifierSelected].channel[3].peq.peq[arg].gain = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        } else {
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency;
                            arrayAmplifier[soloAmplifierSelected].channel[2].peq.peq[arg].gain = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain;
                        }
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 2, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, 3, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_freq, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].frequency));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, soloChannelSelected, Number(arg), arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[arg].gain));
                } else {

                    for (var i = 0; i < arrayAmplifier.length; i++) {
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_group_peq_freq, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].frequency));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_group_peq_gain, i, groupGroupSelected, Number(arg), arrayGroup[groupGroupSelected].peq[arg].gain));
                        $.fn.sendCommandsWS(arrayCmd);
                    }
                }
                $.fn.sendCommandsWS(arrayCmd);
                break;
        }

        //UPDATE THE UI
        if (src < 5)
            $.fn.setDataSoloPEQUpdate(arg);
        else
            $.fn.setDataSoloPEQUpdateWithoutDraggie(arg);

    } else if (arg === 100) {
        var arrCmd = new Array();
        for (var j = 0; j < eqCount; j++) {
            arrCmd.push($.fn.getCommandFromArgs(cmd_get_solo_peq_enable, soloAmplifierSelected, soloChannelSelected, j, "null"));
            arrCmd.push($.fn.getCommandFromArgs(cmd_get_solo_peq_type, soloAmplifierSelected, soloChannelSelected, j, "null"));
            arrCmd.push($.fn.getCommandFromArgs(cmd_get_solo_peq_freq, soloAmplifierSelected, soloChannelSelected, j, "null"));
            arrCmd.push($.fn.getCommandFromArgs(cmd_get_solo_peq_gain, soloAmplifierSelected, soloChannelSelected, j, "null"));
            arrCmd.push($.fn.getCommandFromArgs(cmd_get_solo_peq_q, soloAmplifierSelected, soloChannelSelected, j, "null"));
        }
        $.fn.sendCommandsWS(arrCmd);

        for (var i = 0; i < eqCount; i++) {
            $.fn.setDataSoloPEQUpdate(i);
        }
    } else {
        for (var i = 0; i < eqCount; i++) {
            $.fn.setDataSoloPEQUpdate(i);
        }
    }
}

//SEND COPY SOLO CONTENT TO DSP
$.fn.setDataSoloPEQCopy = function(src, peq) {
    var arrCmd = new Array(0);
    for (var k = 0; k < src.length; k++) {
        for (var j = 0; j < peq.length; j++) {
            var peqCopyCommand = new Object();
            peqCopyCommand.ena = arrayAmplifier[soloAmplifierSelected].channel[parseInt(src[k])].peq.peq[parseInt(peq[j])].ena;
            peqCopyCommand.type = arrayAmplifier[soloAmplifierSelected].channel[parseInt(src[k])].peq.peq[parseInt(peq[j])].type;
            peqCopyCommand.frequency = arrayAmplifier[soloAmplifierSelected].channel[parseInt(src[k])].peq.peq[parseInt(peq[j])].frequency;
            peqCopyCommand.gain = arrayAmplifier[soloAmplifierSelected].channel[parseInt(src[k])].peq.peq[parseInt(peq[j])].gain;
            peqCopyCommand.q = arrayAmplifier[soloAmplifierSelected].channel[parseInt(src[k])].peq.peq[parseInt(peq[j])].q;

            var peqCopyCommandTxt = JSON.stringify(peqCopyCommand);
            let resultTxt = peqCopyCommandTxt.replaceAll("\"", "\\\"");
            arrCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq, soloAmplifierSelected, parseInt(src[k]), parseInt(peq[j]), resultTxt));
        }
    }
    if (arrCmd.length > 0)
        $.fn.sendCommandsWS(arrCmd);
    // console.log("src peq update" + arrCmd);
}

//SEND COPY GROUP PEQ CONTENT TO DSP
$.fn.setDataGroupPEQCopy = function(src, peq) {
    // //COPY TO LOCAL DEVICE
    // var arrCmd = new Array(0);
    // for (var k = 0; k < src.length; k++) {
    //     for (var j = 0; j < peq.length; j++) {
    //         var peqCopyCommand = new Object();
    //         peqCopyCommand.ena = arrayGroup[parseInt(src[k])].peq[parseInt(peq[j])].ena;
    //         peqCopyCommand.type = arrayGroup[parseInt(src[k])].peq[parseInt(peq[j])].type;
    //         peqCopyCommand.frequency = arrayGroup[parseInt(src[k])].peq[parseInt(peq[j])].frequency;
    //         peqCopyCommand.gain = arrayGroup[parseInt(src[k])].peq[parseInt(peq[j])].gain;
    //         peqCopyCommand.q = arrayGroup[parseInt(src[k])].peq[parseInt(peq[j])].q;

    //         var peqCopyCommandTxt = JSON.stringify(peqCopyCommand);
    //         let resultTxt = peqCopyCommandTxt.replaceAll("\"", "\\\"");
    //         arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_peq, soloAmplifierSelected, parseInt(src[k]), parseInt(peq[j]), resultTxt));
    //     }
    // }
    // if (arrCmd.length > 0)
    //     $.fn.sendCommandsWS(arrCmd);

    //COPY TO NETWORK CHANNEL THAT ARE REGISTERED TO THIS GROUP
    for (var i = 0; i < arrayAmplifier.length; i++) {
        let arrCmd = new Array(0);
        for (var k = 0; k < groupCount; k++) {
            if (jQuery.inArray(k, src) >= 0) {
                if (returnGroupGroupRegistration(i, k) > 0 || i === 0) {
                    for (var j = 0; j < peq.length; j++) {
                        var peqCopyCommand = new Object();
                        peqCopyCommand.ena = arrayGroup[k].peq[parseInt(peq[j])].ena;
                        peqCopyCommand.type = arrayGroup[k].peq[parseInt(peq[j])].type;
                        peqCopyCommand.frequency = arrayGroup[k].peq[parseInt(peq[j])].frequency;
                        peqCopyCommand.gain = arrayGroup[k].peq[parseInt(peq[j])].gain;
                        peqCopyCommand.q = arrayGroup[k].peq[parseInt(peq[j])].q;

                        var peqCopyCommandTxt = JSON.stringify(peqCopyCommand);
                        let resultTxt = peqCopyCommandTxt.replaceAll("\"", "\\\"");
                        arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_peq, i, k, parseInt(peq[j]), resultTxt));
                        // $.fn.sendCommandWS(cmd_set_group_peq, i, k, parseInt(peq[j]), resultTxt);
                    }
                }
            }
        }
        if (arrCmd.length > 0) {
            $.fn.sendCommandsWS(arrCmd);
        }
    }
    // console.log("src peq update" + arrCmd);
}

//SET GAIN PEQ TO DSP
$.fn.setDataSoloPEQGain = function(src, peq) {
    var arrCmd = new Array(0);
    for (var k = 0; k < src.length; k++) {
        for (var j = 0; j < peq.length; j++) {
            arrCmd.push($.fn.getCommandFromArgs(cmd_set_solo_peq_gain, soloAmplifierSelected, parseInt(src[k]), parseInt(peq[j]), arrayAmplifier[soloAmplifierSelected].channel[parseInt(src[k])].peq.peq[parseInt(peq[j])].gain));
        }
    }
    if (arrCmd.length > 0)
        $.fn.sendCommandsWS(arrCmd);
    // console.log("src peq update" + arrCmd);
}

$.fn.setDataSoloPEQUpdate = function(i) {
    if (displaySoloGroup === 0) {
        //PEQ ENABLE
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].ena === true) {
            $("#dragPEQ" + i).addClass("enable");
            $("#label" + i).addClass("enable");
            $("#peqAnav" + i).addClass("enable");
            $("#dragPEQ" + i).draggabilly('enable');
            $("#eqEna" + i).prop("checked", true);
            $("#enaTogglePEQ" + i).addClass("active");
        } else {
            $("#dragPEQ" + i).removeClass("enable");
            $("#label" + i).removeClass("enable");
            $("#peqAnav" + i).removeClass("enable");
            $("#dragPEQ" + i).draggabilly('disable');
            $("#eqEna" + i).prop("checked", false);
            $("#enaTogglePEQ" + i).removeClass("active");
        }
        arrayEqParam[i].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].ena;

        //PEQ FREQUENCY
        arrayEqParam[i].frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency;
        var freq = "#freq_text" + i;
        $(freq).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency);
        freq = "#freq_textSolo" + i;
        $(freq).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency);
        var freq = "#sliderHorizontalFreqPEQ" + i;
        $(freq).slider("option", "value", Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency));

        //PEQ GAIN
        arrayEqParam[i].gain = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain;
        var gain = "#gain_text" + i;
        $(gain).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);
        gain = "#gain_textSolo" + i;
        $(gain).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);
        var gain = "#sliderHorizontalGainPEQ" + i;
        $(gain).slider("option", "value", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);

        //PEQ Q
        arrayEqParam[i].q = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q;
        var q = "#q_text" + i;
        $(q).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q);
        q = "#q_textSolo" + i;
        $(q).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q);
        var q = "#sliderHorizontalQPEQ" + i;
        $(q).slider("option", "value", Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q));

        //PEQ TYPE
        arrayEqParam[i].type = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].type;
        var n = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].type;
        var imgSrc = "./img/peq/peq" + n + ".png";
        var id = "#peqImgNav" + i;
        $(id).attr("src", imgSrc);
        id = "#peqImgSolo" + i;
        $(id).attr("src", imgSrc);
        var dest = "#eqType" + i;
        $(dest).val(n);
        var idType = "#peqType" + i;
        $(idType).html(peqLabelShort[arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].type]);

    } else {
        //PEQ ENABLE
        if (arrayGroup[groupGroupSelected].peq[i].ena === true) {
            $("#dragPEQ" + i).addClass("enable");
            $("#label" + i).addClass("enable");
            $("#peqAnav" + i).addClass("enable");
            $("#dragPEQ" + i).draggabilly('enable');
            $("#eqEna" + i).prop("checked", true);
            $("#enaTogglePEQ" + i).addClass("active");
        } else {
            $("#dragPEQ" + i).removeClass("enable");
            $("#label" + i).removeClass("enable");
            $("#peqAnav" + i).removeClass("enable");
            $("#dragPEQ" + i).draggabilly('disable');
            $("#eqEna" + i).prop("checked", false);
            $("#enaTogglePEQ" + i).removeClass("active");
        }
        arrayEqParam[i].ena = arrayGroup[groupGroupSelected].peq[i].ena;

        //PEQ FREQUENCY
        arrayEqParam[i].frequency = arrayGroup[groupGroupSelected].peq[i].frequency;
        var freq = "#freq_text" + i;
        $(freq).val(arrayGroup[groupGroupSelected].peq[i].frequency);
        freq = "#freq_textSolo" + i;
        $(freq).val(arrayGroup[groupGroupSelected].peq[i].frequency);
        var freq = "#sliderHorizontalFreqPEQ" + i;
        $(freq).slider("option", "value", Math.log10(arrayGroup[groupGroupSelected].peq[i].frequency));

        //PEQ GAIN
        arrayEqParam[i].gain = arrayGroup[groupGroupSelected].peq[i].gain;
        var gain = "#gain_text" + i;
        $(gain).val(arrayGroup[groupGroupSelected].peq[i].gain);
        gain = "#gain_textSolo" + i;
        $(gain).val(arrayGroup[groupGroupSelected].peq[i].gain);
        var gain = "#sliderHorizontalGainPEQ" + i;
        $(gain).slider("option", "value", arrayGroup[groupGroupSelected].peq[i].gain);

        //PEQ Q
        arrayEqParam[i].q = arrayGroup[groupGroupSelected].peq[i].q;
        var q = "#q_text" + i;
        $(q).val(arrayGroup[groupGroupSelected].peq[i].q);
        q = "#q_textSolo" + i;
        $(q).val(arrayGroup[groupGroupSelected].peq[i].q);
        var q = "#sliderHorizontalQPEQ" + i;
        $(q).slider("option", "value", Math.log10(arrayGroup[groupGroupSelected].peq[i].q));

        //PEQ TYPE
        arrayEqParam[i].type = arrayGroup[groupGroupSelected].peq[i].type;
        var n = arrayGroup[groupGroupSelected].peq[i].type;
        var imgSrc = "./img/peq/peq" + n + ".png";
        var id = "#peqImgNav" + i;
        $(id).attr("src", imgSrc);
        id = "#peqImgSolo" + i;
        $(id).attr("src", imgSrc);
        var dest = "#eqType" + i;
        $(dest).val(n);
        var idType = "#peqType" + i;
        $(idType).html(peqLabelShort[arrayGroup[groupGroupSelected].peq[i].type]);
    }
    // $.fn.initiatePEQDraggie();
    if (peqViewMode != 1)
        $.fn.draggieSetPosition(i);
    $.fn.drawPEQWidget(i);
}

$.fn.setDataSoloPEQUpdateWithoutDraggie = function(i) {
    if (displaySoloGroup === 0) {
        //PEQ ENABLE
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].ena === true) {
            $("#dragPEQ" + i).addClass("enable");
            $("#label" + i).addClass("enable");
            $("#peqAnav" + i).addClass("enable");
            $("#dragPEQ" + i).draggabilly('enable');
            $("#eqEna" + i).prop("checked", true);
            $("#enaTogglePEQ" + i).addClass("active");
        } else {
            $("#dragPEQ" + i).removeClass("enable");
            $("#label" + i).removeClass("enable");
            $("#peqAnav" + i).removeClass("enable");
            $("#dragPEQ" + i).draggabilly('disable');
            $("#eqEna" + i).prop("checked", false);
            $("#enaTogglePEQ" + i).removeClass("active");
        }
        arrayEqParam[i].ena = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].ena;

        //PEQ FREQUENCY
        arrayEqParam[i].frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency;
        var freq = "#freq_text" + i;
        $(freq).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency);
        freq = "#freq_textSolo" + i;
        $(freq).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency);
        var freq = "#sliderHorizontalFreqPEQ" + i;
        $(freq).slider("option", "value", Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].frequency));

        //PEQ GAIN
        arrayEqParam[i].gain = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain;
        var gain = "#gain_text" + i;
        $(gain).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);
        gain = "#gain_textSolo" + i;
        $(gain).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);
        var gain = "#sliderHorizontalGainPEQ" + i;
        $(gain).slider("option", "value", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].gain);

        //PEQ Q
        arrayEqParam[i].q = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q;
        var q = "#q_text" + i;
        $(q).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q);
        q = "#q_textSolo" + i;
        $(q).val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q);
        var q = "#sliderHorizontalQPEQ" + i;
        $(q).slider("option", "value", Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].q));

        //PEQ TYPE
        arrayEqParam[i].type = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].type;
        var n = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[i].type;
        var imgSrc = "./img/peq/peq" + n + ".png";
        var id = "#peqImgNav" + i;
        $(id).attr("src", imgSrc);
        id = "#peqImgSolo" + i;
        $(id).attr("src", imgSrc);
    } else {
        //PEQ ENABLE
        if (arrayGroup[groupGroupSelected].peq[i].ena === true) {
            $("#dragPEQ" + i).addClass("enable");
            $("#label" + i).addClass("enable");
            $("#peqAnav" + i).addClass("enable");
            $("#dragPEQ" + i).draggabilly('enable');
            $("#eqEna" + i).prop("checked", true);
            $("#enaTogglePEQ" + i).addClass("active");
        } else {
            $("#dragPEQ" + i).removeClass("enable");
            $("#label" + i).removeClass("enable");
            $("#peqAnav" + i).removeClass("enable");
            $("#dragPEQ" + i).draggabilly('disable');
            $("#eqEna" + i).prop("checked", false);
            $("#enaTogglePEQ" + i).removeClass("active");
        }
        arrayEqParam[i].ena = arrayGroup[groupGroupSelected].peq[i].ena;

        //PEQ FREQUENCY
        arrayEqParam[i].frequency = arrayGroup[groupGroupSelected].peq[i].frequency;
        var freq = "#freq_text" + i;
        $(freq).val(arrayGroup[groupGroupSelected].peq[i].frequency);
        freq = "#freq_textSolo" + i;
        $(freq).val(arrayGroup[groupGroupSelected].peq[i].frequency);
        var freq = "#sliderHorizontalFreqPEQ" + i;
        $(freq).slider("option", "value", Math.log10(arrayGroup[groupGroupSelected].peq[i].frequency));

        //PEQ GAIN
        arrayEqParam[i].gain = arrayGroup[groupGroupSelected].peq[i].gain;
        var gain = "#gain_text" + i;
        $(gain).val(arrayGroup[groupGroupSelected].peq[i].gain);
        gain = "#gain_textSolo" + i;
        $(gain).val(arrayGroup[groupGroupSelected].peq[i].gain);
        var gain = "#sliderHorizontalGainPEQ" + i;
        $(gain).slider("option", "value", arrayGroup[groupGroupSelected].peq[i].gain);

        //PEQ Q
        arrayEqParam[i].q = arrayGroup[groupGroupSelected].peq[i].q;
        var q = "#q_text" + i;
        $(q).val(arrayGroup[groupGroupSelected].peq[i].q);
        q = "#q_textSolo" + i;
        $(q).val(arrayGroup[groupGroupSelected].peq[i].q);
        var q = "#sliderHorizontalQPEQ" + i;
        $(q).slider("option", "value", Math.log10(arrayGroup[groupGroupSelected].peq[i].q));

        //PEQ TYPE
        arrayEqParam[i].type = arrayGroup[groupGroupSelected].peq[i].type;
        var n = arrayGroup[groupGroupSelected].peq[i].type;
        var imgSrc = "./img/peq/peq" + n + ".png";
        var id = "#peqImgNav" + i;
        $(id).attr("src", imgSrc);
        id = "#peqImgSolo" + i;
        $(id).attr("src", imgSrc);
        var dest = "#eqType" + i;
        $(dest).val(n);
    }
    $.fn.drawPEQWidget(i);
}

//XOVER SETUP
$.fn.setDataSoloXover = function(arg, src) {

    highPassEqParam.frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq;
    highPassEqParam.type = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType;

    lowPassEqParam.frequency = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq;
    lowPassEqParam.type = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType;

    switch (arg) {
        //ARG = 0 -> HIGH PASS SET FROM UI
        case 0:
            $.fn.setDataSoloXoverUpdateHP();

            //XOVER SET DRAGGIE POSITION
            $.fn.draggieXOVERSetPosition(0);

            //XOVER SENT COMMAND TO AMPLIFIER
            switch (src) {
                //HP ENA SRC
                case 0:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].xover.hpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].xover.hpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_enable, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_enable, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].xover.hpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].xover.hpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_enable, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_enable, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_xover_hp_enable, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna);
                    break;
                    //HP TYPE SRC
                case 1:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].xover.hpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].xover.hpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_type, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_type, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].xover.hpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].xover.hpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_type, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_type, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_xover_hp_type, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                    break;
                    //HP FREQ SRC
                case 2:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].xover.hpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].xover.hpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_freq, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_freq, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].xover.hpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].xover.hpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_freq, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_hp_freq, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_xover_hp_freq, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq);
                    break;
                default:
                    break;
            }
            break;
            //ARG = 1 -> LOW PASS SET FROM UI
        case 1:
            $.fn.setDataSoloXoverUpdateLP();

            //XOVER SET DRAGGIE POSITION
            $.fn.draggieXOVERSetPosition(1);

            //XOVER SENT COMMAND TO AMPLIFIER
            switch (src) {
                //LP ENA SRC
                case 3:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].xover.lpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].xover.lpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_enable, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_enable, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].xover.lpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].xover.lpEna = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_enable, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_enable, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_xover_lp_enable, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna);
                    break;
                    //LP TYPE SRC
                case 4:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].xover.lpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].xover.lpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_type, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_type, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].xover.lpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].xover.lpType = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_type, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_type, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_xover_lp_type, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
                    break;
                    //LP FREQ SRC
                case 5:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].xover.lpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].xover.lpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_freq, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_freq, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].xover.lpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].xover.lpFreq = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_freq, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_xover_lp_freq, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_xover_lp_freq, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq);
                    break;
                default:
                    break;
            }
            break;
            //ARG = 2 -> HIGH PASS GET FROM WS
        case 2:
            $.fn.setDataSoloXoverUpdateHP();

            //XOVER SET DRAGGIE POSITION
            $.fn.draggieXOVERSetPosition(0);
            break;
            //ARG = 3 -> LOW PASS GET FROM WS
        case 3:
            $.fn.setDataSoloXoverUpdateLP();

            //XOVER SET DRAGGIE POSITION
            $.fn.draggieXOVERSetPosition(1);
            break;
            //ARG = 4 -> HIGH/LOW PASS SET
        case 4:
            $.fn.setDataSoloXoverUpdateHP();
            $.fn.setDataSoloXoverUpdateLP();

            //XOVER SET DRAGGIE POSITION
            $.fn.draggieXOVERSetPosition(0);

            //XOVER SET DRAGGIE POSITION
            $.fn.draggieXOVERSetPosition(1);
            break;
            //ARG = 5 -> HIGH PASS SET FROM DRAGGIE UI
        case 5:
            $.fn.setDataSoloXoverUpdateHP();
            $.fn.sendCommandWS(cmd_set_solo_xover_hp_freq, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq);
            break;
            //ARG = 6 -> LOW PASS SET FROM DRAGGIE UI
        case 6:
            $.fn.setDataSoloXoverUpdateLP();
            $.fn.sendCommandWS(cmd_set_solo_xover_lp_freq, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq);
            break;
            //ARG = 7 -> HIGH PASS SPEAKER PRESET OVERIDE UPDATE
        case 7:
            $.fn.setSpeakerPresetFrequencyUpdate();
            $.fn.sendCommandWS(cmd_get_xover_hp_freq_from_preset, soloAmplifierSelected, "null", "null", soloChannelSelected);
            break;
            //ARG = 8 -> LOW PASS SPEAKER PRESET OVERIDE UPDATE
        case 8:
            $.fn.setSpeakerPresetFrequencyUpdate();
            $.fn.sendCommandWS(cmd_get_xover_lp_freq_from_preset, soloAmplifierSelected, "null", "null", soloChannelSelected);
            break;
            //ARG = 9 -> set speaker preset hp frequency from user UI
        case 9:
            $.fn.sendCommandWS(cmd_set_speaker_xover_hp_freq, soloAmplifierSelected, soloChannelSelected, "null", parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpSpeakerPresetFreq));
            break;
            //ARG = 10 -> set speaker preset lp frequency from user UI
        case 10:
            $.fn.sendCommandWS(cmd_set_speaker_xover_lp_freq, soloAmplifierSelected, soloChannelSelected, "null", parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpSpeakerPresetFreq));
            break;
        default:
            break;
    }
}

$.fn.setSpeakerPresetFrequencyUpdate = function() {
    if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpSpeakerPresetOveride) {
        $("#speakerPresetHPFrequency").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpSpeakerPresetFreq);
        $("#speakerPresetHighPassFrequencySetup").show();
    } else {
        $("#speakerPresetHighPassFrequencySetup").hide();
    }

    if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpSpeakerPresetOveride) {
        $("#speakerPresetLPFrequency").val(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpSpeakerPresetFreq);
        $("#speakerPresetLowPassFrequencySetup").show();
    } else {
        $("#speakerPresetLowPassFrequencySetup").hide();
    }
}

$.fn.setDataSoloXoverUpdateHP = function() {
    let x1 = "#enaToggleHighPassXOVER";
    let x2 = "#freq_HighPassXOVER";
    let x3 = "#sliderHorizontalHighPassXOVER";

    //XOVER HP ENABLE CHECKBOX
    if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true) {
        $(x1).addClass("active");
        $("#dragHighPass").addClass("enable");
        $("#labelHighPass").addClass("enable");
        if (highPassDrag)
            highPassDrag.draggabilly('enable');
    } else {
        $(x1).removeClass("active");
        $("#dragHighPass").removeClass("enable");
        $("#labelHighPass").removeClass("enable");
        if (highPassDrag)
            highPassDrag.draggabilly('disable');
    }

    //XOVER HP FREQUENCY TEXTFIELD
    $(x2).val(parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq));

    //XOVER HP FREQUENCY SLIDER
    $(x3).slider("value", Math.log10(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq)));

    //XOVER HP TYPE
    $("#highPassXOVERLabel").html(xoverLabel[arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType]);
    $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
}

$.fn.setDataSoloXoverUpdateLP = function() {
    let x5 = "#enaToggleLowPassXOVER";
    let x6 = "#freq_LowPassXOVER";
    let x7 = "#sliderHorizontalLowPassXOVER";

    //XOVER LP ENABLE CHECKBOX
    if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true) {
        $(x5).addClass("active");
        $("#dragLowPass").addClass("enable");
        $("#labelLowPass").addClass("enable");
        if (lowPassDrag)
            lowPassDrag.draggabilly('enable');
    } else {
        $(x5).removeClass("active");
        $("#dragLowPass").removeClass("enable");
        $("#labelLowPass").removeClass("enable");
        if (lowPassDrag)
            lowPassDrag.draggabilly('disable');
    }

    //XOVER LP FREQUENCY TEXTFIELD
    $(x6).val(parseInt(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq));

    //XOVER LP FREQUENCY SLIDER
    $(x7).slider("value", Math.log10(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq)));

    //XOVER LP TYPE
    $("#lowPassXOVERLabel").html(xoverLabel[arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType]);
    $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
}

//LIMITER SETUP
$.fn.setDataSoloLimiter = function(arg, src) {
    switch (arg) {
        //UPADTE LIMITER FROM UI
        case 0:
            $.fn.setDataSoloLimiterUpdate();
            switch (src) {
                //RMS THRESHOLD SRC
                case 0:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, soloChannelSelected, "null", getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0));
                    break;
                    //RMS ATTACK SRC
                case 1:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack);
                    break;
                    //RMS RELEASE SRC
                case 2:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_lim_rms_release, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease);
                    break;
                    //PEAK THRESHOLD SRC
                case 3:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, soloChannelSelected, "null", getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1));
                    break;
                    //PEAK RELEASE SRC
                case 4:
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0)
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2)
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        else
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        var arrayCmd = new Array();
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    $.fn.sendCommandWS(cmd_set_solo_lim_peak_release, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease);
                    break;
                    //CALCULATOR RMS SRC
                case 5:
                    var arrayCmd = new Array();
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0) {
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        } else {
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        }
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2) {
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        } else {
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.rmsThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres;
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.rmsAttack = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack;
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.rmsRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease;
                        }
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres / 2), 0)));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_thres, soloAmplifierSelected, soloChannelSelected, "null", getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres, 0)));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_attack, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_rms_release, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));
                    $.fn.sendCommandsWS(arrayCmd);
                    break;
                    //CALCULATOR PEAK SRC
                case 6:
                    var arrayCmd = new Array();
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (soloChannelSelected === 0 || soloChannelSelected === 1)) {
                        if (soloChannelSelected === 0) {
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                            arrayAmplifier[soloAmplifierSelected].channel[1].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        } else {
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                            arrayAmplifier[soloAmplifierSelected].channel[0].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        }
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 0, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 1, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 0, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 1, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (soloChannelSelected === 2 || soloChannelSelected === 3)) {
                        if (soloChannelSelected === 2) {
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                            arrayAmplifier[soloAmplifierSelected].channel[3].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        } else {
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.peakThres = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres;
                            arrayAmplifier[soloAmplifierSelected].channel[2].limiter.peakRelease = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease;
                        }
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1))));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 2, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        // arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, 3, "null", (getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres / 2), 1)));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 2, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, 3, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                        $.fn.sendCommandsWS(arrayCmd);
                        break;
                    }
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_thres, soloAmplifierSelected, soloChannelSelected, "null", getThresholdInDb(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres, 1)));
                    arrayCmd.push($.fn.getCommandFromArgs(cmd_set_solo_lim_peak_release, soloAmplifierSelected, soloChannelSelected, "null", arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
                    $.fn.sendCommandsWS(arrayCmd);
                    break;
                default:
                    break;
            }
            break;
            //UPADATE FROM WS
        case 1:
            $.fn.setDataSoloLimiterUpdate();
            break;
    }
}

function getThresholdInDb(volt, lim) {
    var ret = 0.0;
    if (lim === 0) {
        if (volt === 130)
            ret = 5.3;
        else
            ret = (20 * Math.log10(volt)) - 37;
    } else {
        if (volt === 180)
            ret = 4.1;
        else
            ret = (20 * Math.log10(volt)) - 41;
    }
    return parseFloat(ret.toFixed(1));
}

function getThresholdInVolt(db, lim) {
    var ret = 0.0;
    if (lim === 0) {
        if (db === 5.3)
            ret = 130;
        else
            ret = Math.pow(10, ((db + 37) / 20));
    } else {
        if (db === 4.1)
            ret = 180;
        else
            ret = Math.pow(10, ((db + 41) / 20));
    }
    return parseFloat(ret.toFixed(1));
}

$.fn.setDataSoloLimiterUpdate = function() {
    //RMS THRESHOLD
    $("#thresRmsSoloLimiterInput").val(parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres).toFixed(1)));
    $("#thresRmsSoloLimiterSlider").slider('value', arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres);

    //RMS ATTACK
    $("#attackRmsSoloLimiterInput").val(parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack).toFixed(1)));
    $("#attackRmsSoloLimiterSlider").slider('value', Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack));

    //RMS RELEASE
    $("#releaseRmsSoloLimiterInput").val(parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease).toFixed(1)));
    $("#releaseRmsSoloLimiterSlider").slider('value', Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease));

    //PEAK THRESHOLD
    $("#thresPeakSoloLimiterInput").val(parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres).toFixed(1)));
    $("#thresPeakSoloLimiterSlider").slider('value', arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres);

    //PEAK RELEASE
    $("#releasePeakSoloLimiterInput").val(parseFloat(parseFloat(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease).toFixed(1)));
    $("#releasePeakSoloLimiterSlider").slider('value', Math.log10(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease));
}

//OUTPUT SETUP
$.fn.setDataSoloOutput = function(output) {
    // if (discoveryList[soloAmplifierSelected].model === "CP354" || discoveryList[soloAmplifierSelected].model === "CP704") {
    $.fn.setDataSoloOutputUpdate();
    var arrayCmd = new Array();
    switch (output) {
        case 0:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge12 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_12, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_12, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 1:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge34 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_34, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_34, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 2:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge56 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_56, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_56, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 3:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge78 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_78, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_78, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 4:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge910 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_910, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_910, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 5:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1112 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_1112, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_1112, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 6:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1314 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_1314, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_1314, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 7:
            if (arrayAmplifier[soloAmplifierSelected].bridge.bridge1516 === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_1516, soloAmplifierSelected, 1, "null", "null"));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_bridge_mode_1516, soloAmplifierSelected, 0, "null", "null"));
            break;
        case 8:
            if (arrayAmplifier[soloAmplifierSelected].amp_stage_disabled === true)
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_amp_stage_disable, soloAmplifierSelected, "null", "null", true));
            else
                arrayCmd.push($.fn.getCommandFromArgs(cmd_set_amp_stage_disable, soloAmplifierSelected, "null", "null", false));
            break;
        default:
            break;
    }
    $.fn.sendCommandsWS(arrayCmd);
    // }
}

//UPDATE OUTPUT PANEL IN SETTINGS
$.fn.setDataSoloOutputUpdate = function() {
    //HiZ Filter Area
    $("#hiZFilterTabContent").html("")
    if ($.fn.getModel() > 0 && $.fn.getModel() < 5) {
        $("#hiZFilterTabContent").append($("<h1>").prop({ className: "page-header", innerHTML: "70/100V Mode" }));
        $("#hiZFilterTabContent").append($("<div>").prop({ id: "hiZContent", className: "row justify-content-md-center" }));
        $("#hiZContent").append($("<div>").prop({ id: "hiZContainer", className: "container" }));
        $("#hiZContainer").append($("<div>").prop({ id: "hiZContainerRow", className: "row" }));
        for (var i = 0; i < channelCount; i++) {
            let idDiv1 = "hiZDiv" + i;
            $("#hiZContainerRow").append($("<div>").prop({ id: idDiv1, className: "col outputChannelArea d-flex justify-content-center" }));
            let labelContent = "CH-" + labelOverviewChannel[i];
            $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelTitle", innerHTML: labelContent }));
            let idButton1 = "hiZEnableButton" + i;
            $("#" + idDiv1).append($("<button>").prop({ id: idButton1, className: "hiZButton", innerHTML: "Enable" }));
            $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelInfoEnable", innerHTML: "HPF 100Hz" }))
        }
        $("#hiZContainer").append($("<div>").prop({ className: "groupAssignSpacer" }));
    }
    if ($.fn.getModel() == 7 || $.fn.getModel() == 8) {
        // console.log("model 7")
        $("#hiZFilterTabContent").append($("<h1>").prop({ className: "page-header", innerHTML: "70/100V Mode" }));
        $("#hiZFilterTabContent").append($("<div>").prop({ id: "hiZContent", className: "row justify-content-md-center" }));
        $("#hiZContent").append($("<div>").prop({ id: "hiZContainer", className: "container" }));
        var rowId1 = "hiZContainerRow0"
        var j = 0;
        for (var i = 0; i < channel16Count; i++) {
            if (i % 4 == 0) {
                rowId1 = "hiZContainerRow" + j
                $("#hiZContainer").append($("<div>").prop({ id: rowId1, className: "row" }));
                j++;
            }
            let idDiv1 = "hiZDiv" + i;
            $("#" + rowId1).append($("<div>").prop({ id: idDiv1, className: "col outputChannelArea d-flex justify-content-center" }));
            let labelContent = "CH-" + labelOverviewChannel[i];
            $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelTitle", innerHTML: labelContent }));
            let idButton1 = "hiZEnableButton" + i;
            $("#" + idDiv1).append($("<button>").prop({ id: idButton1, className: "hiZButton", innerHTML: "Enable" }));
            $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelInfoEnable", innerHTML: "HPF 100Hz" }));
        }
        $("#hiZContainer").append($("<div>").prop({ className: "groupAssignSpacer" }));
    }
    $.fn.setDataSoloHiZ(0, 100);

    //Bridge Mode Area
    $("#bridgeTabContent").html("")
    if ($.fn.getModel() == 1 || $.fn.getModel() == 2) {
        $("#bridgeTabContent").append($("<h1>").prop({ className: "page-header", innerHTML: "Bridge Mode" }));
        $("#bridgeTabContent").append($("<div>").prop({ id: "bridgeContent", className: "row justify-content-md-center" }));
        $("#bridgeContent").append($("<div>").prop({ id: "bridgeContainer", className: "container" }));
        var rowId1 = "bridgeContainerRow0"
        var j = 0;
        for (var i = 0; i < channelCount / 2; i++) {
            if (i % 4 == 0) {
                rowId1 = "bridgeContainerRow" + j
                $("#bridgeContainer").append($("<div>").prop({ id: rowId1, className: "row" }));
                j++;
            }
            let idDiv1 = "brigdeDiv" + i;
            $("#" + rowId1).append($("<div>").prop({ id: idDiv1, className: "col outputChannelArea d-flex justify-content-center" }));
            let labelContent = "CH " + labelBridgeOverviewChannel[i];
            $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelTitle", innerHTML: labelContent }));
            let idButton1 = "bridge" + idBridgeChannel[i] + "Button";
            $("#" + idDiv1).append($("<button>").prop({ id: idButton1, className: "bridgeButton", innerHTML: "Enable" }));
            let wiringContent = "Channels (+) (-)"
            let idInfo1 = "outputBridgeChannelInfoEnable bridgeWiring" + idBridgeChannel[i];
            $("#" + idDiv1).append($("<div>").prop({ className: idInfo1, innerHTML: wiringContent }));
        }
        $("#bridgeContainer").append($("<div>").prop({ className: "groupAssignSpacer" }));
    }
    if ($.fn.getModel() == 7 || $.fn.getModel() == 8) {
        $("#bridgeTabContent").append($("<h1>").prop({ className: "page-header", innerHTML: "Bridge Mode" }));
        $("#bridgeTabContent").append($("<div>").prop({ id: "bridgeContent", className: "row justify-content-md-center" }));
        $("#bridgeContent").append($("<div>").prop({ id: "bridgeContainer", className: "container" }));
        var rowId1 = "bridgeContainerRow0"
        var j = 0;
        for (var i = 0; i < channel16Count / 2; i++) {
            if (i % 4 == 0) {
                rowId1 = "bridgeContainerRow" + j
                $("#bridgeContainer").append($("<div>").prop({ id: rowId1, className: "row" }));
                j++;
            }
            let idDiv1 = "brigdeDiv" + i;
            $("#" + rowId1).append($("<div>").prop({ id: idDiv1, className: "col outputChannelArea d-flex justify-content-center" }));
            let labelContent = "CH " + labelBridgeOverviewChannel[i];
            $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelTitle", innerHTML: labelContent }));
            let idButton1 = "bridge" + idBridgeChannel[i] + "Button";
            $("#" + idDiv1).append($("<button>").prop({ id: idButton1, className: "bridgeButton", innerHTML: "Enable" }));
            let wiringContent = "Channels (+) (-)"
            let idInfo1 = "outputBridgeChannelInfoEnable bridgeWiring" + idBridgeChannel[i];
            $("#" + idDiv1).append($("<div>").prop({ className: idInfo1, innerHTML: wiringContent }));
        }
        $("#bridgeContainer").append($("<div>").prop({ className: "groupAssignSpacer" }));
    }


    //Amplifier stage power Area
    $("#powerAmpStageTabContent").html("")
    $("#powerAmpStageTabContent").append($("<h1>").prop({ className: "page-header", innerHTML: "Amplifier Stage Power" }));
    $("#powerAmpStageTabContent").append($("<div>").prop({ id: "stageContent", className: "row justify-content-md-center" }));
    $("#stageContent").append($("<div>").prop({ id: "stageContainer", className: "container" }));
    let idDiv1 = "stageDiv1";
    $("#stageContainer").append($("<div>").prop({ id: idDiv1, className: "col outputChannelArea d-flex justify-content-center" }));
    let labelContent = "Amplifier stage Power Supply";
    $("#" + idDiv1).append($("<div>").prop({ className: "outputChannelTitle", innerHTML: labelContent }));
    let idButton1 = "powerStageButton";
    $("#" + idDiv1).append($("<button>").prop({ id: idButton1, className: "powerStageButton", innerHTML: "ON" }));
    // let wiringContent = "+/- 3 seconds to turn ON"
    // let idInfo1 = "outputBridgeChannelInfoEnable";
    // $("#" + idDiv1).append($("<div>").prop({ className: idInfo1, innerHTML: wiringContent }));
    $("#stageContainer").append($("<div>").prop({ className: "groupAssignSpacer" }));

    $.fn.setVisualBridge();
    $.fn.setVisualAmpStagePower();
}

$.fn.setDataSoloHiZ = function(arg, src) {
    if (src == 0) {
        $.fn.sendCommandWS(cmd_set_hiz_filter, soloAmplifierSelected, Number(arg), "null", arrayAmplifier[soloAmplifierSelected].hiZ[Number(arg)]);
        $.fn.setDataSoloHiZUpdate(arg);
    } else if (src == 1) {
        $.fn.setDataSoloHiZUpdate(arg);
    } else if (src == 100) {
        for (var i = 0; i < channel16Count; i++) {
            $.fn.setDataSoloHiZUpdate(i);
        }
    }
}

//STATUS PANEL IN SETTINGS
$.fn.setDataSoloStatusPanel = function() {
    $("#StatusTabContent").html("")
    $("#StatusTabContent").append($("<h2>").prop({ className: "page-header", innerHTML: "Temperature" }));

    //TEMPERATURE

    //CP354 - CP704 - CP Amp Plate
    if ($.fn.getModel() < 3 || $.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        let idDiv1 = "module1";
        let labelContent = "Amplifier Module : ";
        $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
        let idTempSpan = "tempModule1";
        let content = readBackStatus[soloAmplifierSelected][0][0] + " °C";
        if (readBackStatus[soloAmplifierSelected][0][0] < moduleTempGood) {
            $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-success", innerHTML: content }));
        } else if (readBackStatus[soloAmplifierSelected][0][0] < moduleTempWarning) {
            $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-warning", innerHTML: content }));
        } else if (readBackStatus[soloAmplifierSelected][0][0] >= moduleTempWarning) {
            $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-danger", innerHTML: content }));
        }
    } else if ($.fn.getModel() == 3) {
        for (var i = 0; i < moduleCount / 2; i++) {
            let idDiv1 = "module" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idTempSpan = "tempModule" + (i + 1);
            let content = readBackStatus[soloAmplifierSelected][i][0] + " °C";
            if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempGood) {
                $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-success", innerHTML: content }));
            } else if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempWarning) {
                $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-warning", innerHTML: content }));
                //moduleTempDanger
            } else {
                // } else if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempDanger) {
                $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-danger", innerHTML: content }));
            }
        }
    } else if ($.fn.getModel() == 4 || $.fn.getModel() == 7 || $.fn.getModel() == 8) {
        for (var i = 0; i < moduleCount; i++) {
            let idDiv1 = "module" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idTempSpan = "tempModule" + (i + 1);
            let content = readBackStatus[soloAmplifierSelected][i][0] + " °C";
            if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempGood) {
                $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-success", innerHTML: content }));
            } else if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempWarning) {
                $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-warning", innerHTML: content }));
                //moduleTempDanger
            } else {
                // } else if (readBackStatus[soloAmplifierSelected][i][0] < moduleTempDanger) {
                $("#" + idDiv1).append($("<span>").prop({ id: idTempSpan, className: "badge badge-pill badge-danger", innerHTML: content }));
            }
        }
    }
    $("#tempStatusContainer").append($("<div>").prop({ className: "groupAssignSpacer" }));

    $("#StatusTabContent").append($("<div>").prop({ className: "groupAssignSpacer" }));
    $("#StatusTabContent").append($("<h2>").prop({ className: "page-header", innerHTML: "Active" }));


    //AMPLIFIER STAGE STATUS

    //CP354 - CP704 - CP Amp Plate
    if ($.fn.getModel() < 3 || $.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        let idDiv1 = "moduleStage1";
        let labelContent = "Amplifier Module : ";
        $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
        let idStageSpan = "stageModule1";
        if (readBackStatus[soloAmplifierSelected][0][1] == 0) {
            $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-light", innerHTML: "OFF" }));
        } else {
            $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: "ON" }));
        }
    } else if ($.fn.getModel() == 3) {
        for (var i = 0; i < moduleCount / 2; i++) {
            let idDiv1 = "moduleStage" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idStageSpan = "stageModule" + (i + 1);
            if (readBackStatus[soloAmplifierSelected][i][1] == 0) {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-light", innerHTML: "OFF" }));
            } else {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: "ON" }));
            }
        }
    } else if ($.fn.getModel() == 4 || $.fn.getModel() == 7 || $.fn.getModel() == 8) {
        for (var i = 0; i < moduleCount; i++) {
            let idDiv1 = "moduleStage" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idStageSpan = "stageModule" + (i + 1);
            if (readBackStatus[soloAmplifierSelected][i][1] == 0) {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-light", innerHTML: "OFF" }));
            } else {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: "ON" }));
            }
        }
    }


    $("#StatusTabContent").append($("<div>").prop({ className: "groupAssignSpacer" }));
    $("#StatusTabContent").append($("<h2>").prop({ className: "page-header", innerHTML: "Module Status" }));

    //OVERTEMP PROTECTION

    //CP354 - CP704 - CP Amp Plate
    if ($.fn.getModel() < 3 || $.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        let idDiv1 = "ovpStage1";
        let labelContent = "Amplifier Module : ";
        $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
        let idStageSpan = "ovpModule1";
        if (readBackStatus[soloAmplifierSelected][0][2] == 0) {
            $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: "OK" }));
        } else {
            $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-danger", innerHTML: "OTP" }));
        }
    } else if ($.fn.getModel() == 3) {
        for (var i = 0; i < moduleCount / 2; i++) {
            let idDiv1 = "ovpStage" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idStageSpan = "ovpModule" + (i + 1);
            if (readBackStatus[soloAmplifierSelected][i][2] == 0) {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: "OK" }));
            } else {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-danger", innerHTML: "OTP" }));
            }
        }
    } else if ($.fn.getModel() == 4 || $.fn.getModel() == 7 || $.fn.getModel() == 8) {
        for (var i = 0; i < moduleCount; i++) {
            let idDiv1 = "ovpStage" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idStageSpan = "ovpModule" + (i + 1);
            if (readBackStatus[soloAmplifierSelected][i][2] == 0) {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: "OK" }));
            } else {
                $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-danger", innerHTML: "OTP" }));
            }
        }
    }

    //INPUT VOLTAGE
    $("#StatusTabContent").append($("<div>").prop({ className: "groupAssignSpacer" }));
    $("#StatusTabContent").append($("<h2>").prop({ className: "page-header", innerHTML: "Main Voltage" }));
    //CP354 - CP704 - CP Amp Plate
    if ($.fn.getModel() < 3 || $.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
        let idDiv1 = "inputVoltage1";
        let labelContent = "Amplifier Module : ";
        $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
        let idStageSpan = "inputVoltageModule1";
        $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: readBackStatus[soloAmplifierSelected][0][3] + "V" }));

    } else if ($.fn.getModel() == 3) {
        for (var i = 0; i < moduleCount / 2; i++) {
            let idDiv1 = "inputVoltage" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idStageSpan = "inputVoltageModule" + (i + 1);
            $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: readBackStatus[soloAmplifierSelected][i][3] + "V" }));

        }
    } else if ($.fn.getModel() == 4 || $.fn.getModel() == 7 || $.fn.getModel() == 8) {
        for (var i = 0; i < moduleCount; i++) {
            let idDiv1 = "inputVoltage" + (i + 1);
            let labelContent = "Amplifier Module " + (i + 1) + " : ";
            $("#StatusTabContent").append($("<div>").prop({ id: idDiv1, className: "page-header", innerHTML: labelContent }));
            let idStageSpan = "inputVoltageModule" + (i + 1);
            $("#" + idDiv1).append($("<span>").prop({ id: idStageSpan, className: "badge badge-pill badge-success", innerHTML: readBackStatus[soloAmplifierSelected][i][3] + "V" }));
        }
    }

}

//UPDATE HIZ BUTTON STATUS
$.fn.setDataSoloHiZUpdate = function(i) {
    var id = "#hiZEnableButton" + i;
    if (arrayAmplifier[soloAmplifierSelected].hiZ[i]) {
        $(id).addClass("active");
    } else {
        $(id).removeClass("active");
    }

}

//SPEAKER SETUP
$.fn.setDataSoloSpeaker = function(arg) {
    //SET SPEAKER PRESET
    if (arg < 99) {
        //SET SPEAKER PRESET
        var cmd = "\"";
        cmd += soloFolderSpeakerSelected + "\\" + soloFileSpeakerSelected;
        cmd += "\"";
        if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
            $.fn.sendCommandWS(cmd_set_all_speaker_preset_file, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + "/" + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name, soloChannelSelected, "null");
        } else {
            $.fn.sendCommandWS(cmd_set_speaker_preset_file, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].name + "/" + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[soloFileSpeakerSelected].name, soloChannelSelected, "null");
        }
    } else if (arg === 99) {
        //GET THE FOLDERS LIST FROM THE AMPLIFIER
        if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
            $.fn.sendCommandWS(cmd_get_all_speaker_preset_list_names, soloAmplifierSelected, "null", "null", "null");
        } else {
            $.fn.sendCommandWS(cmd_get_speaker_preset_list_names, soloAmplifierSelected, "null", "null", "null");
        }
    } else if (arg === 100) {
        //JUST UPDATE THE SPEAKER PRESET LIST
        $.fn.setDataSoloSpeakerUpdate();
    } else if (arg === 101) {
        var arrCmd = new Array();
        for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderCount; i++) {
            if ($.fn.getModel() == 5 || $.fn.getModel() == 6 || $.fn.getModel() == 9) {
                arrCmd.push($.fn.getCommandFromArgs(cmd_get_all_speaker_preset_file_names, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[i].name, "null", "null"));
            } else {
                arrCmd.push($.fn.getCommandFromArgs(cmd_get_speaker_preset_file_names, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[i].name, "null", "null"));
            }
        }
        $.fn.sendCommandsWS(arrCmd);
    }
}

$.fn.setDataSoloSpeakerUpdate = function() {
    //GENERATE FOLDER LIST
    var str = "";
    var i_folder = -1;
    var path = arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].preset.split("/");
    $("#fileListSpeaker").html(str);
    //HEADER OF THE ASSIGN GROUP TAB TABLE
    str += "<thead><tr><th>Speaker Folder</th></tr></thead>";
    str += "<tbody>"

    for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderCount; i++) {
        if (i === soloFolderSpeakerSelected)
            str += "<tr class=\"active\">";
        else
            str += "<tr>";
        str += "<td id=\"folderListIndex" + i + "\" colspan=\"1\">"
        str += "<label id=\"folderListTab" + i + "\">" + arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[i].name + "</label>";
        str += "</td>";
        str += "</tr>";
        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[i].name.localeCompare(path[0]) === 0)
            i_folder = i;
    }
    str += "</tbody>"

    $("#folderListSpeaker").html(str);

    //GENERATE FILE LIST
    var str = "";
    str += "<thead><tr><th>Speaker File</th></tr></thead>";
    str += "<tbody>"

    for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileCount; i++) {
        let name = "";
        if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[i].protected === true) {
            name = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[i].name + " (OEM)";
        } else {
            name = arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[i].name;
        }
        if (i === soloFileSpeakerSelected)
            str += "<tr class=\"active\">";
        else
            str += "<tr>";
        if (i_folder > -1) {
            if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[i].name)
                if (arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[soloFolderSpeakerSelected].fileList[i].name.localeCompare(path[1]) === 0)
                    name = ">" + name + "<";
        }
        str += "<td id=\"fileListIndex" + i + "\" colspan=\"1\">"
        str += "<label id=\"fileListTab" + i + "\">" + name + "</label>";
        str += "</td>";
        str += "</tr>";
    }
    str += "</tbody>"
    $("#fileListSpeaker").html(str);
    $.fn.setSpeakerPresetFrequencyUpdate();
}

//ASSIGN CHANNEL TO GROUP
$.fn.setDataGroupAssign = function(src, ampSrc, chaSrc, grSrc) {
    switch (src) {
        case 0:
            //SOURCE FROM WEBSOCKET
            $.fn.setDataGroupAssignUpdate(ampSrc, chaSrc, 99);
            break;
        case 1:
            //SOURCE FROM WEBUI            
            var arrCmd = new Array();
            if (arrayAmplifier[ampSrc].channel[chaSrc].group[grSrc] === 1) {
                if (arrayGroupData[ampSrc][grSrc].gain.muteEna != arrayGroup[grSrc].gain.muteEna)
                    arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_mute, ampSrc, grSrc, "null", arrayGroup[grSrc].gain.muteEna))
                if (arrayGroupData[ampSrc][grSrc].gain.gain != arrayGroup[grSrc].gain.gain)
                    arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_gain, ampSrc, grSrc, "null", arrayGroup[grSrc].gain.gain))
                if (arrayGroupData[ampSrc][grSrc].gain.polarityEna != arrayGroup[grSrc].gain.polarityEna)
                    arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_polarity, ampSrc, grSrc, "null", arrayGroup[grSrc].gain.polarityEna))
                if (arrayGroupData[ampSrc][grSrc].delay.delayEna != arrayGroup[grSrc].delay.delayEna)
                    arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_delay_enable, ampSrc, grSrc, "null", arrayGroup[grSrc].delay.delayEna))
                if (arrayGroupData[ampSrc][grSrc].delay.delay != arrayGroup[grSrc].delay.delay)
                    arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_delay_value, ampSrc, grSrc, "null", arrayGroup[grSrc].delay.delay))
                for (var i = 0; i < peqCount; i++) {
                    var peqCopyCommand = new Object();
                    var updatable = 0;
                    if (arrayGroupData[ampSrc][grSrc].peq[i].ena != arrayGroup[grSrc].peq[i].ena) {
                        updatable++;
                    }
                    if (arrayGroupData[ampSrc][grSrc].peq[i].type != arrayGroup[grSrc].peq[i].type) {
                        updatable++;
                    }
                    if (arrayGroupData[ampSrc][grSrc].peq[i].frequency != arrayGroup[grSrc].peq[i].frequency) {
                        updatable++;
                    }
                    if (arrayGroupData[ampSrc][grSrc].peq[i].gain != arrayGroup[grSrc].peq[i].gain) {
                        updatable++;
                    }
                    if (arrayGroupData[ampSrc][grSrc].peq[i].q != arrayGroup[grSrc].peq[i].q) {
                        updatable++;
                    }

                    if (updatable > 0) {
                        peqCopyCommand.ena = arrayGroup[grSrc].peq[i].ena;
                        peqCopyCommand.type = arrayGroup[grSrc].peq[i].type;
                        peqCopyCommand.frequency = arrayGroup[grSrc].peq[i].frequency;
                        peqCopyCommand.gain = arrayGroup[grSrc].peq[i].gain;
                        peqCopyCommand.q = arrayGroup[grSrc].peq[i].q;

                        var peqCopyCommandTxt = JSON.stringify(peqCopyCommand);
                        let resultTxt = peqCopyCommandTxt.replaceAll("\"", "\\\"");
                        arrCmd.push($.fn.getCommandFromArgs(cmd_set_group_peq, ampSrc, grSrc, i, resultTxt));
                    }
                }
            }
            // arrCmd.push($.fn.getCommandFromArgs(cmd_set_assign_channel_to_group, ampSrc, chaSrc, grSrc, arrayAmplifier[ampSrc].channel[chaSrc].group[grSrc]));
            if (arrCmd.length > 0) {
                $.fn.sendCommandsWS(arrCmd);
            }

            $.fn.sendCommandWS(cmd_set_assign_channel_to_group, ampSrc, chaSrc, grSrc, arrayAmplifier[ampSrc].channel[chaSrc].group[grSrc]);
            $.fn.setDataGroupAssignUpdate(ampSrc, chaSrc, grSrc);

            break;
        default:
            break;
    }
}

//ASSIGN CHANNEL UPDATE TO GROUP
$.fn.setDataGroupAssignUpdate = function(ampSrc, chaSrc, grSrc) {
    var dest = "#GABtnCh" + chaSrc + "Gr" + grSrc;

    // var ampIndex = parseInt(amplifierFinder(arrayAmplifier, $("#groupAssignAmpSelectedName").text()));
    var tabId = "#groupAssignGroupAmp" + ampSrc + "Channel" + chaSrc + "Group" + grSrc;

    //SET VALUE FROM THE WEBSOCKET
    if (grSrc === 99) {
        for (var i = 0; i < groupCount; i++) {
            dest = "#GABtnCh" + chaSrc + "Gr" + i;
            tabId = "#groupAssignGroupAmp" + ampSrc + "Channel" + chaSrc + "Group" + i;

            if (arrayAmplifier[ampSrc].channel[chaSrc].group[i] === 1) {
                if (ampSrc === groupAssignAmplifierSelected)
                    $(dest).addClass("active");
                $(tabId).removeClass("dotEnable");
                $(tabId).removeClass("dot");
                $(tabId).addClass("dotEnable");
            } else {
                if (ampSrc === groupAssignAmplifierSelected)
                    $(dest).removeClass("active");
                $(tabId).removeClass("dotEnable");
                $(tabId).removeClass("dot");
                $(tabId).addClass("dot");
            }
        }
    } else {
        if (arrayAmplifier[ampSrc].channel[chaSrc].group[grSrc] === 1) {
            if (ampSrc === groupAssignAmplifierSelected)
                $(dest).addClass("active");
            $(tabId).removeClass("dotEnable");
            $(tabId).removeClass("dot");
            $(tabId).addClass("dotEnable");
        } else {
            if (ampSrc === groupAssignAmplifierSelected)
                $(dest).removeClass("active");
            $(tabId).removeClass("dotEnable");
            $(tabId).removeClass("dot");
            $(tabId).addClass("dot");
        }
    }
}

function returnGroupRegistration(ampId) {
    var result = 0;
    let amountOfChannel = channelCount;
    switch ($.fn.getModel(ampId)) {
        case 9:
            amountOfChannel = 3
            break;
        case 8:
            amountOfChannel = channel16Count;
            break;
        case 7:
            amountOfChannel = channel16Count;
            break;
        case 6:
            amountOfChannel = 1;
            break;
        case 5:
            amountOfChannel = 1;
            break;
        default:
            amountOfChannel = channelCount;
            break;
    }
    for (var i = 0; i < amountOfChannel; i++) {
        $.each(arrayAmplifier[ampId].channel[i].group, function() { result += parseFloat(this) || 0; });
    }
    // $.each(arrayAmplifier[ampId].channel[0].group, function() { result += parseFloat(this) || 0; });
    // $.each(arrayAmplifier[ampId].channel[1].group, function() { result += parseFloat(this) || 0; });
    // $.each(arrayAmplifier[ampId].channel[2].group, function() { result += parseFloat(this) || 0; });
    // $.each(arrayAmplifier[ampId].channel[3].group, function() { result += parseFloat(this) || 0; });
    return result;
}

function returnGroupGroupRegistration(ampId, groupId) {
    var result = 0;
    let amountOfChannel = channelCount;
    switch ($.fn.getModel(ampId)) {
        case 9:
            amountOfChannel = channel3Count;
            break;
        case 8:
            amountOfChannel = channel16Count;
            break;
        case 7:
            amountOfChannel = channel16Count;
            break;
        case 6:
            amountOfChannel = 1;
            break;
        case 5:
            amountOfChannel = 1;
            break;
        default:
            amountOfChannel = channelCount;
            break;
    }
    for (var i = 0; i < amountOfChannel; i++) {
        result += arrayAmplifier[ampId].channel[i].group[groupId];
    }
    return result;
}

//GAIN SETUP GROUP
$.fn.setDataGroupGain = function(arg, src) {
    if (arg < 99) {
        $.fn.setDataGroupGainUpdate();
        switch (src) {
            case 0:
                for (var i = 0; i < arrayAmplifier.length; i++) {
                    if (returnGroupGroupRegistration(i, groupGroupSelected) > 0 || i === 0) {
                        var arrCmd = new Array();
                        arrCmd.push(this.getCommandFromArgs(cmd_set_group_mute, i, groupGroupSelected, "null", arrayGroup[groupGroupSelected].gain.muteEna));
                        $.fn.sendCommandsWS(arrCmd);
                    }
                }
                break;
            case 1:
                for (var i = 0; i < arrayAmplifier.length; i++) {
                    if (returnGroupGroupRegistration(i, groupGroupSelected) > 0 || i === 0) {
                        $.fn.sendCommandWS(cmd_set_group_gain, i, groupGroupSelected, "null", arrayGroup[groupGroupSelected].gain.gain);
                    }
                }
                break;
            case 2:
                for (var i = 0; i < arrayAmplifier.length; i++) {
                    if (returnGroupGroupRegistration(i, groupGroupSelected) > 0 || i === 0) {
                        var arrCmd = new Array();
                        arrCmd.push(this.getCommandFromArgs(cmd_set_group_polarity, i, groupGroupSelected, "null", arrayGroup[groupGroupSelected].gain.polarityEna));
                        $.fn.sendCommandsWS(arrCmd);
                    }
                }
                break;
            default:
                break;
        }
    } else {
        $.fn.setDataGroupGainUpdate();
    }
}

$.fn.setDataGroupGainUpdate = function() {
    let g1 = "#gainGroup";
    let g2 = "#sliderVerticalGainGroup";
    let g3 = ".itemQuarterGroupButtonMute";
    let g4 = ".itemQuarterGroupButtonPhase";
    //GAIN VALUE TEXTFIELD
    $(g1).val(arrayGroup[groupGroupSelected].gain.gain);
    //SLIDER GAIN VALUE
    $(g2).slider("value", arrayGroup[groupGroupSelected].gain.gain);
    //MUTE BUTTON STATUS
    if (arrayGroup[groupGroupSelected].gain.muteEna === true)
        $(g3).addClass("active");
    else
        $(g3).removeClass("active");
    //POLARITY BUTTON STATUS
    if (arrayGroup[groupGroupSelected].gain.polarityEna === true)
        $(g4).addClass("active");
    else
        $(g4).removeClass("active");
}

//DELAY SETUP GROUP
$.fn.setDataGroupDelay = function(arg, src) {
    if (arg < 99) {
        $.fn.setDataGroupDelayUpdate();
        switch (src) {
            case 0:
                for (var i = 0; i < arrayAmplifier.length; i++) {
                    $.fn.sendCommandWS(cmd_set_group_delay_enable, i, groupGroupSelected, "null", arrayGroup[groupGroupSelected].delay.delayEna);
                }
                break;
            case 1:
                for (var i = 0; i < arrayAmplifier.length; i++) {
                    $.fn.sendCommandWS(cmd_set_group_delay_value, i, groupGroupSelected, "null", arrayGroup[groupGroupSelected].delay.delay);
                }
                break;
            default:
                break;
        }
    } else {
        $.fn.setDataGroupDelayUpdate();
    }
}

$.fn.setDataGroupDelayUpdate = function() {
    let d1 = "#delayGroup";
    let d2 = "#sliderVerticalDelayGroup";
    let d3 = ".itemQuarterGroupButtonDelay";
    //DELAY VALUE TEXTFIELD
    $(d1).val(parseFloat(arrayGroup[groupGroupSelected].delay.delay.toFixed(1)));
    //SLIDER DELAY VALUE 
    $(d2).slider("value", Math.log10(parseFloat(arrayGroup[groupGroupSelected].delay.delay)));
    //DELAY BUTTON STATUS
    if (arrayGroup[groupGroupSelected].delay.delayEna === true)
        $(d3).addClass("active");
    else
        $(d3).removeClass("active");
}

$.fn.setDataGroupLabel = function(arg, src) {
    switch (arg) {
        case 0:
            $.fn.setDataGroupLabelUpdate(src);
            break;
        case 1:
            $.fn.setDataGroupLabelUpdate(src);
            for (var i = 0; i < arrayAmplifier.length; i++) {
                $.fn.sendCommandWS(cmd_set_group_name, i, Number(src), "null", arrayGroup[src].label.toString());
            }

            break;
    }
}

$.fn.setDataGroupLabelUpdate = function(src) {
    var t = "#labelGroupButton" + src;
    var txt = "#groupName" + src;
    var dest = "#groupAssignAmpGroupLabel" + src;
    $(t).html(arrayGroup[src].label.substring(0, groupButtonLabelMaxLength));
    $(txt).val(arrayGroup[src].label);
    var tzt = ".registerGroupName" + src;
    $(tzt).text(arrayGroup[src].label);
    $(dest).html(arrayGroup[src].label);
}

//SPEAKER SETUP
$.fn.setDataSoloGlobal = function(arg) {
    //SET SPEAKER PRESET
    if (arg < 99) {
        //SET SPEAKER PRESET
        var cmd = "\"";
        cmd += soloFolderGlobalSelected + "\\" + soloFileGlobalSelected;
        cmd += "\"";
        $.fn.sendCommandWS(cmd_set_global_preset_file, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].name + "/" + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[soloFileGlobalSelected].name, soloChannelSelected);
    } else if (arg === 99) {
        //GET THE FOLDERS LIST FROM THE AMPLIFIER
        $.fn.sendCommandWS(cmd_get_global_preset_folder_names, soloAmplifierSelected, "null", "null", "null");
    } else if (arg === 100) {
        //JUST UPDATE THE SPEAKER PRESET LIST
        $.fn.setDataSoloGlobalUpdate();
    } else if (arg === 101) {
        var arrCmd = new Array();
        for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderGlobal.folderCount; i++) {
            arrCmd.push($.fn.getCommandFromArgs(cmd_get_global_preset_file_names, soloAmplifierSelected, arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[i].name, "null", "null"));
        }
        $.fn.sendCommandsWS(arrCmd);
        $.fn.setDataSoloGlobalUpdate();
    }
}

$.fn.setDataSoloGlobalUpdate = function() {
    //GENERATE FOLDER LIST
    var str = "";
    $("#fileListGlobal").html(str);
    //HEADER OF THE ASSIGN GROUP TAB TABLE
    str += "<thead><tr><th>Preset Folder</th></tr></thead>";
    str += "<tbody>"

    for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList.length; i++) {
        if (i === soloFolderGlobalSelected)
            str += "<tr class=\"active\">";
        else
            str += "<tr>";
        str += "<td id=\"folderListIndex" + i + "\" colspan=\"1\">"
        str += "<label id=\"folderListTab" + i + "\">" + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[i].name + "</label>";
        str += "</td>";
        str += "</tr>";
    }
    str += "</tbody>"

    $("#folderListGlobal").html(str);

    //GENERATE FILE LIST
    var str = "";
    //HEADER OF THE ASSIGN GROUP TAB TABLE
    str += "<thead><tr><th>Preset File</th></tr></thead>";
    str += "<tbody>"

    for (var i = 0; i < arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList.length; i++) {
        if (i === soloFileGlobalSelected)
            str += "<tr class=\"active\">";
        else
            str += "<tr>";
        str += "<td id=\"fileListIndex" + i + "\" colspan=\"1\">"
        str += "<label id=\"fileListTab" + i + "\">" + arrayAmplifier[soloAmplifierSelected].folderGlobal.folderList[soloFolderGlobalSelected].fileList[i].name + "</label>";
        str += "</td>";
        str += "</tr>";
    }
    str += "</tbody>"
    $("#fileListGlobal").html(str);
}

$.fn.getCurrentGroupDelay = function(amp, cha) {
    var currentDelay = 0;
    for (var i = 0; i < groupCount; i++) {
        if (arrayAmplifier[amp].channel[cha].group[i] === 1) {
            if (arrayGroup[i].delay.delayEna) {
                currentDelay += arrayGroup[i].delay.delay;
            }
        }
    }
    return parseFloat(currentDelay.toFixed(1));
}

//CREATE AND INITIALIZE SLIDERS
$.fn.initSlider = function() {
    for (var i = 0; i < 16; i++) {
        // CREATE AND INITIALIZE 4 SLIDERS AND BIND THEM TO THE GAIN TEXTFIELD
        var idSlider = "#sliderVertical" + i;
        var idGain = "#gain" + i;
        $(idSlider).slider({
            orientation: "vertical",
            range: "min",
            min: -80.0,
            max: 15.0,
            step: 0.1,
            slide: function(event, ui) {
                var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
                if (soloChannelSelected != num)
                    $("#overviewButton" + num).trigger("click");

                soloChannelSelected = num;

                // $("#overviewButton" + num).trigger("click");
                arrayAmplifier[soloAmplifierSelected].channel[num].gain.gain = parseFloat(parseFloat(ui.value).toFixed(1));
                $.fn.setDataSoloGain(num, 1);
            }
        });

        // CREATE AND INITIALIZE 4 SLIDERS AND BIND THEM TO THE DELAY TEXTFIELD
        var idSlider = "#sliderDelayVertical" + i;
        var idDelay = "#delay" + i;
        $(idSlider).slider({
            orientation: "vertical",
            range: "min",
            min: 0.0,
            max: Math.log10(delayScaleMax),
            step: 0.00001,
            slide: function(event, ui) {
                var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
                //IF CHANNEL IS NOT YET SELECTED, SELECT IT
                if (soloChannelSelected != num)
                    $("#overviewButton" + num).trigger("click");

                //IF STEREO12 IS ENABLE AND IF SOURCE IS CHANNEL 1 OR 2
                if (arrayAmplifier[soloAmplifierSelected].stereo.stereo12 === true && (num === 0 || num === 1)) {
                    //IF EVENT COMES FROM CHANNEL 1 (0)
                    if (num === 0) {
                        if (ui.value != 0 && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0)) && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1)) && arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna === true) {
                            $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        } else if ((ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0)) || ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1))) && ui.value < Math.log10(delayScaleMax) && arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna === true) {
                            if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 0) > $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1)) {
                                arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 0).addClass("Max");
                            } else {
                                arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 1).addClass("Max");
                            }
                            $.fn.setDataSoloDelay(0, 1);
                            return false;
                        } else if (ui.value === Math.log10(delayScaleMax)) {
                            arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = delayScaleMax;
                            $("#itemQuarterTotalDelay" + num).addClass("Max");
                        } else if (ui.value === 0) {
                            $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = delayScaleMin;
                        } else {
                            $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[0].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        }
                        $.fn.setDataSoloDelay(0, 1);
                    } else {
                        if (ui.value != 0 && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0)) && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1)) && arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna === true) {
                            $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        } else if ((ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0)) || ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1))) && ui.value < Math.log10(delayScaleMax) && arrayAmplifier[soloAmplifierSelected].channel[0].delay.delayEna === true) {
                            if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 0) > $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1)) {
                                arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 0)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 0).addClass("Max");
                            } else {
                                arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 1)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 1).addClass("Max");
                            }
                            $.fn.setDataSoloDelay(1, 1);
                            return false;
                        } else if (ui.value === Math.log10(delayScaleMax)) {
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = delayScaleMax;
                            $("#itemQuarterTotalDelay" + num).addClass("Max");
                        } else if (ui.value === 0) {
                            $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = delayScaleMin;
                        } else {
                            $("#itemQuarterTotalDelay" + 0).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 1).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        }
                        $.fn.setDataSoloDelay(1, 1);
                    }
                    return;
                }

                if (arrayAmplifier[soloAmplifierSelected].stereo.stereo34 === true && (num === 2 || num === 3)) {
                    //IF EVENT COMES FROM CHANNEL 1 (0)
                    if (num === 2) {
                        if (ui.value != 0 && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2)) && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3)) && arrayAmplifier[soloAmplifierSelected].channel[2].delay.delayEna === true) {
                            $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        } else if ((ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2)) || ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3))) && ui.value < Math.log10(delayScaleMax) && arrayAmplifier[soloAmplifierSelected].channel[2].delay.delayEna === true) {
                            if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 2) > $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3)) {
                                arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 2).addClass("Max");
                            } else {
                                arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 3).addClass("Max");
                            }
                            $.fn.setDataSoloDelay(2, 1);
                            return false;
                        } else if (ui.value === Math.log10(delayScaleMax)) {
                            arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = delayScaleMax;
                            $("#itemQuarterTotalDelay" + num).addClass("Max");
                        } else if (ui.value === 0) {
                            $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = delayScaleMin;
                        } else {
                            $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[2].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        }
                        $.fn.setDataSoloDelay(2, 1);
                    } else {
                        if (ui.value != 0 && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2)) && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3)) && arrayAmplifier[soloAmplifierSelected].channel[3].delay.delayEna === true) {
                            $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        } else if ((ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2)) || ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3))) && ui.value < Math.log10(delayScaleMax) && arrayAmplifier[soloAmplifierSelected].channel[3].delay.delayEna === true) {
                            if ($.fn.getCurrentGroupDelay(soloAmplifierSelected, 2) > $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3)) {
                                arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 2)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 2).addClass("Max");
                            } else {
                                arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, 3)).toFixed(2));
                                $("#itemQuarterTotalDelay" + 3).addClass("Max");
                            }
                            $.fn.setDataSoloDelay(3, 1);
                            return false;
                        } else if (ui.value === Math.log10(delayScaleMax)) {
                            arrayAmplifier[soloAmplifierSelected].channel[1].delay.delay = delayScaleMax;
                            $("#itemQuarterTotalDelay" + num).addClass("Max");
                        } else if (ui.value === 0) {
                            $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = delayScaleMin;
                        } else {
                            $("#itemQuarterTotalDelay" + 2).removeClass("Max");
                            $("#itemQuarterTotalDelay" + 3).removeClass("Max");
                            arrayAmplifier[soloAmplifierSelected].channel[3].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                        }
                        $.fn.setDataSoloDelay(3, 1);
                    }
                    return;
                }

                if (ui.value != 0 && ui.value <= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)) && arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna === true) {
                    $("#itemQuarterTotalDelay" + num).removeClass("Max");
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                } else if (ui.value >= Math.log10(delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)) && ui.value < Math.log10(delayScaleMax) && arrayAmplifier[soloAmplifierSelected].channel[num].delay.delayEna === true) {
                    $("#itemQuarterTotalDelay" + num).addClass("Max");
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat((delayScaleMax - $.fn.getCurrentGroupDelay(soloAmplifierSelected, num)).toFixed(2));
                    $.fn.setDataSoloDelay(num, 1);
                    return false;
                } else if (ui.value === Math.log10(delayScaleMax)) {
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMax;
                    $("#itemQuarterTotalDelay" + num).addClass("Max");
                } else if (ui.value === 0) {
                    $("#itemQuarterTotalDelay" + num).removeClass("Max");
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = delayScaleMin;
                } else {
                    $("#itemQuarterTotalDelay" + num).removeClass("Max");
                    arrayAmplifier[soloAmplifierSelected].channel[num].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(2));
                }
                $.fn.setDataSoloDelay(num, 1);
            }
        });
        $(idDelay).val(parseFloat(Math.pow(10, $(idSlider).slider("value")).toFixed(2)));
    }
    for (var i = 0; i < maxMixerInput; i++) {
        // CREATE AND INITIALIZE 4 SLIDERS AND BIND THEM TO THE MIXER TEXTFIELD
        var idSlider = "#sliderMixerVertical" + i;
        $(idSlider).slider({
            orientation: "vertical",
            range: "min",
            min: -80.0,
            max: 15.0,
            step: 0.1,
            slide: function(event, ui) {
                var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].mixer.gain[num] = parseFloat(parseFloat(ui.value).toFixed(1));
                $.fn.setDataSoloMixer(0, num);
            }
        });
    }

    // SLIDER GAIN GROUP
    $("#sliderVerticalGainGroup").slider({
        orientation: "vertical",
        range: "min",
        min: -80.0,
        max: 15.0,
        step: 0.1,
        slide: function(event, ui) {
            arrayGroup[groupGroupSelected].gain.gain = ui.value;
            $.fn.setDataGroupGain(groupGroupSelected, 1);
        }
    });

    // SLIDER DELAY GROUP
    $("#sliderVerticalDelayGroup").slider({
        orientation: "vertical",
        range: "min",
        min: 0.0,
        max: Math.log10(delayScaleMax),
        step: 0.00001,
        slide: function(event, ui) {
            if (ui.value != 0 && ui.value <= Math.log10(delayScaleMax))
                arrayGroup[groupGroupSelected].delay.delay = parseFloat(Math.pow(10, ui.value).toFixed(1));
            else if (ui.value === Math.log10(delayScaleMax))
                arrayGroup[groupGroupSelected].delay.delay = delayScaleMax;
            else if (ui.value === 0)
                arrayGroup[groupGroupSelected].delay.delay = 0;
            $.fn.setDataGroupDelay(groupGroupSelected, 1);
        }
    });

    //SLIDER HIGH PASS XOVER
    $("#sliderHorizontalHighPassXOVER").slider({
        orientation: "horizontal",
        range: "min",
        min: 1,
        max: Math.log10(freqScaleMaxPEQ),
        step: 0.00001,
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq = Math.round(Math.pow(10, ui.value));
            $.fn.setDataSoloXover(0, 2);
        }
    });

    //SLIDER LOW PASS XOVER
    $("#sliderHorizontalLowPassXOVER").slider({
        orientation: "horizontal",
        range: "min",
        min: 1,
        max: Math.log10(freqScaleMaxPEQ),
        step: 0.00001,
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq = Math.round(Math.pow(10, ui.value));
            $.fn.setDataSoloXover(1, 5);
        }
    });

    //SLIDER THRESHOLD RMS STAGE LIMITER
    $("#thresRmsSoloLimiterSlider").slider({
        orientation: "horizontal",
        range: "min",
        min: rmsThresScaleMin,
        max: rmsThresScaleMax,
        step: 0.1,
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsThres = ui.value;
            $.fn.setDataSoloLimiter(0, 0);
        }
    });

    //SLIDER ATTACK RMS STAGE LIMITER
    $("#attackRmsSoloLimiterSlider").slider({
        orientation: "horizontal",
        range: "min",
        min: Math.log10(rmsAttackScaleMin),
        max: Math.log10(rmsAttackScaleMax),
        step: 0.00001,
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsAttack = Math.round(Math.pow(10, ui.value) * 10) / 10;
            $.fn.setDataSoloLimiter(0, 1);
        }
    });

    //SLIDER RELEASE RMS STAGE LIMITER
    $("#releaseRmsSoloLimiterSlider").slider({
        orientation: "horizontal",
        range: "min",
        min: Math.log10(rmsReleaseScaleMin),
        max: Math.log10(rmsReleaseScaleMax),
        step: 0.00001,
        // value: Math.log10(16.0),
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.rmsRelease = Math.round(Math.pow(10, ui.value) * 10) / 10;
            $.fn.setDataSoloLimiter(0, 2);
        }
    });

    //SLIDER THRESHOLD PEAK STAGE LIMITER
    $("#thresPeakSoloLimiterSlider").slider({
        orientation: "horizontal",
        range: "min",
        min: peakThresScaleMin,
        max: peakThresScaleMax,
        step: 0.1,
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakThres = ui.value;
            $.fn.setDataSoloLimiter(0, 3);
        }
    });

    //SLIDER RELEASE PEAK STAGE LIMITER
    $("#releasePeakSoloLimiterSlider").slider({
        orientation: "horizontal",
        range: "min",
        min: Math.log10(peakReleaseScaleMin),
        max: Math.log10(peakReleaseScaleMax),
        step: 0.00001,
        slide: function(event, ui) {
            arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].limiter.peakRelease = Math.round(Math.pow(10, ui.value) * 10) / 10;
            $.fn.setDataSoloLimiter(0, 4);
        }
    });
}

$.fn.initSliderPEQ = function() {
    // SLIDER FREQ PEQ
    for (var i = 0; i < eqCount; i++) {
        var id = "#sliderHorizontalFreqPEQ" + i;
        $(id).slider({
            orientation: "horizontal",
            range: "min",
            min: 1,
            max: Math.log10(freqScaleMaxPEQ),
            step: 0.00001,
            value: 1,
            slide: function(event, ui) {
                var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
                if (displaySoloGroup === 0) {
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency = Math.round(Math.pow(10, ui.value));
                    $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                    $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
                } else
                    arrayGroup[groupGroupSelected].peq[num].frequency = Math.round(Math.pow(10, ui.value));
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 2);
            }
        });
    }

    // SLIDER GAIN PEQ
    for (var i = 0; i < eqCount; i++) {
        var id = "#sliderHorizontalGainPEQ" + i;
        $(id).slider({
            orientation: "horizontal",
            range: "min",
            min: -40.0,
            max: 15.0,
            step: 0.1,
            value: 0,
            slide: function(event, ui) {
                var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
                if (displaySoloGroup === 0) {
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain = ui.value;
                    $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                    $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
                } else
                    arrayGroup[groupGroupSelected].peq[num].gain = ui.value;
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 3);
            }
        });
    }

    // SLIDER Q PEQ
    for (var i = 0; i < eqCount; i++) {
        var id = "#sliderHorizontalQPEQ" + i;
        $(id).slider({
            orientation: "horizontal",
            range: "min",
            min: Math.log10(0.1),
            max: Math.log10(48),
            step: 0.0001,
            value: 2.5,
            slide: function(event, ui) {
                var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
                if (displaySoloGroup === 0) {
                    arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].q = Math.round(Math.pow(10, ui.value) * 100) / 100;
                    $.fn.drawXOVERWidget(0, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpType);
                    $.fn.drawXOVERWidget(1, arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpType);
                } else
                    arrayGroup[groupGroupSelected].peq[num].q = Math.round(Math.pow(10, ui.value) * 100) / 100;
                //SEND DATA TO AMPLIFIER
                $.fn.setDataSoloPEQ(num, 4);
            }
        });
    }
}

//FUNCTION RUN WHEN SIZE OF THE WINDOWS IS UPDATED
$(window).resize(function() {
    // console.log("resize function");
    screenHeight = window.innerHeight;
    screenWidth = window.innerWidth;
    screenScrollHeight = document.documentElement.scrollHeight;

    winHeightFader = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 485;
    winHeightGroupFader = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 400;
    winHeightVuMeter = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 425;

    if (screenHeight < 570) {
        winHeightFader = 104;
        winHeightGroupFader = 170;
        winHeightVuMeter = 150;
        $(".sliderContainer").css("min-height", "80px");

        $(".sliderGroupContainer").css("min-height", "168px");
        $(".sliderContainerGroupBackground").css("min-height", "185px");

        $(".sliderDelayGroupContainer").css("min-height", "170px");
        $(".sliderContainerGroupDelayBackground").css("min-height", "185px");

        $(".sliderDelayContainer").css("min-height", "62px");
        $(".sliderDelayContainer").css("max-height", "62px");
        // $(".sliderDelayContainer").css("min-height", "90px");
        // $(".sliderDelayContainer").css("max-height", "90px");
        // $(".sliderDelayContainerBackground").css("min-height", "88px");
        $(".sliderDelayContainerBackground").css("min-height", "60px");

        $(".itemQuarterVuMeter").css("min-height", "165px");

        $(".gainSoloVuMeter").css("top", "164px");
        $(".gainSoloVuMeter").css("transform", 'scaleY(0)');
        $(".gainSoloVuMeter").css("height", "164px");
        $(".limiterSoloVuMeter").css("top", "366px");
        $(".limiterGRSoloVuMeter").css("height", "327px");
        $(".limiterPeakSoloVuMeter").css("height", "327px");
        $(".limiterSoloVuMeter").css("height", "327px");

        $(".itemQuarterVuMeterBackground").css("min-height", "178px");
        $(".vuMeterRGDivLimiter").css("height", "326px");
        $(".vuMeterPeakDivLimiter").css("height", "326px");
        $(".vuMeterOutputDivLimiter").css("height", "326px");
        $(".outputPanelBackgroundLimiter").css("min-height", "457px");
    } else {
        $(".sliderContainer").css("min-height", "-webkit-calc(100vh - 472px)");
        $(".sliderContainer").css("min-height", "-moz-calc(100vh - 472px)");
        $(".sliderContainer").css("min-height", "calc(100vh - 472px)");

        $(".sliderGroupContainer").css("min-height", "-webkit-calc(100vh - 402px)");
        $(".sliderGroupContainer").css("min-height", "-moz-calc(100vh - 402px)");
        $(".sliderGroupContainer").css("min-height", "calc(100vh - 402px)");

        $(".sliderContainerGroupBackground").css("min-height", "-webkit-calc(100vh - 402px)");
        $(".sliderContainerGroupBackground").css("min-height", "-moz-calc(100vh - 402px)");
        $(".sliderContainerGroupBackground").css("min-height", "calc(100vh - 402px)");

        $(".sliderDelayGroupContainer").css("min-height", "-webkit-calc(100vh - 402px)");
        $(".sliderDelayGroupContainer").css("min-height", "-moz-calc(100vh - 402px)");
        $(".sliderDelayGroupContainer").css("min-height", "calc(100vh - 402px)");

        $(".sliderContainerGroupDelayBackground").css("min-height", "-webkit-calc(100vh - 422px)");
        $(".sliderContainerGroupDelayBackground").css("min-height", "-moz-calc(100vh - 422px)");
        $(".sliderContainerGroupDelayBackground").css("min-height", "calc(100vh - 422px)");

        $(".sliderDelayContainer").css("min-height", "-webkit-calc(100vh - 508px)");
        $(".sliderDelayContainer").css("min-height", "-moz-calc(100vh - 508px)");
        $(".sliderDelayContainer").css("min-height", "calc(100vh - 508px)");

        // $(".sliderDelayContainer").css("min-height", "-webkit-calc(100vh - 480px)");
        // $(".sliderDelayContainer").css("min-height", "-moz-calc(100vh - 480px)");
        // $(".sliderDelayContainer").css("min-height", "calc(100vh - 480px)");

        $(".itemQuarterVuMeter").css("min-height", "-webkit-calc(100vh - 405px)");
        $(".itemQuarterVuMeter").css("min-height", "-moz-calc(100vh - 405px)");
        $(".itemQuarterVuMeter").css("min-height", "calc(100vh - 405px)");

        $(".gainSoloVuMeter").css("top", "calc(100vh - 406px)");
        $(".gainSoloVuMeter").css("transform", 'scaleY(0)');
        $(".gainSoloVuMeter").css("height", (screenHeight - 406) + "px");
        var topPosLimSoloVuMeter = screenScrollHeight - 373;
        topPosLimSoloVuMeter = topPosLimSoloVuMeter.toFixed(0) + "px";
        $(".limiterSoloVuMeter").css("top", topPosLimSoloVuMeter);

        var heightLimSoloVuMeter = screenScrollHeight - 372;
        $(".limiterGRSoloVuMeter").css("height", heightLimSoloVuMeter + "px");
        $(".limiterPeakSoloVuMeter").css("height", heightLimSoloVuMeter + "px");
        $(".limiterSoloVuMeter").css("height", heightLimSoloVuMeter + "px");

        $(".itemQuarterVuMeterBackground").css("min-height", "-webkit-calc(100vh - 392px)");
        $(".itemQuarterVuMeterBackground").css("min-height", "-moz-calc(100vh - 392px)");
        $(".itemQuarterVuMeterBackground").css("min-height", "calc(100vh - 392px)");
    }
    winHeightFaderLimiter = screenHeight - 380;
    var w = screenWidth - 20;
    var h = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 300;
    if ((screenHeight || document.documentElement.clientHeight || document.body.clientHeight) < 680) {
        widgetPEQX = w - 80;
        widgetPEQY = 180;

        widgetXOVERX = w - 80;
        widgetXOVERY = 180;
        $(".itemFullButtonView").css("top", "136px");
        $("#peqNavBar").css("margin-top", 190 + "px");
    } else {
        widgetPEQX = w - 80;
        widgetPEQY = h * 0.5;

        widgetXOVERX = w - 80;
        widgetXOVERY = h * 0.5;

        $(".itemFullButtonView").css("top", "176px");
        $("#peqNavBar").css("margin-top", widgetPEQY + 20 + "px");
    }

    $("#peqGroupNavBar").css("margin-top", widgetPEQY + 20 + "px");
    $("#parametersAreaXOVER").css("margin-top", widgetPEQY + 20 + "px");

    $.fn.resizeLimiter();

    $.fn.drawTickLabels();

    $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
    $.fn.initXOVER(peqViewMode, xoverGainScaleType, xoverPhaseScaleType);
});

function resize() {
    $.fn.resizeWindows();
}

$.fn.resizeWindows = function() {
    screenHeight = window.innerHeight;
    screenWidth = window.innerWidth;
    screenScrollHeight = document.documentElement.scrollHeight;

    winHeightFader = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 485;
    winHeightGroupFader = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 400;
    winHeightVuMeter = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 425;

    if (screenHeight < 570) {
        winHeightFader = 104;
        winHeightGroupFader = 170;
        winHeightVuMeter = 150;
        $(".sliderContainer").css("min-height", "80px");

        $(".sliderGroupContainer").css("min-height", "168px");
        $(".sliderContainerGroupBackground").css("min-height", "185px");

        $(".sliderDelayGroupContainer").css("min-height", "170px");
        $(".sliderContainerGroupDelayBackground").css("min-height", "185px");

        $(".sliderDelayContainer").css("min-height", "62px");
        $(".sliderDelayContainer").css("max-height", "62px");
        // $(".sliderDelayContainer").css("min-height", "90px");
        // $(".sliderDelayContainer").css("max-height", "90px");
        // $(".sliderDelayContainerBackground").css("min-height", "88px");
        $(".sliderDelayContainerBackground").css("min-height", "60px");

        $(".itemQuarterVuMeter").css("min-height", "165px");

        $(".gainSoloVuMeter").css("top", "164px");
        $(".gainSoloVuMeter").css("transform", 'scaleY(0)');
        $(".gainSoloVuMeter").css("height", "164px");
        $(".limiterSoloVuMeter").css("top", "366px");
        $(".limiterGRSoloVuMeter").css("height", "327px");
        $(".limiterPeakSoloVuMeter").css("height", "327px");
        $(".limiterSoloVuMeter").css("height", "327px");

        $(".itemQuarterVuMeterBackground").css("min-height", "178px");
        $(".vuMeterRGDivLimiter").css("height", "326px");
        $(".vuMeterPeakDivLimiter").css("height", "326px");
        $(".vuMeterOutputDivLimiter").css("height", "326px");
        $(".outputPanelBackgroundLimiter").css("min-height", "457px");
    } else {
        $(".sliderContainer").css("min-height", "-webkit-calc(100vh - 472px)");
        $(".sliderContainer").css("min-height", "-moz-calc(100vh - 472px)");
        $(".sliderContainer").css("min-height", "calc(100vh - 472px)");

        $(".sliderGroupContainer").css("min-height", "-webkit-calc(100vh - 402px)");
        $(".sliderGroupContainer").css("min-height", "-moz-calc(100vh - 402px)");
        $(".sliderGroupContainer").css("min-height", "calc(100vh - 402px)");

        $(".sliderContainerGroupBackground").css("min-height", "-webkit-calc(100vh - 402px)");
        $(".sliderContainerGroupBackground").css("min-height", "-moz-calc(100vh - 402px)");
        $(".sliderContainerGroupBackground").css("min-height", "calc(100vh - 402px)");

        $(".sliderDelayGroupContainer").css("min-height", "-webkit-calc(100vh - 402px)");
        $(".sliderDelayGroupContainer").css("min-height", "-moz-calc(100vh - 402px)");
        $(".sliderDelayGroupContainer").css("min-height", "calc(100vh - 402px)");

        $(".sliderContainerGroupDelayBackground").css("min-height", "-webkit-calc(100vh - 422px)");
        $(".sliderContainerGroupDelayBackground").css("min-height", "-moz-calc(100vh - 422px)");
        $(".sliderContainerGroupDelayBackground").css("min-height", "calc(100vh - 422px)");

        $(".sliderDelayContainer").css("min-height", "-webkit-calc(100vh - 508px)");
        $(".sliderDelayContainer").css("min-height", "-moz-calc(100vh - 508px)");
        $(".sliderDelayContainer").css("min-height", "calc(100vh - 508px)");

        // $(".sliderDelayContainer").css("min-height", "-webkit-calc(100vh - 480px)");
        // $(".sliderDelayContainer").css("min-height", "-moz-calc(100vh - 480px)");
        // $(".sliderDelayContainer").css("min-height", "calc(100vh - 480px)");

        $(".itemQuarterVuMeter").css("min-height", "-webkit-calc(100vh - 405px)");
        $(".itemQuarterVuMeter").css("min-height", "-moz-calc(100vh - 405px)");
        $(".itemQuarterVuMeter").css("min-height", "calc(100vh - 405px)");

        $(".gainSoloVuMeter").css("top", "calc(100vh - 406px)");
        $(".gainSoloVuMeter").css("transform", 'scaleY(0)');
        $(".gainSoloVuMeter").css("height", (screenHeight - 406) + "px");
        var topPosLimSoloVuMeter = screenScrollHeight - 373;
        topPosLimSoloVuMeter = topPosLimSoloVuMeter.toFixed(0) + "px";
        $(".limiterSoloVuMeter").css("top", topPosLimSoloVuMeter);

        var heightLimSoloVuMeter = screenScrollHeight - 372;
        $(".limiterGRSoloVuMeter").css("height", heightLimSoloVuMeter + "px");
        $(".limiterPeakSoloVuMeter").css("height", heightLimSoloVuMeter + "px");
        $(".limiterSoloVuMeter").css("height", heightLimSoloVuMeter + "px");

        $(".itemQuarterVuMeterBackground").css("min-height", "-webkit-calc(100vh - 392px)");
        $(".itemQuarterVuMeterBackground").css("min-height", "-moz-calc(100vh - 392px)");
        $(".itemQuarterVuMeterBackground").css("min-height", "calc(100vh - 392px)");
    }
    winHeightFaderLimiter = screenHeight - 380;

    var w = screenWidth - 20;
    var h = (screenHeight || document.documentElement.clientHeight || document.body.clientHeight) - 300;

    if ((screenHeight || document.documentElement.clientHeight || document.body.clientHeight) < 680) {
        widgetPEQX = w - 80;
        widgetPEQY = 180;

        widgetXOVERX = w - 80;
        widgetXOVERY = 180;
        $(".itemFullButtonView").css("top", "136px");
        $("#peqNavBar").css("margin-top", 190 + "px");
    } else {
        widgetPEQX = w - 80;
        widgetPEQY = h * 0.5;

        widgetXOVERX = w - 80;
        widgetXOVERY = h * 0.5;

        $(".itemFullButtonView").css("top", "176px");
        $("#peqNavBar").css("margin-top", widgetPEQY + 20 + "px");
    }

    $("#peqGroupNavBar").css("margin-top", widgetPEQY + 20 + "px");
    $("#parametersAreaXOVER").css("margin-top", widgetPEQY + 20 + "px");

    $.fn.resizeLimiter();

    $.fn.drawTickLabels();

    $.fn.initPEQ(peqViewMode, peqGainScaleType, peqPhaseScaleType);
    $.fn.initXOVER(peqViewMode, xoverGainScaleType, xoverPhaseScaleType);
}

//RESIZE LIMITER VU METER AREA DEPENDING ON THE WIDTH OF THE PAGE
$.fn.resizeLimiter = function() {
    var moduleWidth = parseFloat($("#outputPanelBackgroundLimiter").width());
    var l = new Array(3);
    var step = 0;

    step = moduleWidth / 3;

    for (var i = 0; i < 3; i++) {
        if (moduleWidth > 170)
            l[i] = i * step + 10;
        else
            l[i] = i * step + 4;
        $("#label" + (i + 1) + "OutputLimiter").css("left", l[i] + "px");
    }

    $("#canvasVuMeterGRBGLimiter").css("left", (l[0] - 4) + "px");
    $("#vuMeterGRBGLimiter").css("left", l[0] + "px");

    $("#canvasVuMeterPeakBGLimiter").css("left", (l[1] - 4) + "px");
    $("#vuMeterPeakBGLimiter").css("left", l[1] + "px");

    $("#canvasVuMeterOutputBGLimiter").css("left", (l[2] - 5) + "px");
    $("#vuMeterOutputBGLimiter").css("left", l[2] + "px");

    var c, ctx;
    c = document.getElementById("canvasVuMeterGRBGLimiter");
    if (c) {
        ctx = c.getContext("2d");
        $.fn.drawTickLimiter(ctx);
    }
    c = document.getElementById("canvasVuMeterPeakBGLimiter");
    if (c) {
        ctx = c.getContext("2d");
        $.fn.drawTickLimiter(ctx);
    }
    c = document.getElementById("canvasVuMeterOutputBGLimiter");
    if (c) {
        ctx = c.getContext("2d");
        $.fn.drawTickLimiter(ctx);
    }
}

//DRAW TICK LABEL FOR SLIDERS
$.fn.drawTickLabels = function() {

    // DRAW TICK LABEL FOR VERTICAL GAIN SLIDER
    // console.log(winHeightFader);
    var c = document.getElementsByClassName("sliderContainerBackground");
    for (var k = 0; k < c.length; k++) {
        var ctx = c[k].getContext("2d");
        ctx.canvas.height = winHeightFader + 16;
        ctx.canvas.width = 52;
        ctx.font = "8px Arial";
        ctx.fillStyle = "#ebeded";
        ctx.textAlign = "end";
        for (var j = 0; j < labelFader.length; j++) {
            var y = ((-(winHeightFader - 4) / 95.5) * labelFader[j]) + (15 * (winHeightFader - 4) / 95);
            // console.log("valeur label : " + labelFader[j] + " // valeur compute " + y);
            if (labelFaderMark[j] != 0) {
                ctx.fillRect(0, y + 10, 40, 2);
                ctx.fillText(labelFader[j], 52, y + 13);
            } else {
                ctx.fillRect(5, y + 10, 30, 1);
                ctx.fillText(labelFader[j], 52, y + 13);
            }
        }
        ctx.stroke();
    }

    //MIXER
    var c = document.getElementsByClassName("sliderMixerContainerBackground");
    for (var k = 0; k < c.length; k++) {
        var ctx = c[k].getContext("2d");
        ctx.canvas.height = winHeightFader + 16;
        ctx.canvas.width = 60;
        ctx.font = "8px Arial";
        ctx.fillStyle = "#ebeded";
        ctx.textAlign = "end";
        for (var j = 0; j < labelFaderMixer.length; j++) {
            var y = ((-(winHeightFader - 4) / 95.5) * labelFaderMixer[j]) + (15 * (winHeightFader - 4) / 95);
            // console.log("valeur label : " + labelFader[j] + " // valeur compute " + y);
            if (labelFaderMark[j] != 0) {
                ctx.fillRect(0, y + 10, 40, 2);
                ctx.fillText(labelFaderMixer[j], 52, y + 13);
            } else {
                if (labelFaderMixer[j] === -80.0) {
                    ctx.fillRect(5, y + 9, 29, 2);
                    ctx.fillText("OFF", 60, y + 13);
                } else {
                    ctx.fillRect(5, y + 10, 29, 1);
                    ctx.fillText(labelFaderMixer[j], 52, y + 13);
                }
            }
        }
        ctx.stroke();
    }

    // DRAW TICK LABEL FOR VERTICAL GAIN GROUP SLIDER
    // console.log(winHeightFader);
    if (screenHeight >= 570) {
        winHeightGroupFader = winHeightGroupFader + 2;
    }
    var c = document.getElementsByClassName("sliderContainerGroupBackground");
    for (var k = 0; k < c.length; k++) {
        var ctx = c[k].getContext("2d");
        ctx.canvas.height = winHeightGroupFader + 16;
        ctx.font = "8px Arial";
        ctx.fillStyle = "#ebeded";
        ctx.textAlign = "end";
        for (var j = 0; j < labelFader.length; j++) {
            var y = ((-(winHeightGroupFader - 4) / 95.5) * labelFader[j]) + (15 * (winHeightGroupFader - 10) / 95);
            if (labelFaderMark[j] != 0) {
                ctx.fillRect(0, y + 10, 42, 2);
                ctx.fillText(labelFader[j], 52, y + 13);
            } else {
                ctx.fillRect(5, y + 10, 32, 1);
                ctx.fillText(labelFader[j], 52, y + 13);
            }
        }
        ctx.stroke();
    }
    if (screenHeight >= 570) {
        winHeightGroupFader = winHeightGroupFader - 2;
    }

    // DRAW TICK LABEL FOR VERTICAL VU METER
    var c = document.getElementsByClassName("itemQuarterVuMeterBackground");

    if (screenHeight < 570)
        winHeightVuMeter += 44;
    else
        winHeightVuMeter += 48;
    for (var k = 0; k < c.length; k++) {
        var ctx = c[k].getContext("2d");
        ctx.canvas.height = winHeightVuMeter - 16;
        ctx.canvas.width = 36;
        ctx.font = "8px Arial";
        ctx.fillStyle = "#ebeded";
        ctx.textAlign = "end";
        for (var j = 0; j < labelVuMeter.length; j++) {
            var y = ((-(winHeightVuMeter - 30) / 60) * labelVuMeter[j] + 2);
            if (labelVuMeterMark[j] != 0) {
                ctx.fillRect(18, y + 8, 16, 2);
                ctx.fillText(labelVuMeter[j], 14, y + 11);
            } else {
                ctx.fillRect(24, y + 8, 12, 1);
            }
        }
        ctx.stroke();
    }
    if (screenHeight < 570)
        winHeightVuMeter -= 44;
    else
        winHeightVuMeter -= 48;

    // DRAW TICK LABEL FOR VERTICAL DELAY SLIDER ((winHeightFader - 30) because the gain slider is 30px higher) -26 for adjusting delay in m
    // console.log(winHeightFader);
    if (screenHeight < 570) {
        winHeightFader = winHeightFader + 4 - 26;
    } else {
        winHeightFader = winHeightFader + 22 - 26;
    }
    var c = document.getElementsByClassName("sliderDelayContainerBackground");
    for (var k = 0; k < c.length; k++) {
        var ctx = c[k].getContext("2d");
        ctx.canvas.height = winHeightFader + 37;
        ctx.canvas.width = 60;
        ctx.font = "8px Arial";
        ctx.fillStyle = "#ebeded";
        for (var j = 0; j < labelDelay.length; j++) {
            if (labelDelay[j] != 0.0)
                var y = (winHeightFader - 20) - (Math.log10(labelDelay[j]) * ((winHeightFader - 20) / Math.log10(delayScaleMax)));
            else if (labelDelay[j] === 0.0)
                var y = (winHeightFader) - 20;
            if (labelDelayMark[j] != 0) {
                ctx.fillRect(22, y + 10, 33, 2);
                ctx.textAlign = "end";
                ctx.fillText(labelDelay[j], 14, y + 14);
            } else {
                ctx.fillRect(30, y + 10, 17, 1);
            }
        }
        ctx.stroke();
    }
    if (screenHeight < 570) {
        winHeightFader = winHeightFader - 4;
    } else {
        winHeightFader = winHeightFader - 22;
    }

    // DRAW TICK LABEL FOR VERTICAL GROUP DELAY SLIDER ((winHeightFader - 30) because the gain slider is 30px higher)
    // console.log(winHeightGroupFader);
    if (screenHeight < 570) {
        winHeightGroupFader = winHeightGroupFader + 17;
    } else {
        winHeightGroupFader = winHeightGroupFader + 15;
    }
    var c = document.getElementsByClassName("sliderContainerGroupDelayBackground");
    for (var k = 0; k < c.length; k++) {
        var ctx = c[k].getContext("2d");
        ctx.canvas.height = winHeightGroupFader + 16;
        ctx.font = "8px Arial";
        ctx.fillStyle = "#ebeded";
        for (var j = 0; j < labelDelay.length; j++) {
            if (labelDelay[j] != 0.0)
                var y = (winHeightGroupFader - 20) - (Math.log10(labelDelay[j]) * ((winHeightGroupFader - 18) / Math.log10(delayScaleMax)));
            else if (labelDelay[j] === 0.0)
                var y = (winHeightGroupFader) - 20;
            if (labelDelayMark[j] != 0) {
                ctx.fillRect(22, y + 10, 33, 2);
                ctx.textAlign = "end";
                ctx.fillText(labelDelay[j], 14, y + 14);
            } else {
                ctx.fillRect(30, y + 10, 17, 1);
            }
        }
        ctx.stroke();
    }
    if (screenHeight < 570) {
        winHeightGroupFader = winHeightGroupFader - 17;
    } else {
        winHeightGroupFader = winHeightGroupFader - 15;
    }

    var c, ctx;

    c = document.getElementById("canvasVuMeterGRBGLimiter");
    if (c) {
        ctx = c.getContext("2d");
        $.fn.drawTickLimiter(ctx);
    }
    c = document.getElementById("canvasVuMeterPeakBGLimiter");
    if (c) {
        ctx = c.getContext("2d");
        $.fn.drawTickLimiter(ctx);
    }
    c = document.getElementById("canvasVuMeterOutputBGLimiter");
    if (c) {
        ctx = c.getContext("2d");
        $.fn.drawTickLimiter(ctx);
    }
};

$.fn.drawTickLimiter = function(ctx) {
    winHeightFaderLimiter = screenScrollHeight - 375;
    ctx.canvas.height = winHeightFaderLimiter + 16;
    if (screenHeight < 570) {
        if (screenWidth < 990) {
            ctx.canvas.height = 851.2 + 20;
            winHeightFaderLimiter = 847;
        } else {
            ctx.canvas.height = 360 + 20;
            winHeightFaderLimiter = 365;
        }
    }

    ctx.canvas.width = 60;
    ctx.font = "8px Arial";
    ctx.fillStyle = "#ebeded";

    for (var j = 0; j < labelVuMeter.length; j++) {
        var y = ((winHeightFaderLimiter / 60) * labelGRVuMeter[j] + 5);
        if (labelVuMeterMark[j] != 0) {
            ctx.fillRect(6, y + 5, 20, 2);
            ctx.textAlign = "start";
            ctx.fillText(labelGRVuMeter[j], 32, y + 7 + 1);
        } else {
            ctx.fillRect(6, y + 5, 14, 1);
        }
    }
    ctx.stroke();
}

//DISCOVERY LIST SETUP
$.fn.setupDiscoverySolo = function() {
    //INIT LOCAL DEVICE
    $("#localDeviceList").prop("innerHTML", "");
    $("#localDeviceList").append($("<button>").prop({ id: "discoveryListDevice0", className: "btn btn-default btnSelector" }));
    $("#discoveryListDevice0").append($("<div>").prop({ id: "dldm0", className: "media" }));
    switch ($.fn.getModel(0)) {
        case 1:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP354.png", className: "logoSelector" }));
            break;
        case 2:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP704.png", className: "logoSelector" }));
            break;
        case 3:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP1504.png", className: "logoSelector" }));
            break;
        case 4:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP3004.png", className: "logoSelector" }));
            break;
        case 7:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP716.png", className: "logoSelector" }));
            break;
        case 8:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP716.png", className: "logoSelector" }));
            break;
        default:
            $("#dldm0").append($("<img>").prop({ src: "./img/CP.png", className: "logoSelector" }));
            break;
    }
    $("#dldm0").append($("<div>").prop({ id: "dldmmb0", className: "media-body" }));
    $("#dldmmb0").append($("<div>").prop({ id: "dldtds0", className: "titleDeviceSelector" }));

    $("#dldmmb0").append($("<div>").prop({ id: "dldcds0", className: "channelDeviceSelector" }));

    $("#dldmmb0").append($("<div>").prop({ id: "dldvms0", className: "vuMeterSelector" }));

    if ($.fn.getModel(0) == 7 || $.fn.getModel(0) == 8) {
        //16 channels device 0
        for (var i = 0; i < channel16Count; i++) {
            let idA = "dldrB" + i + "a" + "0";
            let idB = "dlri" + i + "a" + "0";
            let classA = "bRI border16RectangleInput" + i;
            let classB = "rI rectangleInput" + i;

            $("#dldvms0").append($("<div>").prop({ id: idA, className: classA }));
            $("#" + idA).append($("<div>").prop({ id: idB, className: classB }));
        }

    } else if ($.fn.getModel(0) == 5 || $.fn.getModel(0) == 6) {
        //1 channel device 0
        $("#dldvms0").append($("<div>").prop({ id: "dldrB0a0", className: "bRI borderRectangleInput0" }));
        $("#dldrB0a0").append($("<div>").prop({ id: "dlri0a0", className: "rI rectangleInput0" }));
    } else if ($.fn.getModel(0) == 9) {
        //3 channels device 0
        for (var i = 0; i < channel3Count; i++) {
            let idA = "dldrB" + i + "a" + "0";
            let idB = "dlri" + i + "a" + "0";
            let classA = "bRI borderRectangleInput" + i;
            let classB = "rI rectangleInput" + i;

            $("#dldvms0").append($("<div>").prop({ id: idA, className: classA }));
            $("#" + idA).append($("<div>").prop({ id: idB, className: classB }));
        }
    } else {
        //4 channels device 0
        for (var i = 0; i < channelCount; i++) {
            let idA = "dldrB" + i + "a" + "0";
            let idB = "dlri" + i + "a" + "0";
            let classA = "bRI borderRectangleInput" + i;
            let classB = "rI rectangleInput" + i;

            $("#dldvms0").append($("<div>").prop({ id: idA, className: classA }));
            $("#" + idA).append($("<div>").prop({ id: idB, className: classB }));
        }

    }

    $("#dldm0").append($("<button>").prop({ id: "dldmbi0", className: "infoDiscovery popover-btn" }))
    $("#dldmbi0").attr("data-toggle", "popover");
    $("#dldmbi0").attr("data-placement", "bottom");
    $("#dldmbi0").attr("data-original-title", "Status :");
    $("#dldmbi0").attr("data-content", "More network info");
    $("#dldmbi0").append($("<div>").prop({ id: "dldmi0", className: "infoDiscoveryContent" }));
    $("#dldmi0").prop("innerHTML", "i");
}

//OVERVIEW SETUP
$.fn.setupOverviewSolo = function(type) {

    //BACKGROUND CHANNEL TABS - from 1 to 16 module
    $(".overviewStereo").prop("innerHTML", "");
    $(".overviewChannelArea").prop("innerHTML", "");

    //CP354 = 1 // CP704 = 2 // CP1504 = 3 // CP3004 = 4 // CP0701 = 5 // CP0702 = 6 // CP0716 = 7 // CP7164 = 8 // CP0703 = 9
    if (type >= 0 && type < 5) {
        //BACKGROUND OVERVIEW STEREO - stereo icons to link temporary two channels
        // $(".overviewStereo").prop("innerHTML", "");
        $(".overviewStereo").append($("<button>").prop({ id: "stereo12", className: "btn btn-default btnStereo" }));
        $("#stereo12").append($("<div>").prop({ id: "stereoMedia12", className: "media" }));
        $("#stereoMedia12").append($("<img>").prop({ className: "logoStereo", src: "./img/Gang.png" }));
        $(".overviewStereo").append($("<button>").prop({ id: "stereo34", className: "btn btn-default btnStereo" }));
        $("#stereo34").append($("<div>").prop({ id: "stereoMedia34", className: "media" }));
        $("#stereoMedia34").append($("<img>").prop({ className: "logoStereo", src: "./img/Gang.png" }));

        for (i = 0; i < channelCount; i++) {
            let id = "overviewBG" + i;
            let mute = "overviewButtonMute" + i;
            let select = "overviewButton" + i;
            let source = "overviewSourceLabel" + i;
            let vuMeter = "overviewVuMeter" + i;
            let vuMeterInput = "overviewVuMeterInput" + i;
            let compMeter = "overviewCompMeter" + i;
            let compMeterInput = "overviewCompMeterInput" + i;
            let label = "overviewChLabel" + i;
            $(".overviewChannelArea").append($("<div>").prop({ id: id, className: "backgroundSource bS" }));
            $("#" + id).append($("<div>").prop({ className: "overviewButtonChannelNumber", innerHTML: labelOverviewChannel[i] }));
            $("#" + id).append($("<button>").prop({ id: mute, className: "overviewButtonMute", innerHTML: "Mute" }));
            $("#" + id).append($("<button>").prop({ id: select, className: "overviewButtonSelect oBS", innerHTML: "Select" }));
            $("#" + id).append($("<div>").prop({ className: "overviewButtonTitleInput", innerHTML: "Gain" }));
            $("#" + id).append($("<div>").prop({ id: source, className: "overviewButtonContentInput", innerHTML: "Gain" }));
            $("#" + id).append($("<div>").prop({ id: vuMeter, className: "overviewVuMeterBG" }));
            $("#" + vuMeter).append($("<div>").prop({ id: vuMeterInput, className: "overviewVuMeter" }));
            $("#" + id).append($("<div>").prop({ id: compMeter, className: "overviewCompMeterBG" }));
            $("#" + compMeter).append($("<div>").prop({ id: compMeterInput, className: "overviewCompMeter" }));
            $("#" + id).append($("<div>").prop({ id: label, className: "overviewChannelLabel", innerHTML: "channel label" }));
            //SET VU METER SIZE TO 0
            $("#" + vuMeterInput).css("transform", 'scaleY(0)');
            $("#" + compMeterInput).css("transform", 'scaleY(0)');
        }
        //CP354 = 1 // CP704 = 2 // CP1504 = 3 // CP3004 = 4 // CP0701 = 5 // CP0702 = 6 // CP0716 = 7 // CP7164 = 8 // CP0703 = 9
    } else if (type == 5 || type == 6) {
        let id = "overviewBG0";
        let mute = "overviewButtonMute0";
        let select = "overviewButton0";
        let source = "overviewSourceLabel0";
        let vuMeter = "overviewVuMeter0";
        let vuMeterInput = "overviewVuMeterInput0";
        let compMeter = "overviewCompMeter0";
        let compMeterInput = "overviewCompMeterInput0";
        let label = "overviewChLabel0";
        $(".overviewChannelArea").append($("<div>").prop({ id: id, className: "backgroundSource bS" }));
        $("#" + id).append($("<div>").prop({ className: "overviewButtonChannelNumber", innerHTML: labelOverviewChannel[0] }));
        $("#" + id).append($("<button>").prop({ id: mute, className: "overviewButtonMute", innerHTML: "Mute" }));
        $("#" + id).append($("<button>").prop({ id: select, className: "overviewButtonSelect oBS", innerHTML: "Select" }));
        $("#" + id).append($("<div>").prop({ className: "overviewButtonTitleInput", innerHTML: "Gain" }));
        $("#" + id).append($("<div>").prop({ id: source, className: "overviewButtonContentInput", innerHTML: "Gain" }));
        $("#" + id).append($("<div>").prop({ id: vuMeter, className: "overviewVuMeterBG" }));
        $("#" + vuMeter).append($("<div>").prop({ id: vuMeterInput, className: "overviewVuMeter" }));
        $("#" + id).append($("<div>").prop({ id: compMeter, className: "overviewCompMeterBG" }));
        $("#" + compMeter).append($("<div>").prop({ id: compMeterInput, className: "overviewCompMeter" }));
        $("#" + id).append($("<div>").prop({ id: label, className: "overviewChannelLabel", innerHTML: "channel label" }));
        //SET VU METER SIZE TO 0
        $("#" + vuMeterInput).css("transform", 'scaleY(0)');
        $("#" + compMeterInput).css("transform", 'scaleY(0)');

        //CP354 = 1 // CP704 = 2 // CP1504 = 3 // CP3004 = 4 // CP0701 = 5 // CP0702 = 6 // CP0716 = 7 // CP7164 = 8 // CP0703 = 9
    } else if (type == 7 || type == 8) {
        for (i = 0; i < channel16Count; i++) {
            let id = "overviewBG" + i;
            let mute = "overviewButtonMute" + i;
            let select = "overviewButton" + i;
            let source = "overviewSourceLabel" + i;
            let vuMeter = "overviewVuMeter" + i;
            let vuMeterInput = "overviewVuMeterInput" + i;
            let compMeter = "overviewCompMeter" + i;
            let compMeterInput = "overviewCompMeterInput" + i;
            let label = "overviewChLabel" + i;
            $(".overviewChannelArea").append($("<div>").prop({ id: id, className: "backgroundSource16 bS" }));
            $("#" + id).append($("<div>").prop({ className: "overviewButtonChannelNumber16", innerHTML: labelOverviewChannel[i] }));
            $("#" + id).append($("<button>").prop({ id: select, className: "overviewButtonSelect16 oBS", innerHTML: "Select" }));
            // $("#" + id).append($("<div>").prop({ className: "overviewButtonTitleInput", innerHTML: "Gain" }));
            // $("#" + id).append($("<div>").prop({ id: source, className: "overviewButtonContentInput", innerHTML: "Gain" }));
            $("#" + id).append($("<div>").prop({ id: vuMeter, className: "overviewVuMeterBG16" }));
            $("#" + vuMeter).append($("<div>").prop({ id: vuMeterInput, className: "overviewVuMeter" }));
            $("#" + id).append($("<div>").prop({ id: compMeter, className: "overviewCompMeterBG16" }));
            $("#" + compMeter).append($("<div>").prop({ id: compMeterInput, className: "overviewCompMeter" }));
            $("#" + id).append($("<div>").prop({ id: label, className: "overviewChannelLabel16", innerHTML: "label" }));
            $("#" + id).append($("<button>").prop({ id: mute, className: "overviewButtonMute16", innerHTML: "Mute" }));
            //SET VU METER SIZE TO 0
            $("#" + vuMeterInput).css("transform", 'scaleY(0)');
            $("#" + compMeterInput).css("transform", 'scaleY(0)');
        }
    } else if (type == 9) {
        for (i = 0; i < channelCount; i++) {
            let id = "overviewBG" + i;
            let mute = "overviewButtonMute" + i;
            let select = "overviewButton" + i;
            let source = "overviewSourceLabel" + i;
            let vuMeter = "overviewVuMeter" + i;
            let vuMeterInput = "overviewVuMeterInput" + i;
            let compMeter = "overviewCompMeter" + i;
            let compMeterInput = "overviewCompMeterInput" + i;
            let label = "overviewChLabel" + i;
            $(".overviewChannelArea").append($("<div>").prop({ id: id, className: "backgroundSource bS" }));
            $("#" + id).append($("<div>").prop({ className: "overviewButtonChannelNumber", innerHTML: labelOverviewChannel3ch[i] }));
            $("#" + id).append($("<button>").prop({ id: mute, className: "overviewButtonMute", innerHTML: "Mute" }));
            $("#" + id).append($("<button>").prop({ id: select, className: "overviewButtonSelect oBS", innerHTML: "Select" }));
            $("#" + id).append($("<div>").prop({ className: "overviewButtonTitleInput", innerHTML: "Gain" }));
            $("#" + id).append($("<div>").prop({ id: source, className: "overviewButtonContentInput", innerHTML: "Gain" }));
            $("#" + id).append($("<div>").prop({ id: vuMeter, className: "overviewVuMeterBG" }));
            $("#" + vuMeter).append($("<div>").prop({ id: vuMeterInput, className: "overviewVuMeter" }));
            $("#" + id).append($("<div>").prop({ id: compMeter, className: "overviewCompMeterBG" }));
            $("#" + compMeter).append($("<div>").prop({ id: compMeterInput, className: "overviewCompMeter" }));
            $("#" + id).append($("<div>").prop({ id: label, className: "overviewChannelLabel", innerHTML: "channel label" }));
            //SET VU METER SIZE TO 0
            $("#" + vuMeterInput).css("transform", 'scaleY(0)');
            $("#" + compMeterInput).css("transform", 'scaleY(0)');
        }

        $("#overviewBG1").remove();
    }

    //BACKGROUND OVERVIEW BUTTON - icons buttons to access to mixer, gain, delay, peq, xover, limiter and speaker solo panels
    $(".backgroundOverviewButton").prop("innerHTML", "");
    $(".backgroundOverviewButton").append($("<div>").prop({ id: "overviewUserIcons", className: "overviewUserArea" }));
    $(".overviewUserArea").append($("<div>").prop({ id: "overviewBackgroungUserTitle", className: "backgroundTitleLeft" }));
    $("#overviewBackgroungUserTitle").prop("innerHTML", "USER");
    $(".overviewUserArea").append($("<div>").prop({ className: "backgroundLine" }));
    $(".overviewUserArea").append($("<div>").prop({ className: "overviewMenuDiv" }));

    $(".backgroundOverviewButton").append($("<div>").prop({ id: "overviewBackgroungSpeakerPresetLoaded", className: "loadedPreset" }));
    $("#overviewBackgroungSpeakerPresetLoaded").prop("innerHTML", "");

    // $(".backgroundOverviewButton").prop("innerHTML", "");
    // $(".backgroundSpeakerPresetOverviewButton").append($("<div>").prop({ id: "overviewBackgroungSpeakerTitle", className: "backgroundTitleRight" }));
    // $("#overviewBackgroungSpeakerTitle").prop("innerHTML", "SPEAKER");

    // $(".backgroundSpeakerPresetOverviewButton").append($("<div>").prop({ className: "backgroundLine" }));
    // $(".backgroundOverviewButton").append($("<div>").prop({ className: "overviewSpeakerPresetMenuDiv" }));

    for (var i = 0; i < iconOverviewCount; i++) {
        var idMedia = "btnOverviewSoloMedia" + i;
        if (i < iconOverviewCount - 1)
            $(".overviewMenuDiv").append($("<button>").prop({ id: iconOverviewIdList[i], className: "btn btn-default btnOverview" }));
        else
            $(".backgroundOverviewButton").append($("<button>").prop({ id: iconOverviewIdList[i], className: "btn btn-default btnOverviewSpeaker" }));

        $("#" + iconOverviewIdList[i]).append($("<div>").prop({ id: idMedia, className: "media" }));
        $("#" + idMedia).append($("<img>").prop({ className: "logoOverview", src: iconOverviewIconList[i] }));
        $("#" + iconOverviewIdList[i]).append($("<div>").prop({ className: "btnOverviewTitle", innerHTML: iconOverviewLabelList[i] }));
    }

    $.fn.setVisualBridge();
}

//SETUP SOURCE MAIN PANEL FOR AMP VIEW
$.fn.setupSourceSolo = function(type) {
    //Empty source panel
    $("#sourceMainPanel").prop("innerHTML", "");

    //CP354 = 1 // CP704 = 2 // CP1504 = 3 // CP3004 = 4 // CP0701 = 5 // CP0702 = 6 // CP0716 = 7 // CP7164 = 8 // CP0703 = 9
    if (type == 1 || type == 2 || type == 3 || type == 4 || type == 8 || type == 9) {

        for (var i = 0; i < 12; i++) {
            var idTemp = "mixerPanel" + i;
            var idInput = "mixer" + i;
            var idLabel = "mixerLabel" + i;
            var idGainUp = "gain" + i + "VolUp";
            var idGainDown = "gain" + i + "VolDown";
            var idSlider = "sliderMixerVertical" + i;
            var idCanvas = "canvasSliderMarks" + i;
            $("#sourceMainPanel").append($("<div>").prop({ id: idTemp, className: "itemEighter" }));
            $("#" + idTemp).append($("<div>").prop({ className: "itemEighterDb", innerHTML: "dB" }));
            $("#" + idTemp).append($("<input>").prop({ id: idInput, className: "itemEighterTextField", type: "text", value: "0.0" }));
            $("#" + idTemp).append($("<div>").prop({ id: idLabel, className: "itemEighterTitle", innerHTML: sourceOverviewLabel[i] }));
            $("#" + idTemp).append($("<button>").prop({ id: idGainUp, className: "itemEighterButtonVolUp .text-nowrap" }));
            $("#" + idGainUp).append($("<div>").prop({ className: "media" }));
            $("#" + idGainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
            $("#" + idTemp).append($("<button>").prop({ id: idGainDown, className: "itemEighterButtonVolDown" }));
            $("#" + idGainDown).append($("<div>").prop({ className: "media" }));
            $("#" + idGainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));
            $("#" + idTemp).append($("<div>").prop({ className: "itemEighterSliderContainer" }));
            $("#" + idTemp + ">.itemEighterSliderContainer").append($("<canvas>").prop({ id: idCanvas, className: "sliderMixerContainerBackground", width: "60px", height: "100px" }));
            $("#" + idTemp + ">.itemEighterSliderContainer").append($("<div>").prop({ id: idSlider, className: "sliderContainer" }));
        }

        $("#sourceMainPanel").append($("<div>").prop({ id: "sourceSettingsPanel", className: "itemEighterSettings" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterLabelTitle", innerHTML: "Output A" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterChannelLabelTitle", innerHTML: "Channel label :" }));
        $("#sourceSettingsPanel").append($("<input>").prop({ id: "soloChannelLabel", className: "itemEighterChannelLabelTextField", type: "text" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterChannelSecondaryTitle", innerHTML: "Secondary input :" }));
        $("#sourceSettingsPanel").append($("<select>").prop({ id: "soloSecondaryInputSelect", className: "itemEighterChannelSecondarySelect" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 0, innerHTML: "Analog 1" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 1, innerHTML: "Analog 2" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 2, innerHTML: "Analog 3" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 3, innerHTML: "Analog 4" }));

        $("#sourceSettingsPanel").append($("<button>").prop({ id: "soloChannelLabel", className: "itemEighterMuteAllButton", innerHTML: "ALL OFF" }));

        $("#sourceSettingsPanel").append($("<div>").prop({ id: "itemEighterSignalGenerator", className: "itemEighterSignalGeneratorArea" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenIcon" }));
        $(".itemEighterSiggenIcon").append($("<img>").prop({ className: "itemEighterSiggenLogo", src: "./img/Siggen.png" }))

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenTitle", innerHTML: "Signal Generator" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenSineFreqTitle", innerHTML: "Sine freq (Hz)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenSineFreqInput", className: "itemEighterSiggenSineFreqInput", type: "text" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenSineGainTitle", innerHTML: "Sine gain          (dB)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenSineGainInput", className: "itemEighterSiggenSineGainInput", type: "text" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenPinkGainTitle", innerHTML: "Pink n. gain (dB)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenPinkGainInput", className: "itemEighterSiggenPinkGainInput", type: "text" }));

        if (type == 9) {
            $("#mixerPanel1").remove();
            $("#mixerPanel3").remove();
            $("#mixerPanel4").remove();
            $("#mixerPanel5").remove();
            $("#mixerPanel6").remove();
            $("#mixerPanel7").remove();
            $("#mixerLabel2").innerHTML(sourceOverviewLabel[1]);
        }

    } else if (type == 5 || type == 6) {
        for (var i = 0; i < 12; i++) {
            if (i == 0 || i > 7) {
                var idTemp = "mixerPanel" + i;
                var idInput = "mixer" + i;
                var idLabel = "mixerLabel" + i;
                var idGainUp = "gain" + i + "VolUp";
                var idGainDown = "gain" + i + "VolDown";
                var idSlider = "sliderMixerVertical" + i;
                var idCanvas = "canvasSliderMarks" + i;
                $("#sourceMainPanel").append($("<div>").prop({ id: idTemp, className: "itemEighter" }));
                $("#" + idTemp).append($("<div>").prop({ className: "itemEighterDb", innerHTML: "dB" }));
                $("#" + idTemp).append($("<input>").prop({ id: idInput, className: "itemEighterTextField", type: "text", value: "0.0" }));
                $("#" + idTemp).append($("<div>").prop({ id: idLabel, className: "itemEighterTitle", innerHTML: source1ChOverviewLabel[i] }));
                $("#" + idTemp).append($("<button>").prop({ id: idGainUp, className: "itemEighterButtonVolUp .text-nowrap" }));
                $("#" + idGainUp).append($("<div>").prop({ className: "media" }));
                $("#" + idGainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
                $("#" + idTemp).append($("<button>").prop({ id: idGainDown, className: "itemEighterButtonVolDown" }));
                $("#" + idGainDown).append($("<div>").prop({ className: "media" }));
                $("#" + idGainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));
                $("#" + idTemp).append($("<div>").prop({ className: "itemEighterSliderContainer" }));
                $("#" + idTemp + ">.itemEighterSliderContainer").append($("<canvas>").prop({ id: idCanvas, className: "sliderMixerContainerBackground", width: "60px", height: "100px" }));
                $("#" + idTemp + ">.itemEighterSliderContainer").append($("<div>").prop({ id: idSlider, className: "sliderContainer" }));
            }
        }

        $("#sourceMainPanel").append($("<div>").prop({ id: "sourceSettingsPanel", className: "itemEighterSettings" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterLabelTitle", innerHTML: "Output A" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterChannelLabelTitle", innerHTML: "Channel label :" }));
        $("#sourceSettingsPanel").append($("<input>").prop({ id: "soloChannelLabel", className: "itemEighterChannelLabelTextField", type: "text" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterChannelSecondaryTitle", innerHTML: "Secondary input :" }));
        $("#sourceSettingsPanel").append($("<select>").prop({ id: "soloSecondaryInputSelect", className: "itemEighterChannelSecondarySelect" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 0, innerHTML: "Analog 1" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 1, innerHTML: "Analog 2" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 2, innerHTML: "Analog 3" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 3, innerHTML: "Analog 4" }));

        $("#sourceSettingsPanel").append($("<button>").prop({ id: "soloChannelLabel", className: "itemEighterMuteAllButton", innerHTML: "ALL OFF" }));

        $("#sourceSettingsPanel").append($("<div>").prop({ id: "itemEighterSignalGenerator", className: "itemEighterSignalGeneratorArea" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenIcon" }));
        $(".itemEighterSiggenIcon").append($("<img>").prop({ className: "itemEighterSiggenLogo", src: "./img/Siggen.png" }))

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenTitle", innerHTML: "Signal Generator" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenSineFreqTitle", innerHTML: "Sine freq (Hz)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenSineFreqInput", className: "itemEighterSiggenSineFreqInput", type: "text" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenSineGainTitle", innerHTML: "Sine gain          (dB)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenSineGainInput", className: "itemEighterSiggenSineGainInput", type: "text" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenPinkGainTitle", innerHTML: "Pink n. gain (dB)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenPinkGainInput", className: "itemEighterSiggenPinkGainInput", type: "text" }));

    } else if (type == 7) {
        for (var i = 0; i < 12; i++) {
            var idTemp = "mixerPanel" + i;
            var idInput = "mixer" + i;
            var idLabel = "mixerLabel" + i;
            var idGainUp = "gain" + i + "VolUp";
            var idGainDown = "gain" + i + "VolDown";
            var idSlider = "sliderMixerVertical" + i;
            var idCanvas = "canvasSliderMarks" + i;
            $("#sourceMainPanel").append($("<div>").prop({ id: idTemp, className: "itemEighter" }));
            $("#" + idTemp).append($("<div>").prop({ className: "itemEighterDb", innerHTML: "dB" }));
            $("#" + idTemp).append($("<input>").prop({ id: idInput, className: "itemEighterTextField", type: "text", value: "0.0" }));
            $("#" + idTemp).append($("<div>").prop({ id: idLabel, className: "itemEighterTitle", innerHTML: sourceOverviewLabel[i] }));
            $("#" + idTemp).append($("<button>").prop({ id: idGainUp, className: "itemEighterButtonVolUp .text-nowrap" }));
            $("#" + idGainUp).append($("<div>").prop({ className: "media" }));
            $("#" + idGainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
            $("#" + idTemp).append($("<button>").prop({ id: idGainDown, className: "itemEighterButtonVolDown" }));
            $("#" + idGainDown).append($("<div>").prop({ className: "media" }));
            $("#" + idGainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));
            $("#" + idTemp).append($("<div>").prop({ className: "itemEighterSliderContainer" }));
            $("#" + idTemp + ">.itemEighterSliderContainer").append($("<canvas>").prop({ id: idCanvas, className: "sliderMixerContainerBackground", width: "60px", height: "100px" }));
            $("#" + idTemp + ">.itemEighterSliderContainer").append($("<div>").prop({ id: idSlider, className: "sliderContainer" }));
        }

        $("#mixerPanel5").remove();
        $("#mixerPanel6").remove();
        $("#mixerPanel7").remove();

        $("#sourceMainPanel").append($("<div>").prop({ id: "sourceSettingsPanel", className: "itemEighterSettings" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterLabelTitle", innerHTML: "Output A" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterChannelLabelTitle", innerHTML: "Channel label :" }));
        $("#sourceSettingsPanel").append($("<input>").prop({ id: "soloChannelLabel", className: "itemEighterChannelLabelTextField", type: "text" }));
        $("#sourceSettingsPanel").append($("<div>").prop({ className: "itemEighterChannelSecondaryTitle", innerHTML: "Secondary input :" }));
        $("#sourceSettingsPanel").append($("<select>").prop({ id: "soloSecondaryInputSelect", className: "itemEighterChannelSecondarySelect" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 0, innerHTML: "Analog 1" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 1, innerHTML: "Analog 2" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 2, innerHTML: "Analog 3" }));
        $("#soloSecondaryInputSelect").append($("<option>").prop({ value: 3, innerHTML: "Analog 4" }));

        $("#sourceSettingsPanel").append($("<button>").prop({ id: "soloChannelLabel", className: "itemEighterMuteAllButton", innerHTML: "ALL OFF" }));

        $("#sourceSettingsPanel").append($("<div>").prop({ id: "itemEighterSignalGenerator", className: "itemEighterSignalGeneratorArea" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenIcon" }));
        $(".itemEighterSiggenIcon").append($("<img>").prop({ className: "itemEighterSiggenLogo", src: "./img/Siggen.png" }))

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenTitle", innerHTML: "Signal Generator" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenSineFreqTitle", innerHTML: "Sine freq (Hz)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenSineFreqInput", className: "itemEighterSiggenSineFreqInput", type: "text" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenSineGainTitle", innerHTML: "Sine gain          (dB)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenSineGainInput", className: "itemEighterSiggenSineGainInput", type: "text" }));

        $("#itemEighterSignalGenerator").append($("<div>").prop({ className: "itemEighterSiggenPinkGainTitle", innerHTML: "Pink n. gain (dB)" }));
        $("#itemEighterSignalGenerator").append($("<input>").prop({ id: "siggenPinkGainInput", className: "itemEighterSiggenPinkGainInput", type: "text" }));
    }
}

//SETUP GAIN MAIN PANEL 
$.fn.setupGainSolo = function(type) {
    //Empty gain panel
    $("#gainMainPanel").prop("innerHTML", "");

    if (type >= 0 && type < 5) {
        for (i = 0; i < channelCount; i++) {
            let quarter = "itemQuarter" + i;
            let gainInput = "gain" + i;
            let canvasVuMarks = "canvasVuMarks" + i;
            let itemVuMeter = "itemQuarterVu" + i;
            let gainSoloVu = "gainSoloVuMeterCh" + i;
            let gainUp = "gainUp" + i;
            let gainDown = "gainDown" + i;
            let btnPhase = "buttonPhase" + i;
            let quarterSliderContainer = "quarterSliderContainer" + i;
            let canvasSliderMark = "canvasSliderMarks" + i;
            let sliderVertical = "sliderVertical" + i;

            $("#gainMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterDb", innerHTML: "dB" }));
            $("#" + quarter).append($("<input>").prop({ id: gainInput, className: "itemQuarterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<canvas>").prop({ id: canvasVuMarks, className: "itemQuarterVuMeterBackground" }));
            $("#" + quarter).append($("<div>").prop({ id: itemVuMeter, className: "itemQuarterVuMeter" }));

            $("#" + itemVuMeter).append($("<div>").prop({ id: gainSoloVu, className: "gainSoloVuMeter" }));

            $("#" + quarter).append($("<button>").prop({ id: gainUp, className: "itemQuarterButtonVolUp" }));
            $("#" + gainUp).append($("<div>").prop({ className: "media" }));
            $("#" + gainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));

            $("#" + quarter).append($("<button>").prop({ id: gainDown, className: "itemQuarterButtonVolDown" }));
            $("#" + gainDown).append($("<div>").prop({ className: "media" }));
            $("#" + gainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<button>").prop({ id: btnPhase, className: "itemQuarterButtonPhase" }));
            $("#" + btnPhase).append($("<div>").prop({ className: "media" }));
            $("#" + btnPhase + ">.media").append($("<img>").prop({ className: "buttonPhase", src: "./img/Polarity.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterSliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderContainer" }));
        }

    } else if (type == 5 || type == 6) {

        for (i = 0; i < channel1Count; i++) {
            let quarter = "itemQuarter" + i;
            let gainInput = "gain" + i;
            let canvasVuMarks = "canvasVuMarks" + i;
            let itemVuMeter = "itemQuarterVu" + i;
            let gainSoloVu = "gainSoloVuMeterCh" + i;
            let gainUp = "gainUp" + i;
            let gainDown = "gainDown" + i;
            let btnPhase = "buttonPhase" + i;
            let quarterSliderContainer = "quarterSliderContainer" + i;
            let canvasSliderMark = "canvasSliderMarks" + i;
            let sliderVertical = "sliderVertical" + i;

            $("#gainMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterDb", innerHTML: "dB" }));
            $("#" + quarter).append($("<input>").prop({ id: gainInput, className: "itemQuarterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<canvas>").prop({ id: canvasVuMarks, className: "itemQuarterVuMeterBackground" }));
            $("#" + quarter).append($("<div>").prop({ id: itemVuMeter, className: "itemQuarterVuMeter" }));

            $("#" + itemVuMeter).append($("<div>").prop({ id: gainSoloVu, className: "gainSoloVuMeter" }));

            $("#" + quarter).append($("<button>").prop({ id: gainUp, className: "itemQuarterButtonVolUp" }));
            $("#" + gainUp).append($("<div>").prop({ className: "media" }));
            $("#" + gainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));

            $("#" + quarter).append($("<button>").prop({ id: gainDown, className: "itemQuarterButtonVolDown" }));
            $("#" + gainDown).append($("<div>").prop({ className: "media" }));
            $("#" + gainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<button>").prop({ id: btnPhase, className: "itemQuarterButtonPhase" }));
            $("#" + btnPhase).append($("<div>").prop({ className: "media" }));
            $("#" + btnPhase + ">.media").append($("<img>").prop({ className: "buttonPhase", src: "./img/Polarity.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterSliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderContainer" }));
        }

    } else if (type == 7 || type == 8) {
        for (i = 0; i < channel16Count; i++) {
            let quarter = "itemQuarter" + i;
            let gainInput = "gain" + i;
            let canvasVuMarks = "canvasVuMarks" + i;
            let itemVuMeter = "itemQuarterVu" + i;
            let gainSoloVu = "gainSoloVuMeterCh" + i;
            let gainUp = "gainUp" + i;
            let gainDown = "gainDown" + i;
            let btnPhase = "buttonPhase" + i;
            let quarterSliderContainer = "quarterSliderContainer" + i;
            let canvasSliderMark = "canvasSliderMarks" + i;
            let sliderVertical = "sliderVertical" + i;


            $("#gainMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter16" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterLabel16", innerHTML: labelOverviewChannel[i] }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterDb16", innerHTML: "dB" }));
            $("#" + quarter).append($("<input>").prop({ id: gainInput, className: "itemQuarterTextField16", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<canvas>").prop({ id: canvasVuMarks, className: "itemQuarterVuMeterBackground" }));
            $("#" + quarter).append($("<div>").prop({ id: itemVuMeter, className: "itemQuarterVuMeter" }));

            $("#" + itemVuMeter).append($("<div>").prop({ id: gainSoloVu, className: "gainSoloVuMeter" }));

            $("#" + quarter).append($("<button>").prop({ id: gainUp, className: "itemQuarterButtonVolUp16" }));
            $("#" + gainUp).append($("<div>").prop({ className: "media" }));
            $("#" + gainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));

            $("#" + quarter).append($("<button>").prop({ id: gainDown, className: "itemQuarterButtonVolDown16" }));
            $("#" + gainDown).append($("<div>").prop({ className: "media" }));
            $("#" + gainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<button>").prop({ id: btnPhase, className: "itemQuarterButtonPhase16" }));
            $("#" + btnPhase).append($("<div>").prop({ className: "media" }));
            $("#" + btnPhase + ">.media").append($("<img>").prop({ className: "buttonPhase", src: "./img/Polarity.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterSliderContainer16" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderContainer" }));
        }
    } else if (type == 9) {
        for (i = 0; i < channelCount; i++) {
            let quarter = "itemQuarter" + i;
            let gainInput = "gain" + i;
            let canvasVuMarks = "canvasVuMarks" + i;
            let itemVuMeter = "itemQuarterVu" + i;
            let gainSoloVu = "gainSoloVuMeterCh" + i;
            let gainUp = "gainUp" + i;
            let gainDown = "gainDown" + i;
            let btnPhase = "buttonPhase" + i;
            let quarterSliderContainer = "quarterSliderContainer" + i;
            let canvasSliderMark = "canvasSliderMarks" + i;
            let sliderVertical = "sliderVertical" + i;

            $("#gainMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterDb", innerHTML: "dB" }));
            $("#" + quarter).append($("<input>").prop({ id: gainInput, className: "itemQuarterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<canvas>").prop({ id: canvasVuMarks, className: "itemQuarterVuMeterBackground" }));
            $("#" + quarter).append($("<div>").prop({ id: itemVuMeter, className: "itemQuarterVuMeter" }));

            $("#" + itemVuMeter).append($("<div>").prop({ id: gainSoloVu, className: "gainSoloVuMeter" }));

            $("#" + quarter).append($("<button>").prop({ id: gainUp, className: "itemQuarterButtonVolUp" }));
            $("#" + gainUp).append($("<div>").prop({ className: "media" }));
            $("#" + gainUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));

            $("#" + quarter).append($("<button>").prop({ id: gainDown, className: "itemQuarterButtonVolDown" }));
            $("#" + gainDown).append($("<div>").prop({ className: "media" }));
            $("#" + gainDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<button>").prop({ id: btnPhase, className: "itemQuarterButtonPhase" }));
            $("#" + btnPhase).append($("<div>").prop({ className: "media" }));
            $("#" + btnPhase + ">.media").append($("<img>").prop({ className: "buttonPhase", src: "./img/Polarity.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterSliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderContainer" }));
        }
        $("#itemQuarter1").remove();
    }

    $.fn.setVisualBridge();
}

//SETUP DELAY MAIN PANEL 
$.fn.setupDelaySolo = function(type) {
    //Empty delay panel
    $("#delayMainPanel").prop("innerHTML", "");


    if (type >= 0 && type < 5) {
        for (i = 0; i < channelCount; i++) {
            let quarter = "itemQuarterDelay" + i;
            let delayEna = "buttonDelay" + i;
            let delayTotal = "itemQuarterTotalDelay" + i;
            let delayInput = "delay" + i;
            let delayMeterInput = "delayMeter" + i;

            let delayUp = "delayUp" + i;
            let delayDown = "delayDown" + i;

            let quarterSliderContainer = "quarterDelaySliderContainer" + i;
            let canvasSliderMark = "canvasDelaySliderMarks" + i;
            let sliderVertical = "sliderDelayVertical" + i;

            $("#delayMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter" }));
            $("#" + quarter).append($("<button>").prop({ id: delayEna, className: "itemQuarterButtonDelayEnable", innerHTML: "Enable" }));
            $("#" + quarter).append($("<span>").prop({ id: delayTotal, className: "itemQuarterTotalDelay" }))
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterMs", innerHTML: "ms" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterM", innerHTML: "m" }));
            $("#" + quarter).append($("<input>").prop({ id: delayInput, className: "itemQuarterDelayTextField", value: 0.0, type: "number" }));
            $("#" + quarter).append($("<input>").prop({ id: delayMeterInput, className: "itemQuarterDelayMeterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<button>").prop({ id: delayUp, className: "itemQuarterButtonDelayUp" }));
            $("#" + delayUp).append($("<div>").prop({ className: "media" }));
            $("#" + delayUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
            $("#" + quarter).append($("<button>").prop({ id: delayDown, className: "itemQuarterButtonDelayDown" }));
            $("#" + delayDown).append($("<div>").prop({ className: "media" }));
            $("#" + delayDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterDelaySliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderDelayContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderDelayContainer" }));
        }

    } else if (type == 5 || type == 6) {

        for (i = 0; i < channel1Count; i++) {
            let quarter = "itemQuarterDelay" + i;
            let delayEna = "buttonDelay" + i;
            let delayTotal = "itemQuarterTotalDelay" + i;
            let delayInput = "delay" + i;
            let delayMeterInput = "delayMeter" + i;

            let delayUp = "delayUp" + i;
            let delayDown = "delayDown" + i;

            let quarterSliderContainer = "quarterDelaySliderContainer" + i;
            let canvasSliderMark = "canvasDelaySliderMarks" + i;
            let sliderVertical = "sliderDelayVertical" + i;

            $("#delayMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter" }));
            $("#" + quarter).append($("<button>").prop({ id: delayEna, className: "itemQuarterButtonDelayEnable", innerHTML: "Enable" }));
            $("#" + quarter).append($("<span>").prop({ id: delayTotal, className: "itemQuarterTotalDelay" }))
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterMs", innerHTML: "ms" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterM", innerHTML: "m" }));
            $("#" + quarter).append($("<input>").prop({ id: delayInput, className: "itemQuarterDelayTextField", value: 0.0, type: "number" }));
            $("#" + quarter).append($("<input>").prop({ id: delayMeterInput, className: "itemQuarterDelayMeterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<button>").prop({ id: delayUp, className: "itemQuarterButtonDelayUp" }));
            $("#" + delayUp).append($("<div>").prop({ className: "media" }));
            $("#" + delayUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
            $("#" + quarter).append($("<button>").prop({ id: delayDown, className: "itemQuarterButtonDelayDown" }));
            $("#" + delayDown).append($("<div>").prop({ className: "media" }));
            $("#" + delayDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterDelaySliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderDelayContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderDelayContainer" }));
        }

    } else if (type == 7 || type == 8) {
        for (i = 0; i < channel16Count; i++) {
            let quarter = "itemQuarterDelay" + i;
            let delayEna = "buttonDelay" + i;
            let delayTotal = "itemQuarterTotalDelay" + i;
            let delayInput = "delay" + i;
            let delayMeterInput = "delayMeter" + i;

            let delayUp = "delayUp" + i;
            let delayDown = "delayDown" + i;

            let quarterSliderContainer = "quarterDelaySliderContainer" + i;
            let canvasSliderMark = "canvasDelaySliderMarks" + i;
            let sliderVertical = "sliderDelayVertical" + i;

            $("#delayMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter16" }));
            $("#" + quarter).append($("<button>").prop({ id: delayEna, className: "itemQuarter16ButtonDelayEnable", innerHTML: "Enable" }));
            $("#" + quarter).append($("<span>").prop({ id: delayTotal, className: "itemQuarterTotalDelay" }))
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarter16Ms", innerHTML: "ms" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarter16M", innerHTML: "m" }));
            $("#" + quarter).append($("<input>").prop({ id: delayInput, className: "itemQuarter16DelayTextField", value: 0.0, type: "number" }));
            $("#" + quarter).append($("<input>").prop({ id: delayMeterInput, className: "itemQuarter16DelayMeterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<button>").prop({ id: delayUp, className: "itemQuarter16ButtonDelayUp" }));
            $("#" + delayUp).append($("<div>").prop({ className: "media" }));
            $("#" + delayUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
            $("#" + quarter).append($("<button>").prop({ id: delayDown, className: "itemQuarter16ButtonDelayDown" }));
            $("#" + delayDown).append($("<div>").prop({ className: "media" }));
            $("#" + delayDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarter16DelaySliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderDelayContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderDelayContainer" }));
        }
    } else if (type == 9) {
        for (i = 0; i < channelCount; i++) {
            let quarter = "itemQuarterDelay" + i;
            let delayEna = "buttonDelay" + i;
            let delayTotal = "itemQuarterTotalDelay" + i;
            let delayInput = "delay" + i;
            let delayMeterInput = "delayMeter" + i;

            let delayUp = "delayUp" + i;
            let delayDown = "delayDown" + i;

            let quarterSliderContainer = "quarterDelaySliderContainer" + i;
            let canvasSliderMark = "canvasDelaySliderMarks" + i;
            let sliderVertical = "sliderDelayVertical" + i;

            $("#delayMainPanel").append($("<div>").prop({ id: quarter, className: "itemQuarter" }));
            $("#" + quarter).append($("<button>").prop({ id: delayEna, className: "itemQuarterButtonDelayEnable", innerHTML: "Enable" }));
            $("#" + quarter).append($("<span>").prop({ id: delayTotal, className: "itemQuarterTotalDelay" }))
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterMs", innerHTML: "ms" }));
            $("#" + quarter).append($("<div>").prop({ className: "itemQuarterM", innerHTML: "m" }));
            $("#" + quarter).append($("<input>").prop({ id: delayInput, className: "itemQuarterDelayTextField", value: 0.0, type: "number" }));
            $("#" + quarter).append($("<input>").prop({ id: delayMeterInput, className: "itemQuarterDelayMeterTextField", value: 0.0, type: "number" }));

            $("#" + quarter).append($("<button>").prop({ id: delayUp, className: "itemQuarterButtonDelayUp" }));
            $("#" + delayUp).append($("<div>").prop({ className: "media" }));
            $("#" + delayUp + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Up.png" }));
            $("#" + quarter).append($("<button>").prop({ id: delayDown, className: "itemQuarterButtonDelayDown" }));
            $("#" + delayDown).append($("<div>").prop({ className: "media" }));
            $("#" + delayDown + ">.media").append($("<img>").prop({ className: "buttonVolume", src: "./img/Down.png" }));

            $("#" + quarter).append($("<div>").prop({ id: quarterSliderContainer, className: "itemQuarterDelaySliderContainer" }));
            $("#" + quarterSliderContainer).append($("<canvas>").prop({ id: canvasSliderMark, className: "sliderDelayContainerBackground" }));
            $("#" + quarterSliderContainer).append($("<div>").prop({ id: sliderVertical, className: "sliderDelayContainer" }));
        }

        $("#itemQuarterDelay1").remove();
    }

    $.fn.setVisualBridge();
}

//INITIALIZE THE DRAGGABILITY OF THE PEQ
$.fn.initiatePEQDraggie = function() {
    //ENABLE EACH PEQS TO BE DRAGGABLE AND SET FUNCTION TO peqDrag EVENTS
    for (var i = 0; i < eqCount; i++) {
        var a = "#dragPEQ" + i;

        // IF XLOCK AND YLOCK IS ENABLE ----> DISABLE THE DRAG AND DROP
        if (widgetPEQMainXLock === true && widgetPEQMainYLock === true) {
            peqDrag[i] = $(a).draggabilly('disable');
        } else if (widgetPEQMainXLock === true && widgetPEQMainYLock === false) {
            peqDrag[i] = $(a).draggabilly({ containment: "#dragWidgetPEQ", axis: "x" });
            peqDrag[i] = $(a).draggabilly('enable');
        } else if (widgetPEQMainXLock === false && widgetPEQMainYLock === true) {
            peqDrag[i] = $(a).draggabilly({ containment: "#dragWidgetPEQ", axis: "y" });
            peqDrag[i] = $(a).draggabilly('enable');
        } else if (widgetPEQMainXLock === false && widgetPEQMainYLock === false) {
            peqDrag[i] = $(a).draggabilly({ containment: "#dragWidgetPEQ", axis: "null" });
            peqDrag[i] = $(a).draggabilly('enable');
        }

        // IF PEQ FILTER IS NO GAIN NEEDED FIX THE GAIN AXE AND SET VALUE TO 0
        if ($.inArray(arrayEqParam[i].type, [2, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >= 0) {
            peqDrag[i] = $(a).draggabilly({ containment: "#dragWidgetPEQ", axis: "x" });
            arrayEqParam[i].gain = 0;
            $.fn.draggieSetPosition(i);
            peqDrag[i] = $(a).draggabilly('enable');
        } else
        if ($.inArray(arrayEqParam[i].type, [2, 7, 8, 9, 10, 11, 12, 13, 14, 15]) >= 0 && widgetPEQMainYLock === true) {
            // console.log("var test eq type = 1");
            peqDrag[i] = $(a).draggabilly('disable');
        }

        //EXECUTE AFTER RELEASE EQ
        peqDrag[i].on("dragEnd", function() {});
        //GET THE DRAGGABILLY INSTANCE FROM A JQUERY OBJECT 
        peqDraggie[i] = peqDrag[i].data("draggabilly");
        //EXECUTE DURING THE peqDrag AND DROP OPERATION EQ
        peqDrag[i].on("dragMove", function() {
            //FIND NUMBER IN ID (FROM 0 TO 11);
            var num = parseInt(this.id.toString().match(/(\d+)/g).map(Number));
            peqSoloSelected = num;
            var freq = 0;
            var gain = 0;

            gain = Math.round(gainFromY((peqDraggie[num].position.y - widgetPEQMarginTop + 8)) * 100) / 100;
            if (gain > gainScaleMaxPEQ) {
                gain = gainScaleMaxPEQ;
            }
            if (gain < gainScaleMinPEQ) {
                gain = gainScaleMinPEQ;
            }
            if (displaySoloGroup === 0)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].gain = gain;
            else
                arrayGroup[groupGroupSelected].peq[num].gain = gain;

            freq = Math.round(freqFromX((peqDraggie[num].position.x - widgetPEQMarginLeft)));
            if (freq > freqScaleMaxPEQ) {
                freq = freqScaleMaxPEQ;
            }
            if (freq < freqScaleMinPEQ) {
                freq = freqScaleMinPEQ;
            }
            if (displaySoloGroup === 0)
                arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].peq.peq[num].frequency = freq;
            else
                arrayGroup[groupGroupSelected].peq[num].frequency = freq;

            $.fn.setDataSoloPEQ(num, 5);

        });

        if (arrayEqParam[i].ena === true) {
            $("#dragPEQ" + i).draggabilly('enable');
            if (!$("#dragPEQ" + i).hasClass("enable"))
                $("#dragPEQ" + i).toggleClass("enable");
            if (!$("#label" + i).hasClass("enable"))
                $("#label" + i).toggleClass("enable");
            if (!$("#peqAnav" + i).hasClass("enable"))
                $("#peqAnav" + i).toggleClass("enable");

        }
    }
};

//SETUP PEQ MAIN PANEL FOR AMP VIEW (TYPE) DEFINE IF IT'S IN THE CHANNEL PATH (0) OR GROUP (1)
$.fn.setupPeqSolo = function(type) {

    // displayVal("setupPeqSolo", type);
    if (type === 0) {
        $("#peqMainPanel").html("");
        $("#peqMainPanel").append($("<div>").prop({ id: "peqItemFull", className: "itemFull" }));
        $("#peqGroupPanel").html("");
    } else if (type === 1) {
        $("#peqGroupPanel").html("");
        $("#peqGroupPanel").append($("<div>").prop({ id: "peqItemFull", className: "itemFullGroup" }));
        $("#peqMainPanel").html("");
    }

    //BUTTON LOCK MAG
    $("#peqItemFull").append($("<button>").prop({ id: "eqLockMag", className: "itemFullButtonLockMag" }));
    $("#eqLockMag").append($("<div>").prop({ id: "eqLockMagDiv", className: "media" }));
    $("#eqLockMagDiv").append($("<img>").prop({ src: "./img/LockMag.png", className: "logoPeqViewButton" }));

    //BUTTON LOCK FREQ
    $("#peqItemFull").append($("<button>").prop({ id: "eqLockFreq", className: "itemFullButtonLockFreq" }));
    $("#eqLockFreq").append($("<div>").prop({ id: "eqLockFreqDiv", className: "media" }));
    $("#eqLockFreqDiv").append($("<img>").prop({ src: "./img/LockFreq.png", className: "logoPeqViewButton" }));

    //BUTTON VIEW
    $("#peqItemFull").append($("<button>").prop({ id: "eqView", className: "itemFullButtonView" }));
    $("#eqView").attr("data-toggle", "modal");
    $("#eqView").attr("data-target", "#peqViewModeModal");
    $("#eqView").append($("<div>").prop({ id: "eqModalViewDiv", className: "media" }));
    $("#eqModalViewDiv").append($("<img>").prop({ src: "./img/View.png", className: "logoPeqViewButton" }));

    //DRAWING AREA FOR PEQ
    $("#peqItemFull").append($("<div>").prop({ id: "widgetParamEQ" }));

    //PARAMETERS AREA FOR PEQ
    $("#peqItemFull").append($("<div>").prop({ id: "parametersArea" }));

    //PEQ NAVBAR
    $("#parametersArea").append($("<div>").prop({ id: "peqNavBar", className: "peqNavBar" }));

    //PEQ SOLO PARAMETERS AREA
    $("#parametersArea").append($("<div>").prop({ id: "paramPEQArea" }));

    //NAV BAR AREA
    var str = "";
    str += "<nav aria-label= \"Page navigation example\">";
    str += "<ul class=\"pagination \">";
    str += "<li class=\"page-item\">";
    str += "<a class=\"page-link peqButtonNavBar\" href=\"#peq\" id=\"peqAnav99\" aria-label=\"Previous\">ALL &nbsp";
    str += "<span aria-hidden=\"true\"><img src=\"./img/PEQ.png\" height=\"24px\"></span>";
    str += "<span class=\"sr-only\">Bell Sym</span>";
    str += "</a>";
    str += "</li>";
    for (var i = 0; i < eqCount; i++) {
        str += "<li class=\"page-item\">";
        str += "<a class=\"page-link peqButtonNavBar\" href=\"#peq\"  id=\"peqAnav" + i + "\" aria-label=\"Previous\">PEQ " + (i + 1) + "&nbsp";
        str += "<span aria-hidden=\"true\"><img id=\"peqImgNav" + i + "\" src=\"./img/peq/peq0.png\" height=\"24px\"></span>";
        str += "<span class=\"sr-only\">Bell Sym</span>";
        str += "</a>";
        str += "</li>";
    }
    if (type === 0) {
        str += "<li class=\"page-item\">";
        str += "<a class=\"page-link peqButtonNavBar\" href=\"#peq\" id=\"peqAnav100\" aria-label=\"Previous\">";
        str += "<span aria-hidden=\"true\"><img src=\"./img/copy.png\" height=\"24px\"></span>";
        str += "</a>";
        str += "</li>";
    }
    if (type === 1) {
        str += "<li class=\"page-item\">";
        str += "<a class=\"page-link peqButtonNavBar\" href=\"#peq\" id=\"peqAnav200\" aria-label=\"Previous\">";
        str += "<span aria-hidden=\"true\"><img src=\"./img/copy.png\" height=\"24px\"></span>";
        str += "</a>";
        str += "</li>";
    }
    str += "</ul>";
    str += "</nav>";

    $("#peqNavBar").append(str);

    $("#paramPEQArea").append($("<div>").prop({ id: "parametersAreaEQ99" }));

    // FIRST COLUMN FOR PEQ PARAMETERS FROM 1 TO 6
    $("#parametersAreaEQ99").append($("<div>").prop({ id: "parametersAreaL" }));
    $("#parametersAreaL").append($("<table>").prop({ id: "peqTableParametersL" }))

    //CREATE HEADER COLUMN TITLE
    var trL = $("<tr></tr>").text("");
    $("#peqTableParametersL").append(trL);
    var t1L = $("<td></td>").text("Band");
    var t2L = $("<td></td>").text("Ena");
    var t3L = $("<td></td>").text("Filter type");
    var t4L = $("<td></td>").text("Freq. (Hz)");
    var t5L = $("<td></td>").text("Gain (dB)");
    var t6L = $("<td></td>").text("Q");

    trL.append(t1L);
    trL.append(t2L);
    trL.append(t3L);
    trL.append(t4L);
    trL.append(t5L);
    trL.append(t6L);

    for (var i = 0; i < eqCount / 2; i++) {
        let tr = $("<tr></tr>").text("");
        $("#peqTableParametersL").append(tr);

        //INSERT INPUTS AND SELECTORS FOR EVERY EQs
        let cell1 = $("<td></td>").text((i + 1));
        let cell2 = $("<td></td>").html("<input id=\"eqEna" + i + "\" type=\"checkbox\" class=\"enaInputPEQ\" name=\"enaPEQ\" test />");
        let cell3 = $("<td></td>").html("<select id=\"eqType" + i + "\" class=\"eqTypeSelect\"><option value=\"0\">Bell-Sym</option><option value=\"1\">Bell-ASym</option><option value=\"2\">Notch</option><option value=\"3\">Low-Shelving 6dB/oct</option><option value=\"4\">Low-Shelving 12dB/oct</option><option value=\"5\">High-Shelving 6dB/oct</option><option value=\"6\">High-Shelving 12dB/oct</option><option value=\"7\">All-Pass 90°</option><option value=\"8\">All-Pass 180°</option><option value=\"9\">High-Pass 6dB/oct</option><option value=\"10\">High-Pass 12dB/oct</option><option value=\"11\">High-Pass VariQ 12dB/oct</option><option value=\"12\">Low-Pass 6dB/oct</option><option value=\"13\">Low-Pass 12dB/oct</option><option value=\"14\">Low-Pass VariQ 12dB/oct</option><option value=\"15\">Band-Pass</option></select>");
        let cell4 = $("<td></td>").html("<input id=\"freq_text" + i + "\" type=\"number\" step=\"1\" class=\"freqInputPEQ\">");
        let cell5 = $("<td></td>").html("<input id=\"gain_text" + i + "\" type=\"number\" step=\"0.1\" class=\"gainInputPEQ\">");
        let cell6 = $("<td></td>").html("<input id=\"q_text" + i + "\" type=\"number\" step=\"0.01\" class=\"qInputPEQ\">");

        tr.append(cell1);
        tr.append(cell2);
        tr.append(cell3);
        tr.append(cell4);
        tr.append(cell5);
        tr.append(cell6);
    }

    // SECOND COLUMN FOR PEQ PARAMETERS FROM 7 TO 12
    $("#parametersAreaEQ99").append($("<div>").prop({ id: "parametersAreaR" }));
    $("#parametersAreaR").append($("<table>").prop({ id: "peqTableParametersR" }));

    //CREATE HEADER COLUMN TITLE
    var trR = $("<tr></tr>").text("");
    $("#peqTableParametersR").append(trR);
    var t1R = $("<td></td>").text("Band");
    var t2R = $("<td></td>").text("Ena");
    var t3R = $("<td></td>").text("Filter type");
    var t4R = $("<td></td>").text("Freq. (Hz)");
    var t5R = $("<td></td>").text("Gain (dB)");
    var t6R = $("<td></td>").text("Q");

    trR.append(t1R);
    trR.append(t2R);
    trR.append(t3R);
    trR.append(t4R);
    trR.append(t5R);
    trR.append(t6R);

    for (var i = 0; i < eqCount / 2; i++) {
        j = i + eqCount / 2;
        let tr = $("<tr></tr>").text("");
        $("#peqTableParametersR").append(tr);

        //INSERT INPUTS AND SELECTORS FOR EVERY EQs
        let cell1 = $("<td></td>").text((j + 1));
        let cell2 = $("<td></td>").html("<input id=\"eqEna" + j + "\" type=\"checkbox\" class=\"enaInputPEQ\" name=\"enaPEQ\" test />");
        let cell3 = $("<td></td>").html("<select id=\"eqType" + j + "\" class=\"eqTypeSelect\"><option value=\"0\">Bell-Sym</option><option value=\"1\">Bell-ASym</option><option value=\"2\">Notch</option><option value=\"3\">Low-Shelving 6dB/oct</option><option value=\"4\">Low-Shelving 12dB/oct</option><option value=\"5\">High-Shelving 6dB/oct</option><option value=\"6\">High-Shelving 12dB/oct</option><option value=\"7\">All-Pass 90°</option><option value=\"8\">All-Pass 180°</option><option value=\"9\">High-Pass 6dB/oct</option><option value=\"10\">High-Pass 12dB/oct</option><option value=\"11\">High-Pass VariQ 12dB/oct</option><option value=\"12\">Low-Pass 6dB/oct</option><option value=\"13\">Low-Pass 12dB/oct</option><option value=\"14\">Low-Pass VariQ 12dB/oct</option><option value=\"15\">Band-Pass</option></select>");
        let cell4 = $("<td></td>").html("<input id=\"freq_text" + j + "\" type=\"number\" step=\"1\" class=\"freqInputPEQ\">");
        let cell5 = $("<td></td>").html("<input id=\"gain_text" + j + "\" type=\"number\" step=\"0.1\" class=\"gainInputPEQ\">");
        let cell6 = $("<td></td>").html("<input id=\"q_text" + j + "\" type=\"number\" step=\"0.01\" class=\"qInputPEQ\">");

        tr.append(cell1);
        tr.append(cell2);
        tr.append(cell3);
        tr.append(cell4);
        tr.append(cell5);
        tr.append(cell6);
    }

    //CREATE DIV AREA FOR EDITING PEQs PARAMETERS IN SOLO
    for (var i = 0; i < eqCount; i++) {
        var id = "parametersAreaEQ" + i;
        var idRem = "#" + id
        $(idRem).remove();
        var div = document.createElement("div");
        div.id = id;
        div.style.marginTop = 10 + "px";
        var str = "";

        str += "<div class=\"slidersPEQContainer\">";
        str += "<div class=\"container123\">";
        str += "<div class=\"row\">";

        //ENABLE EQ BUTTON TOGGLE
        //SELECT TYPE EQ BUTTON 
        str += "</div>";
        str += "<div class=\"row justify-content-md-center\">";
        str += "<div class=\"col-lg-1 col-md-2 bgPEQParameterAreaSolo\">";
        str += "<h6 id=\"peqType" + i + "\"></h6>";
        str += "<div class=\"enaInputPEQSolo\"> ";
        str += "<input type=\"checkbox\" class=\"ios8-switch enaInputPEQ\" id=\"enaTogglePEQ" + i + "\" > ";
        str += "<label  for=\"enaTogglePEQ" + i + "\"></label>";
        str += "</div>"
        str += "<button class=\"peqButtonTypeSolo\"  id=\"typeButtonPEQ" + i + "\"  data-toggle=\"modal\" data-target=\"#modalPeqType\" data-id=\"" + i + "\"><img id=\"peqImgSolo" + i + "\" src=\"./img/peq/peq0.png\" class=\"peqTypeImageButton\"></button>";
        str += "</div>"

        //RANGE SLIDER FOR FREQ, GAIN AND Q
        str += "<div class=\"col-lg-3 col-md-11 bgPEQParameterAreaSolo\">";
        str += "<h6 class=\"col-12\">Freq. (Hz)</h6>";
        str += "<div class=\"row\">";
        str += "<div class=\"col-sm\"><button id=\"freqButtonDown" + i + "\" class=\"btn btn-outline-dark btn-sm mb-2 soloPEQFreqButtonDown\">&nbsp-&nbsp</button></div>";
        str += "<div class=\"col-sm\"><input id=\"freq_textSolo" + i + "\" type=\"number\" step=\"1\" class=\"freqInputPEQ form-control form-control-sm\"></div>";
        str += "<div class=\"col-sm\"><button id=\"freqButtonUp" + i + "\" class=\"btn btn-outline-dark btn-sm mb-2 soloPEQFreqButtonUp\">&nbsp+&nbsp</button></div>";
        str += "</div>";
        str += "<div class=\"row\">";
        str += "<div class=\"col col-lg-1\"></div>";
        str += "<div id=\"sliderHorizontalFreqPEQ" + i + "\" class=\"sliderHorizontalFreqPEQ col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
        str += "<div class=\"col col-lg-1\"></div>";
        str += "</div>";
        str += "</div>";
        str += "<div class=\"col-lg-3 col-md-11 bgPEQParameterAreaSolo\">";
        str += "<h6>Gain (dB)</h6>";
        str += "<div class=\"row\">";
        str += "<div class=\"col-sm\"><button id=\"gainButtonDown" + i + "\" class=\"btn btn-outline-dark btn-sm mb-2 soloPEQGainButtonDown\">&nbsp-&nbsp</button></div>";
        str += "<div class=\"col-sm\"><input id=\"gain_textSolo" + i + "\" type=\"number\" step=\"0.1\" class=\"gainInputPEQ form-control form-control-sm\"></div>";
        str += "<div class=\"col-sm\"><button id=\"gainButtonUp" + i + "\" class=\"btn btn-outline-dark btn-sm mb-2 soloPEQGainButtonUp\">&nbsp+&nbsp</button></div>";
        str += "</div>";
        str += "<div class=\"row\">";
        str += "<div class=\"col col-lg-1\"></div>";
        str += "<div id=\"sliderHorizontalGainPEQ" + i + "\" class=\"sliderHorizontalGainPEQ col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
        str += "<div class=\"col col-lg-1\"></div>";
        str += "</div>";
        str += "</div>";
        str += "<div class=\"col-lg-3 col-md-11 bgPEQParameterAreaSolo\">";
        str += "<h6>Q</h6>"
        str += "<div class=\"row\">";
        str += "<div class=\"col-sm\"><button id=\"qButtonDown" + i + "\" class=\"btn btn-outline-dark btn-sm mb-2 soloPEQQButtonDown\">&nbsp-&nbsp</button></div>";
        str += "<div class=\"col-sm\"><input id=\"q_textSolo" + i + "\" type=\"number\" step=\"0.01\" class=\"qInputPEQ form-control form-control-sm\"></div>";
        str += "<div class=\"col-sm\"><button id=\"qButtonUp" + i + "\" class=\"btn btn-outline-dark btn-sm mb-2 soloPEQQButtonUp\">&nbsp+&nbsp</button></div>";
        str += "</div>";
        str += "<div class=\"row\">";
        str += "<div class=\"col col-lg-1\"></div>";
        str += "<div id=\"sliderHorizontalQPEQ" + i + "\" class=\"sliderHorizontalQPEQ col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
        str += "<div class=\"col col-lg-1\"></div>";
        str += "</div>";
        str += "</div>";
        str += "</div>";
        str += "</div>";

        str += "</div>";
        div.innerHTML = str;
        $("#paramPEQArea").append(div);
        $(idRem).hide();
    }

    // PEQ SOLO COPY MODULE

    $("#paramPEQArea").append($("<div>").prop({ id: "parametersAreaEQ100" }));
    $("#parametersAreaEQ100").append($("<div>").prop({ id: "parametersAreaEQ100Panel", className: "row justify-content-md-center" }))
    if ($.fn.getModel() != 5 && $.fn.getModel() != 6) {
        $("#parametersAreaEQ100Panel").append($("<div>").prop({ id: "peqCopyPanel", className: "col-xl-3 col-lg-6 col-md-11 bgPEQParameterAreaSolo" }))
        $("#peqCopyPanel").append($("<div>").prop({ innerHTML: "<h6>COPY :</h6>", className: "peqResetArea" }));
        $("#peqCopyPanel").append($("<div>").prop({ id: "peqCopySource" }));
        $("#peqCopySource").append($("<table>").prop({ id: "peqCopySourceTable", className: "peqCopySource" }))
        var str = "";
        str += "<tr>"
        for (var d = 0; d < 4; d++)
            str += "<td>PEQ &nbsp" + (d + 1) + " &nbsp<input id=\"peqCopySelected" + d + "\" type=\"checkbox\" class=\"peqCopySelected\"/>";
        str += "</tr>";
        str += "<tr>"
        for (var d = 4; d < 8; d++)
            str += "<td>PEQ &nbsp" + (d + 1) + " &nbsp<input id=\"peqCopySelected" + d + "\" type=\"checkbox\" class=\"peqCopySelected\"/>";
        str += "</tr>";
        str += "<tr>"
        for (var d = 8; d < 12; d++)
            str += "<td>PEQ &nbsp" + (d + 1) + " &nbsp<input id=\"peqCopySelected" + d + "\" type=\"checkbox\" class=\"peqCopySelected\"/>";
        str += "</tr>";

        $("#peqCopySourceTable").html(str);
        $("#peqCopyPanel").append($("<button>").prop({ id: "peqCopySelectAll", className: "peqCopySelectAllButton", innerHTML: "ALL" }));


        // PEQ COPY MODULE SOURCE COPY FROM :
        $("#peqCopyPanel").append($("<span>").prop({ innerHTML: "<h6>FROM :</h6>" }));
        $("#peqCopyPanel").append($("<div>").prop({ id: "peqCopySourceChannel", innerHTML: "" }));
        $("#peqCopySourceChannel").append($("<table>").prop({ id: "peqCopySourceChannelTable", className: "peqCopySource" }))

        if ($.fn.getModel() == 7 || $.fn.getModel() == 8) {
            for (var i = 0; i < channelCount; i++) {
                $("#peqCopySourceChannelTable").append($("<tr>").prop({ id: "peqCopySourceChannelTableRow" + i }));
                for (var j = 0; j < channelCount; j++) {
                    var str = "";
                    str += "<label for=\"inlineRadio" + ((i * 4) + j) + "\" class=\"form-check-label peqCopyLabel\">&nbsp; Channel " + labelOverviewChannel[((i * 4) + j)] + " &nbsp</label>";
                    str += "<input id=\"inlineRadio" + ((i * 4) + j) + "\" class=\"peqCopyChannelSourceRadio\" type=\"radio\" name=\"peqCopyOptions\">"
                    $("#peqCopySourceChannelTableRow" + i).append($("<td>").prop({ innerHTML: str }));
                }
            }
        } else if ($.fn.getModel() < 5) {
            $("#peqCopySourceChannelTable").append($("<tr>").prop({ id: "peqCopySourceChannelTableRow0" }));
            for (var j = 0; j < channelCount; j++) {
                var str = "";
                str += "<label for=\"inlineRadio" + j + "\" class=\"form-check-label peqCopyLabel\">&nbsp; Channel " + labelOverviewChannel[j] + " &nbsp</label>";
                str += "<input id=\"inlineRadio" + j + "\" class=\"peqCopyChannelSourceRadio\" type=\"radio\" name=\"peqCopyOptions\">"
                $("#peqCopySourceChannelTableRow0").append($("<td>").prop({ innerHTML: str }));
            }
        }

        // PEQ COPY MODULE SOURCE COPY TO :
        $("#peqCopyPanel").append($("<span>").prop({ innerHTML: "<h6>TO :</h6>" }));
        $("#peqCopyPanel").append($("<div>").prop({ id: "peqCopySourceChannelDest" }));
        $("#peqCopySourceChannelDest").append($("<table>").prop({ id: "peqCopySourceChannelDestTable", className: "peqCopySource" }))

        if ($.fn.getModel() == 7 || $.fn.getModel() == 8) {
            for (var i = 0; i < channelCount; i++) {
                $("#peqCopySourceChannelDestTable").append($("<tr>").prop({ id: "peqCopySourceChannelTableDestRow" + i }));
                for (var j = 0; j < channelCount; j++) {
                    $("#peqCopySourceChannelTableDestRow" + i).append($("<td>").prop({ type: "checkbox", innerHTML: "&nbsp Channel " + labelOverviewChannel[((i * 4) + j)] + " &nbsp<input id=\"peqCopyChannelDest" + ((i * 4) + j) + "\" type=\"checkbox\" class=\"peqCopyChannelDest\"/>" }));
                }
            }
        } else if ($.fn.getModel() < 5) {
            $("#peqCopySourceChannelDestTable").append($("<tr>").prop({ id: "peqCopySourceChannelTableDestRow0" }));
            for (var j = 0; j < channelCount; j++) {
                $("#peqCopySourceChannelTableDestRow0").append($("<td>").prop({ type: "checkbox", innerHTML: "&nbsp Channel " + labelOverviewChannel[j] + " &nbsp<input id=\"peqCopyChannelDest" + j + "\" type=\"checkbox\" class=\"peqCopyChannelDest\"/>" }));
            }

        }

        $("#peqCopyPanel").append($("<button>").prop({ id: "peqCopyApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));
    }

    //SET TO DEFAULT VALUE PEQ MODULE 

    $("#parametersAreaEQ100Panel").append($("<div>").prop({ id: "peqResetPanel", className: "col-xl-3 col-lg-6 col-md-11 bgPEQParameterAreaSolo" }))

    $("#peqResetPanel").append($("<div>").prop({ id: "peqResetFlatAll", className: "peqResetArea" }));
    $("#peqResetFlatAll").append($("<span>").prop({ className: "", innerHTML: "<h6>Flat All PEQs : &nbsp</h6>" }));
    $("#peqResetFlatAll").append($("<button>").prop({ id: "peqFlatApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));

    $("#peqResetPanel").append($("<div>").prop({ id: "peqResetDefaultAll", className: "peqResetArea" }));
    $("#peqResetDefaultAll").append($("<span>").prop({ className: "", innerHTML: "<h6>Default values PEQs : &nbsp</h6>" }));
    $("#peqResetDefaultAll").append($("<button>").prop({ id: "peqDefaultApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));

    $("#peqResetPanel").append($("<div>").prop({ id: "peqResetDefaultChannelAll", className: "peqResetArea" }));
    $("#peqResetDefaultChannelAll").append($("<span>").prop({ className: "", innerHTML: "<h6>Default values PEQs for all channels : &nbsp</h6>" }));
    $("#peqResetDefaultChannelAll").append($("<button>").prop({ id: "peqDefaultAllApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));

    $("#parametersAreaEQ100").hide();




    // PEQ GROUP COPY MODULE

    $("#paramPEQArea").append($("<div>").prop({ id: "parametersAreaEQ200" }));
    $("#parametersAreaEQ200").append($("<div>").prop({ id: "parametersAreaEQ200Panel", className: "row justify-content-md-center" }))
        // if ($.fn.getModel() != 5 && $.fn.getModel() != 6) {
    $("#parametersAreaEQ200Panel").append($("<div>").prop({ id: "peqCopyGroupPanel", className: "col-xl-3 col-lg-6 col-md-11 bgPEQParameterAreaSolo" }))
    $("#peqCopyGroupPanel").append($("<div>").prop({ innerHTML: "<h6>COPY :</h6>", className: "peqResetArea" }));
    $("#peqCopyGroupPanel").append($("<div>").prop({ id: "peqCopyGroupSource" }));
    $("#peqCopyGroupSource").append($("<table>").prop({ id: "peqCopyGroupSourceTable", className: "peqCopySource" }))
    var str = "";
    str += "<tr>"
    for (var d = 0; d < 4; d++)
        str += "<td>PEQ &nbsp" + (d + 1) + " &nbsp<input id=\"peqCopyGroupSelected" + d + "\" type=\"checkbox\" class=\"peqCopyGroupSelected\"/>";
    str += "</tr>";
    str += "<tr>"
    for (var d = 4; d < 8; d++)
        str += "<td>PEQ &nbsp" + (d + 1) + " &nbsp<input id=\"peqCopyGroupSelected" + d + "\" type=\"checkbox\" class=\"peqCopyGroupSelected\"/>";
    str += "</tr>";
    str += "<tr>"
    for (var d = 8; d < 12; d++)
        str += "<td>PEQ &nbsp" + (d + 1) + " &nbsp<input id=\"peqCopyGroupSelected" + d + "\" type=\"checkbox\" class=\"peqCopyGroupSelected\"/>";
    str += "</tr>";

    $("#peqCopyGroupSourceTable").html(str);
    $("#peqCopyGroupPanel").append($("<button>").prop({ id: "peqCopyGroupSelectAll", className: "peqCopySelectAllButton", innerHTML: "ALL" }));


    // PEQ COPY MODULE SOURCE COPY FROM :
    $("#peqCopyGroupPanel").append($("<span>").prop({ innerHTML: "<h6>FROM :</h6>" }));
    $("#peqCopyGroupPanel").append($("<div>").prop({ id: "peqCopyGroupSourceChannel", innerHTML: "" }));
    $("#peqCopyGroupSourceChannel").append($("<table>").prop({ id: "peqCopyGroupSourceChannelTable", className: "peqCopySource" }))


    for (var i = 0; i < 2; i++) {
        $("#peqCopyGroupSourceChannelTable").append($("<tr>").prop({ id: "peqCopyGroupSourceChannelTableRow" + i }));
        for (var j = 0; j < 3; j++) {
            var str = "";
            str += "<label for=\"inlineRadioGroup" + ((i * 3) + j) + "\" class=\"form-check-label peqCopyLabel\">&nbsp; Group " + ((i * 3) + j + 1) + " &nbsp</label>";
            str += "<input id=\"inlineRadioGroup" + ((i * 3) + j) + "\" class=\"peqCopyGroupSourceRadio\" type=\"radio\" name=\"peqCopyGroupOptions\">"
            $("#peqCopyGroupSourceChannelTableRow" + i).append($("<td>").prop({ innerHTML: str }));
        }
    }


    // PEQ COPY MODULE SOURCE COPY TO :
    $("#peqCopyGroupPanel").append($("<span>").prop({ innerHTML: "<h6>TO :</h6>" }));
    $("#peqCopyGroupPanel").append($("<div>").prop({ id: "peqCopyGroupSourceChannelDest" }));
    $("#peqCopyGroupSourceChannelDest").append($("<table>").prop({ id: "peqCopyGroupSourceChannelDestTable", className: "peqCopySource" }))


    for (var i = 0; i < 2; i++) {
        $("#peqCopyGroupSourceChannelDestTable").append($("<tr>").prop({ id: "peqCopyGroupSourceChannelTableDestRow" + i }));
        for (var j = 0; j < 3; j++) {
            $("#peqCopyGroupSourceChannelTableDestRow" + i).append($("<td>").prop({ type: "checkbox", innerHTML: "&nbsp Group " + ((i * 3) + j + 1) + " &nbsp<input id=\"peqCopyGroupChannelDest" + ((i * 3) + j) + "\" type=\"checkbox\" class=\"peqCopyGroupDest\"/>" }));
        }
    }
    $("#peqCopyGroupPanel").append($("<button>").prop({ id: "peqCopyGroupApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));
    // }

    //SET TO DEFAULT VALUE PEQ MODULE 

    $("#parametersAreaEQ200Panel").append($("<div>").prop({ id: "peqGroupResetPanel", className: "col-xl-3 col-lg-6 col-md-11 bgPEQParameterAreaSolo" }))

    $("#peqGroupResetPanel").append($("<div>").prop({ id: "peqGroupResetCurrent", className: "peqResetArea" }));
    $("#peqGroupResetCurrent").append($("<span>").prop({ className: "", innerHTML: "<h6>Default Group PEQs : &nbsp</h6>" }));
    $("#peqGroupResetCurrent").append($("<button>").prop({ id: "peqGroupResetCurrentApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));

    $("#parametersAreaEQ200").hide();



    //FILL CONTENT OF MODAL WINDOWS
    $("#modalPeqTabContent").html("");

    var number_of_rows = 4;
    var number_of_cols = 4;
    var table_body = "<table class=\"peqModalType\">";
    for (var i = 0; i < number_of_rows; i++) {
        table_body += "<tr>";
        for (var j = 0; j < number_of_cols; j++) {
            var t = i * 4 + j;
            table_body += "<td>";
            table_body += "<button class=\"btn btn-default peqModalTypeBtn\" id=\"peqTypeModal" + t + "\">";
            table_body += "<div class=\"media\">";
            table_body += "<img class=\"peqModalTypeLogo logoPeqViewButton\" src=\"./img/peq/peq" + t + ".png\">";
            table_body += "</div>";
            table_body += "<div class=\"peqModalTypeText\">" + peqLabel[t] + "</div>";
            table_body += "</button>";
            table_body += "</td>";
            // displayVal("T", t);
        }
        table_body += "</tr>";
    }
    table_body += "</table>";
    $("#modalPeqTabContent").html(table_body);
    $('#peqModalType td').each(function() {
        var min = 10; // Define a minimum
        var step = 5 * $(this).index(); // Define Step(your step is 5 here)
        $(this).css('width', (min + step) + "px"); // css attribute of your <td> width:15px; i.e.
    });
};

//DRAW PEQ (mode = 0 : only Mag, mode = 1 : only phase, mode = 2 : dual view) (scale = 0 : -36 to 18, scale = 1 : -18 to 18, scale = 2 : -6 to 6) (phase 0 : phase 180, phase = 1 : phase 360)
$.fn.initPEQ = function(mode, scale, phase) {

    peqViewMode = mode;
    peqGainScaleType = scale;
    peqPhaseScaleType = phase;

    $("#canvasWidgetPEQ").remove();
    $("#graphWidgetPEQ").remove();
    $("#dragWidgetPEQ").remove();

    for (var i = 0; i < eqCount; i++) {
        var t = "#dragPEQ" + i;
        $(t).remove();
    }

    if (arrayEqParam === null) {
        arrayEqParam = new Array(eqCount);
        for (var i = 0; i < eqCount; i++) {
            arrayEqParam[i] = new EqParam(eqEnaDefault, eqFreqDefault, eqGainDefault, eqQDefault, eqTypeDefault, new AParam(), new BParam(), eqXLockDefault, eqYLockDefault);
            arrayEqParam[i].frequency = eqFreqDefaultInit[i];
        }
    }
    for (var i = 0; i < eqCount; i++) {
        peqTabMagX[i] = new Array(graphPEQWidth);
        peqTabPhaX[i] = new Array(graphPEQWidth);
        for (var j = 0; j < graphPEQWidth; j++) {
            peqTabMagX[i][j] = 0;
            peqTabPhaX[i][j] = 0;
        }
    }
    graphPEQHeight = widgetPEQY - widgetPEQMarginTop - widgetPEQMarginBottom;

    if (peqViewMode === 2)
        graphPEQWidth = widgetPEQX - widgetPEQMarginLeft - widgetPEQMarginRightDual;
    else
        graphPEQWidth = widgetPEQX - widgetPEQMarginLeft - widgetPEQMarginRight;

    //BACKGROUND INIT
    var canvasPEQ = document.createElement("canvas");
    canvasPEQ.id = "canvasWidgetPEQ";
    canvasPEQ.width = widgetPEQX;
    canvasPEQ.height = widgetPEQY;
    $("#widgetParamEQ").append(canvasPEQ);

    //CURVE DRAWING AREA INIT
    var graphPEQ = document.createElement("canvas");
    graphPEQ.id = "graphWidgetPEQ";
    graphPEQ.width = graphPEQWidth;
    graphPEQ.height = graphPEQHeight;
    graphPEQ.style.marginTop = "" + widgetPEQMarginTop + "px";
    graphPEQ.style.marginLeft = "" + widgetPEQMarginLeft + "px";
    $("#widgetParamEQ").append(graphPEQ);

    //CREATE peqDrag AREA FOR PEQ
    var dragPEQ = document.createElement("div");
    dragPEQ.id = "dragWidgetPEQ";
    dragPEQ.setAttribute("style", "width:" + (graphPEQWidth) + "px; height:" + (graphPEQHeight + 6) + "px; margin-top:" + widgetPEQMarginTop + "px; margin-left: " + (widgetPEQMarginLeft - 9) + "px;");
    $("#widgetParamEQ").append(dragPEQ);

    //INIT EXTERNAL CANVAS
    var c = document.getElementById("canvasWidgetPEQ");
    if (c != null) {
        var ctx = c.getContext("2d");
        c.style.width = widgetPEQX;
        c.style.height = widgetPEQY;
        ctx.beginPath();

        //BG COLOR
        ctx.rect(0, 0, widgetPEQX, widgetPEQY);
        ctx.fillStyle = "#0a1a29";
        ctx.fill();

        //VERTICAL AXE

        //MAG ONLY
        if (peqViewMode === 0) {
            var localGainGap = Math.max(...gain_scalePEQ[peqGainScaleType]) - Math.min(...gain_scalePEQ[peqGainScaleType]);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < gain_scalePEQ_line[peqGainScaleType].length; i++) {
                var step = localGainGap / (gain_scalePEQ_line[peqGainScaleType].length - 1);
                step = step * graphPEQHeight / localGainGap;
                ctx.moveTo(widgetPEQMarginLeft, widgetPEQMarginTop + i * step);
                ctx.lineTo(widgetPEQX - widgetPEQMarginRight, widgetPEQMarginTop + i * step);
                ctx.stroke();
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "right";
                if (gain_scalePEQ[peqGainScaleType].includes(gain_scalePEQ_line[peqGainScaleType][i]) != 0)
                    ctx.fillText(gain_scalePEQ_line[peqGainScaleType][i].toString(), widgetPEQMarginLeft - 5, widgetPEQMarginTop + i * step + 5);
            }
            yZeroPEQ = yFromGain(0);
        }
        //PHASE ONLY 
        else if (peqViewMode === 1) {
            var localPhaseGap = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < phase_scale_line[peqPhaseScaleType].length; i++) {
                var step = localPhaseGap / (phase_scale_line[peqPhaseScaleType].length - 1);
                step = step * graphPEQHeight / localPhaseGap;
                ctx.moveTo(widgetPEQMarginLeft, widgetPEQMarginTop + i * step);
                ctx.lineTo(widgetPEQX - widgetPEQMarginRight, widgetPEQMarginTop + i * step);
                ctx.stroke();
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "right";
                if (phase_scale[peqPhaseScaleType].includes(phase_scale_line[peqPhaseScaleType][i]) != 0)
                    ctx.fillText(phase_scale_line[peqPhaseScaleType][i].toString() + "°", widgetPEQMarginLeft - 5, widgetPEQMarginTop + i * step + 5);
            }
            yZeroPEQ = yFromGain(0);
        }
        //MAG + PHASE
        else if (peqViewMode === 2) {
            var localGainGap = Math.max(...gain_scalePEQ[peqGainScaleType]) - Math.min(...gain_scalePEQ[peqGainScaleType]);
            // displayVal("gap", localGainGap);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < gain_scalePEQ_line[peqGainScaleType].length; i++) {
                var step = localGainGap / (gain_scalePEQ_line[peqGainScaleType].length - 1);
                step = step * graphPEQHeight / localGainGap;
                ctx.moveTo(widgetPEQMarginLeft, widgetPEQMarginTop + i * step);
                ctx.lineTo(widgetPEQX - widgetPEQMarginRightDual, widgetPEQMarginTop + i * step);
                ctx.stroke();
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "right";
                if (gain_scalePEQ[peqGainScaleType].includes(gain_scalePEQ_line[peqGainScaleType][i]) != 0)
                    ctx.fillText(gain_scalePEQ_line[peqGainScaleType][i].toString(), widgetPEQMarginLeft - 5, widgetPEQMarginTop + i * step + 5);
            }
            yZeroPEQ = yFromGain(0);

            var localPhaseGap = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);
            // displayVal("gap", localPhaseGap);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < phase_scale_line[peqPhaseScaleType].length; i++) {
                //ADJUST RIGHT ANGULAR SCALE TO FITS WITH A NON SYMETRICAL (AROUND 0dB)
                if (peqGainScaleType === 2)
                    var step = localPhaseGap / (phase_scale_line[peqPhaseScaleType].length + 4 - 1);
                else
                    var step = localPhaseGap / (phase_scale_line[peqPhaseScaleType].length - 1);
                step = step * graphPEQHeight / localPhaseGap;

                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "left";
                if (phase_scale[peqPhaseScaleType].includes(phase_scale_line[peqPhaseScaleType][i]) != 0)
                    ctx.fillText(phase_scale_line[peqPhaseScaleType][i].toString() + "°", widgetPEQX - widgetPEQMarginRightDual + 5, widgetPEQMarginTop + i * step + 5);
            }
        }

        //FREQUENCY AXE

        ctx.strokeStyle = "#3e4954";
        var j = 0;
        ctx.font = "12px Arial";
        ctx.fillStyle = "white";
        ctx.textAlign = "center";
        // displayVal("size widget Y", widgetPEQX);
        var a = widgetPEQY;
        for (var i = 0; i < freq_scale_line.length; i++) {
            ctx.moveTo(xFromFreq(freq_scale_line[i]) + widgetPEQMarginLeft, widgetPEQMarginTop);
            if (peqViewMode === 2) {
                a = graphPEQHeight + widgetPEQMarginTop + widgetPEQMarginBottom;
                ctx.lineTo(xFromFreq(freq_scale_line[i]) + widgetPEQMarginLeft, a - widgetPEQMarginBottom);
            } else
                ctx.lineTo(xFromFreq(freq_scale_line[i]) + widgetPEQMarginLeft, widgetPEQY - widgetPEQMarginBottom);
            ctx.stroke();
            if (freq_scale.includes(freq_scale_line[i]) != 0) {
                if (i === 0)
                    ctx.fillText(freq_scale_text[j].toString(), widgetPEQMarginLeft, a - 10);
                else
                    ctx.fillText(freq_scale_text[j].toString(), xFromFreq(freq_scale_line[i]) + widgetPEQMarginLeft, a - 10);
                j++;
            }
        }

        if (peqViewMode === 2)
            ctx.strokeRect(widgetPEQMarginLeft, widgetPEQMarginTop, widgetPEQX - widgetPEQMarginLeft - widgetPEQMarginRightDual, a - widgetPEQMarginTop - widgetPEQMarginBottom);
        else
            ctx.strokeRect(widgetPEQMarginLeft, widgetPEQMarginTop, widgetPEQX - widgetPEQMarginLeft - widgetPEQMarginRight, a - widgetPEQMarginTop - widgetPEQMarginBottom);

        //INITIALIZE 12 PEQS

        //ADD WHITE BORDER TRANSPARENT BACKGROUND AND NUMBER ON EACH PEQs
        if (peqViewMode != 1) {
            for (var i = 0; i < eqCount; i++) {
                var divLabelGraphPEQ = document.createElement("div");
                divLabelGraphPEQ.id = "dragPEQ" + i;
                divLabelGraphPEQ.className = "circleEq";

                var bgCirclePEQ = document.createElement("div");
                bgCirclePEQ.className = "bgCircleEq";

                var labelGraphPEQ = document.createElement("p");
                labelGraphPEQ.id = "label" + i;
                labelGraphPEQ.className = "labelEq";

                var num = i + 1;
                labelGraphPEQ.innerHTML = "" + num;
                $("#widgetParamEQ").append(divLabelGraphPEQ);

                var t = "#dragPEQ" + i;
                arrayEqParamDraggable[i] = $(t);

                arrayEqParamDraggable[i].append(bgCirclePEQ);
                arrayEqParamDraggable[i].append(labelGraphPEQ);
            }
        }

        $.fn.initiatePEQDraggie();

        //SET INITIAL POSITION FOR EVERY PEQs DEPENDING ON THE DEFAULT VALUE

        for (var i = 0; i < eqCount; i++) {
            if (peqViewMode != 1)
                $.fn.draggieSetPosition(i);
            var ena = "#eqEna" + i;
            $(ena).prop('checked', arrayEqParam[i].ena);
            var type = "#eqType" + i;
            // displayValues("id", type, "value", arrayEqParam[i].type);
            $(type).val(arrayEqParam[i].type);

            var freq = "#freq_text" + i;
            $(freq).val(arrayEqParam[i].frequency);
            freq = "#freq_textSolo" + i;
            $(freq).val(arrayEqParam[i].frequency);

            var gain = "#gain_text" + i;
            $(gain).val(arrayEqParam[i].gain);
            gain = "#gain_textSolo" + i;
            $(gain).val(arrayEqParam[i].gain);

            var q = "#q_text" + i;
            $(q).val(arrayEqParam[i].q);
            q = "#q_textSolo" + i;
            $(q).val(arrayEqParam[i].q);

            var a = "#dragPEQ" + i;
            peqDrag[i] = $(a).draggabilly('disable');
        }
    }
}

//REDRAW CURVES
$.fn.drawPEQWidget = function(updatedPEQ) {
    // console.log("ID:" + n + " // X:" + Math.round(x*100)/100 + " // Y:" + Math.round(y*100)/100 + " // Freq:" + freqFromX(x) + " // gain:" + gainFromY(y));
    var c = document.getElementById("graphWidgetPEQ");
    if (c) {
        var ctx = c.getContext("2d");

        ctx.strokeStyle = '#00a3e0';
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.setLineDash([]);
        for (var x = 0; x < eqCount; x++) {
            //IF PEQ SELECTED TO UPDATE, WE COMPUTE NEW VALUES -- IF VALUE === 99 WE COMPUTE ALL THE VALUES FOR THE FIRST TIME
            if (arrayEqParam[x].ena === true)
            // displayVal("PEQ Array enable", x);

                if (x === updatedPEQ || updatedPEQ === 99) {
                    ctx.beginPath();
                    if (arrayEqParam[x].ena === true) {
                        computePEQCoeff(x);

                        for (var i = 0; i < graphPEQWidth; i++) {
                            var t = $.fn.processPEQ(i, x);
                            peqTabMagX[x][i] = t.magnitude;
                            peqTabPhaX[x][i] = t.phase;
                        }
                        //MAG ONLY
                        if (peqViewMode === 0) {
                            ctx.beginPath();
                            ctx.moveTo(-2, graphPEQHeight);
                            ctx.lineTo(-2, yFromGain(peqTabMagX[x][0]));
                            for (var i = 0; i < graphPEQWidth; i++) {
                                ctx.lineTo(i, yFromGain(peqTabMagX[x][i]));
                            }
                            ctx.lineTo(graphPEQWidth + 100, yFromGain(peqTabMagX[x][graphPEQWidth - 1]));
                            ctx.lineTo(graphPEQWidth + 100, graphPEQHeight);
                            ctx.fillStyle = "rgba(83, 230, 246, 0.2)";
                            ctx.fill("nonzero");
                        }
                        //PHASE ONLY 
                        else if (peqViewMode === 1) {}
                        //MAG + PHASE
                        else if (peqViewMode === 2) {
                            ctx.beginPath();
                            ctx.moveTo(-2, graphPEQHeight);
                            ctx.lineTo(-2, yFromGain(peqTabMagX[x][0]));
                            for (var i = 0; i < graphPEQWidth; i++) {
                                ctx.lineTo(i, yFromGain(peqTabMagX[x][i]))
                            }
                            ctx.lineTo(graphPEQWidth + 100, yZeroPEQ)
                            ctx.lineTo(graphPEQWidth, yFromGain(peqTabMagX[x][graphPEQWidth - 1]));
                            ctx.lineTo(graphPEQWidth + 100, graphPEQHeight);
                            ctx.fillStyle = "rgba(83, 230, 246, 0.2)";
                            ctx.fill("nonzero");
                        }
                        ctx.stroke();
                    }
                }
                //IF PEQ IS NOT UPDATED, WE TAKE VALUE FROM THE STORED ARRAY
                else {
                    ctx.beginPath();
                    if (arrayEqParam[x].ena === true) {
                        //MAG ONLY
                        if (peqViewMode === 0) {}
                        //PHASE ONLY 
                        else if (peqViewMode === 1) {}
                        //MAG + PHASE
                        else if (peqViewMode === 2) {}
                    }
                }
        }

        var valG = new Array(graphPEQWidth);
        var valP = new Array(graphPEQWidth);
        ctx.strokeStyle = '#fe8e00';
        ctx.lineWidth = 2;
        ctx.beginPath();
        for (var i = 0; i < graphPEQWidth; i++) {
            valG[i] = 0;
            valP[i] = 0;
            for (var x = 0; x < eqCount; x++) {
                if (arrayEqParam[x].ena === true) {
                    valG[i] = valG[i] + peqTabMagX[x][i];
                    valP[i] = valP[i] + peqTabPhaX[x][i];
                }
            }
        }
        //MAG ONLY
        if (peqViewMode === 0) {
            ctx.beginPath();
            ctx.strokeStyle = '#fe8e00';
            ctx.moveTo(-2, graphPEQHeight);
            ctx.lineTo(-2, yFromGain(valG[0]));
            for (var i = 0; i < graphPEQWidth; i++) {
                ctx.lineTo(i, yFromGain(valG[i]));
            }
            ctx.lineTo(graphPEQWidth + 100, yFromGain(valG[graphPEQWidth - 1]));
            ctx.lineTo(graphPEQWidth + 100, graphPEQHeight);
            ctx.fillStyle = "rgba(255, 142, 0, 0.1)";
            ctx.fill("nonzero");
            ctx.stroke();
        }
        //PHASE ONLY 
        else if (peqViewMode === 1) {
            ctx.beginPath();
            ctx.strokeStyle = '#fe8e00';
            ctx.moveTo(-2, yFromPhase(0));
            ctx.lineTo(-2, yFromPhase(valP[0]));
            for (var i = 0; i < graphPEQWidth; i++) {
                ctx.lineTo(i, yFromPhase(valP[i]));
            }
            ctx.lineTo(graphPEQWidth + 2, yFromPhase(valP[graphPEQWidth]));
            ctx.lineTo(graphPEQWidth + 2, yFromPhase(0));
            ctx.setLineDash([15, 15]);
            ctx.fillStyle = "rgba(255, 142, 0, 0.1)";
            ctx.fill("nonzero");
            ctx.stroke();
        }
        //MAG + PHASE
        else if (peqViewMode === 2) {
            ctx.beginPath();
            ctx.strokeStyle = '#fe8e00';
            ctx.moveTo(-2, graphPEQHeight);
            ctx.lineTo(-2, yFromGain(valG[0]));
            for (var i = 0; i < graphPEQWidth; i++) {
                ctx.lineTo(i, yFromGain(valG[i]));
            }
            ctx.lineTo(graphPEQWidth + 2, yFromGain(valG[graphPEQWidth - 1]));
            ctx.lineTo(graphPEQWidth + 2, graphPEQHeight);
            ctx.setLineDash([]);
            ctx.fillStyle = "rgba(255, 142, 0, 0.1)";
            ctx.fill("nonzero");
            ctx.stroke();
            ctx.beginPath();
            ctx.moveTo(-2, yFromPhase(0));
            ctx.lineTo(0, yFromPhase(valP[0]));
            for (var i = 0; i < graphPEQWidth; i++) {
                ctx.lineTo(i, yFromPhase(valP[i]));
            }
            ctx.lineTo(graphPEQWidth + 2, yFromPhase(valP[graphPEQWidth]));
            ctx.lineTo(graphPEQWidth + 2, yFromPhase(0));
            ctx.setLineDash([10, 5]);
            ctx.stroke();
        }

        //DRAW SUM CURVE ON PEQ CURVE
        //SUM OF PEQ AND CROSSOVER FILTER
        if (displaySoloGroup === 0) { //DRAW THE CROSSOVER ONLY IN CHANNEL MODE AND NOT IN GROUP MODE
            ctx.lineWidth = 1;
            for (var i = 0; i < graphPEQWidth; i++) {
                if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true) {
                    valG[i] = valG[i] + xoverTabMagX[0][i];
                    valP[i] = valP[i] + xoverTabPhaX[0][i];
                }
                if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true) {
                    valG[i] = valG[i] + xoverTabMagX[1][i];
                    valP[i] = valP[i] + xoverTabPhaX[1][i];
                }
            }

            //MAG ONLY
            if (peqViewMode === 0) {
                ctx.beginPath();
                ctx.strokeStyle = "rgba(230, 230, 230, 1)";
                ctx.moveTo(-2, graphPEQHeight + 2);
                ctx.lineTo(-2, yFromGain(valG[0]));
                for (var i = 0; i < graphPEQWidth; i++) {
                    ctx.lineTo(i, yFromGain(valG[i]));
                }
                ctx.lineTo(graphPEQWidth + 100, yFromGain(valG[graphPEQWidth - 1]));
                ctx.lineTo(graphPEQWidth + 100, graphPEQHeight);
                ctx.fillStyle = "rgba(255, 255, 255, .1)";
                ctx.fill("nonzero");
                ctx.setLineDash([]);
                ctx.stroke();
            }
            //PHASE ONLY 
            else if (peqViewMode === 1) {
                ctx.beginPath();
                ctx.strokeStyle = "rgba(230, 230, 230, 1)";
                ctx.moveTo(-100, yFromPhase(0));
                ctx.lineTo(0, yFromPhase(valP[0]));
                for (var i = 0; i < graphPEQWidth; i++) {
                    ctx.lineTo(i, yFromPhase(valP[i]));
                }
                ctx.lineTo(graphPEQWidth + 100, yFromPhase(valP[graphPEQWidth]));
                ctx.lineTo(graphPEQWidth + 100, yFromPhase(0));
                ctx.moveTo(-100, yFromGain(0));
                ctx.lineTo(-2, yFromGain(0));
                ctx.closePath();

                ctx.setLineDash([15, 15]);
                ctx.fillStyle = "rgba(255, 255, 255, .1)";
                ctx.fill("nonzero");
                ctx.stroke();
            }
            //MAG + PHASE
            else if (peqViewMode === 2) {
                ctx.beginPath();
                ctx.strokeStyle = "rgba(230, 230, 230, 1)";
                ctx.moveTo(-2, graphPEQHeight + 2);
                ctx.lineTo(-2, yFromGain(valG[0]));
                for (var i = 0; i < graphPEQWidth; i++) {
                    ctx.lineTo(i, yFromGain(valG[i]));
                }
                ctx.lineTo(graphPEQWidth + 100, yFromGain(valG[graphPEQWidth - 1]));
                ctx.lineTo(graphPEQWidth + 100, graphPEQHeight);
                ctx.setLineDash([]);
                ctx.fillStyle = "rgba(255, 255, 255,.1)";
                ctx.fill("nonzero");
                ctx.setLineDash([]);
                ctx.stroke();
                ctx.beginPath();
                ctx.moveTo(-100, yFromPhase(0));
                for (var i = 0; i < graphPEQWidth; i++) {
                    ctx.lineTo(i, yFromPhase(valP[i]));
                }
                ctx.lineTo(graphPEQWidth + 100, yFromPhase(valP[graphPEQWidth]));
                ctx.setLineDash([10, 5]);
                ctx.stroke();
            }
        }
    }
}

//SETUP XOVER MAIN PANEL FOR AMP VIEW
$.fn.setupXOVERSolo = function() {

    //ERASE PREVIOUS VERSION OF XOVER MAIN PANEL
    $("#xoverMainPanel").html("");

    //ITEM FULL FOR BACKGROUND
    $("#xoverMainPanel").append($("<div>").prop({ id: "xoverItemFull", className: "itemFull" }));

    //BUTTON VIEW
    $("#xoverItemFull").append($("<button>").prop({ id: "xoverView", className: "itemFullButtonViewXOVER" }));
    $("#xoverView").attr("data-toggle", "modal");
    $("#xoverView").attr("data-target", "#xoverViewModeModal");
    $("#xoverView").append($("<div>").prop({ id: "xoverModalViewDiv", className: "media" }));
    $("#xoverModalViewDiv").append($("<img>").prop({ src: "./img/View.png", className: "logoPeqViewButton" }));

    //DRAWING AREA FOR XOVER
    $("#xoverItemFull").append($("<div>").prop({ id: "widgetXOVER" }));

    //PARAMETERS AREA FOR XOVER
    $("#xoverItemFull").append($("<div>").prop({ id: "parametersAreaXOVER" }));

    //XOVER SOLO PARAMETERS AREA
    $("#parametersAreaXOVER").append($("<div>").prop({ id: "paramXOVERArea" }));

    $("#parametersAreaXOVER").css("margin-top", widgetPEQY + 20 + "px");

    var str = "";
    str += "<div class=\"slidersXOVERContainer\">";
    str += "<div class=\"container123\">";
    str += "<div class=\"row justify-content-md-center\">";

    //LOW PASS HIGH PASS FILTER BOX
    str += "<div class=\"col col-lg-5 col-md-10 bgPEQParameterAreaSolo\">";
    str += "<h6 class=\"col-12\">High-Pass</h6>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col-12\">";
    str += "<button class=\"typeFilterXOVER\" id=\"typeHighPassXover\" data-toggle=\"modal\" data-target=\"#modalXOVERTypeHighPass\"><img id=\"peqImgSolo\" src=\"./img/XOver.png\" height=\"24px\"></button>";
    str += "<span id=\"highPassXOVERLabel\" class=\"xoverLabel\"><\span>";
    str += "</div>";
    str += "<div class=\"col-12\">";
    str += "<input type=\"checkbox\" class=\"ios8-switch enaXOVER switchXOVER\" id=\"enaToggleHighPassXOVER\">";
    str += "<label class=\"switchXOVER\" for=\"enaToggleHighPassXOVER\"></label>";
    str += "</div>";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-2 col-md-2\"><button id=\"xoverHPFreqDownButton\" type=\"submit\" class=\"btn btn-outline-dark btn-sm mb-2\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-8 col-md-8\"><input id=\"freq_HighPassXOVER\" type=\"number\" step=\"1\" class=\"freqInputXOVER form-control form-control-sm\"></div>";
    str += "<div class=\"col-2 col-md-2\"><button id=\"xoverHPFreqUpButton\" type=\"submit\" class=\"btn btn-outline-dark btn-sm mb-2\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"sliderHorizontalHighPassXOVER\" class=\"sliderHorizontalFreqPEQ col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";
    str += "<div class=\"col-lg-auto col-md-0\"></div>";
    str += "<div class=\"col col-lg-5 col-md-10 bgPEQParameterAreaSolo\">";
    str += "<h6>Low-Pass</h6>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col-12\">";
    str += "<button class=\"typeFilterXOVER\"  id=\"typeLowPassXover\"  data-toggle=\"modal\" data-target=\"#modalXOVERTypeLowPass\"><img id=\"peqImgSolo\" src=\"./img/XOver.png\" height=\"24px\"></button>";
    str += "<span id=\"lowPassXOVERLabel\" class=\"xoverLabel\"><\span>";
    str += "</div>";
    str += "<div class=\"col-12\">";
    str += "<input type=\"checkbox\" class=\"ios8-switch enaXOVER switchXOVER\" id=\"enaToggleLowPassXOVER\">";
    str += "<label class=\"switchXOVER\" for=\"enaToggleLowPassXOVER\"></label>";
    str += "</div>";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-2 col-md-2\"><button id=\"xoverLPFreqDownButton\" type=\"submit\" class=\"btn btn-outline-dark btn-sm mb-2\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-8 col-md-8\"><input id=\"freq_LowPassXOVER\" type=\"number\" step=\"0.1\" class=\"freqInputXOVER form-control form-control-sm\"></div>";
    str += "<div class=\"col-2 col-md-2\"><button id=\"xoverLPFreqUpButton\" type=\"submit\" class=\"btn btn-outline-dark btn-sm mb-2\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"sliderHorizontalLowPassXOVER\" class=\"sliderHorizontalGainPEQ col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";
    str += "</div>";
    str += "</div>";
    $("#paramXOVERArea").html(str);

    $("#highPassXOVERLabel").html(xoverLabel[highPassDefaultType]);
    $("#lowPassXOVERLabel").html(xoverLabel[lowPassDefaultType]);

    //FILL CONTENT OF MODAL WINDOWS
    $("#modalXOVERTabContentHighPass").html("");
    $("#modalXOVERTabContentLowPass").html("");

    var number_of_rows = 5;
    var number_of_cols = 4;
    var table_body = "<table class=\"xoverModalType\">";
    for (var i = 0; i < number_of_rows; i++) {
        table_body += "<tr>";
        for (var j = 0; j < number_of_cols; j++) {
            var t = i * 4 + j;
            if (xoverLabel[t]) {
                table_body += "<td>";
                table_body += "<button class=\"btn btn-default xoverModalTypeBtn\" id=\"xoverTypeModalHighPass" + t + "\">";
                table_body += "<div class=\"media\">";
                table_body += "<img class=\"peqModalTypeLogo logoPeqViewButton\" src=\"./img/XOver.png\">";
                table_body += "</div>";
                table_body += "<div class=\"peqModalTypeText\">" + xoverLabel[t] + "</div>";
                table_body += "</button>";
                table_body += "</td>";
            }
        }
        table_body += "</tr>";
    }
    table_body += "</table>";

    $("#modalXOVERTabContentHighPass").html(table_body);

    table_body = "";
    table_body = "<table class=\"xoverModalType\">";
    for (var i = 0; i < number_of_rows; i++) {
        table_body += "<tr>";
        for (var j = 0; j < number_of_cols; j++) {
            var t = i * 4 + j;
            if (xoverLabel[t]) {
                table_body += "<td>";
                table_body += "<button class=\"btn btn-default xoverModalTypeBtn\" id=\"xoverTypeModalLowPass" + t + "\">";
                table_body += "<div class=\"media\">";
                table_body += "<img class=\"peqModalTypeLogo logoPeqViewButton\" src=\"./img/XOver.png\">";
                table_body += "</div>";
                table_body += "<div class=\"peqModalTypeText\">" + xoverLabel[t] + "</div>";
                table_body += "</button>";
                table_body += "</td>";
            }
        }
        table_body += "</tr>";
    }
    table_body += "</table>";

    $("#modalXOVERTabContentLowPass").html(table_body);
};

//DRAW XOVER (mode = 0 : only Mag, mode = 1 : only phase, mode = 2 : dual view) (scale = 0 : -12 to 6, scale = 1 : -24 to 6, scale = 2 : -48 to 6, scale = 3 : -120 to 10) (phase 0 : phase 180, phase = 1 : phase 360)
$.fn.initXOVER = function(mode, scale, phase) {

    peqViewMode = mode;
    xoverGainScaleType = scale;
    xoverPhaseScaleType = phase;

    $("#canvasWidgetXOVER").remove();
    $("#graphWidgetXOVER").remove();
    $("#widgetXOVER").html("");

    highPassEqParam = new XoverParam(eqEnaDefault, highPassDefaultFrequency, eqGainDefault, eqQDefault, highPassDefaultType, eqXLockDefault, eqYLockDefault);
    lowPassEqParam = new XoverParam(eqEnaDefault, lowPassDefaultFrequency, eqGainDefault, eqQDefault, lowPassDefaultType, eqXLockDefault, eqYLockDefault);

    graphXOVERHeight = widgetXOVERY - widgetXOVERMarginTop - widgetXOVERMarginBottom;

    if (peqViewMode === 2)
        graphXOVERWidth = widgetXOVERX - widgetXOVERMarginLeft - widgetXOVERMarginRightDual;
    else
        graphXOVERWidth = widgetXOVERX - widgetXOVERMarginLeft - widgetXOVERMarginRight;

    //BACKGROUND INIT
    var canvasXOVER = document.createElement("canvas");
    canvasXOVER.id = "canvasWidgetXOVER";
    canvasXOVER.width = widgetXOVERX;
    canvasXOVER.height = widgetXOVERY;
    $("#widgetXOVER").append(canvasXOVER);

    //CURVE DRAWING AREA INIT
    var graphXOVER = document.createElement("canvas");
    graphXOVER.id = "graphWidgetXOVER";
    graphXOVER.width = graphXOVERWidth;
    graphXOVER.height = graphXOVERHeight;
    graphXOVER.style.marginTop = "" + widgetXOVERMarginTop + "px";
    graphXOVER.style.marginLeft = "" + widgetXOVERMarginLeft + "px";
    $("#widgetXOVER").append(graphXOVER);

    //CREATE peqDrag AREA FOR PEQ
    var dragXOVER = document.createElement("div");
    dragXOVER.id = "dragWidgetXOVER";
    dragXOVER.setAttribute("style", "width:" + (graphXOVERWidth) + "px; height:" + (graphXOVERHeight + 6) + "px; margin-top:" + widgetXOVERMarginTop + "px; margin-left: " + (widgetXOVERMarginLeft - 9) + "px;");
    $("#widgetXOVER").append(dragXOVER);

    //INIT EXTERNAL CANVAS
    var c = document.getElementById("canvasWidgetXOVER");
    if (c != null) {
        var ctx = c.getContext("2d");
        c.style.width = widgetXOVERX;
        c.style.height = widgetXOVERY;
        ctx.beginPath();

        //BG COLOR
        ctx.rect(0, 0, widgetXOVERX, widgetXOVERY);
        ctx.fillStyle = "#0a1a29";
        ctx.fill();

        //VERTICAL AXE

        //MAG ONLY
        if (peqViewMode === 0) {
            var localGainGap = Math.max(...gain_scaleXOVER[xoverGainScaleType]) - Math.min(...gain_scaleXOVER[xoverGainScaleType]);
            // displayVal("gap", localGainGap);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < gain_scaleXOVER_line[xoverGainScaleType].length; i++) {
                var step = localGainGap / (gain_scaleXOVER_line[xoverGainScaleType].length - 1);
                step = step * graphXOVERHeight / localGainGap;
                ctx.moveTo(widgetXOVERMarginLeft, widgetXOVERMarginTop + i * step);
                ctx.lineTo(widgetXOVERX - widgetXOVERMarginRight, widgetXOVERMarginTop + i * step);
                ctx.stroke();
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "right";
                if (gain_scaleXOVER[xoverGainScaleType].includes(gain_scaleXOVER_line[xoverGainScaleType][i]) != 0)
                    ctx.fillText(gain_scaleXOVER_line[xoverGainScaleType][i].toString(), widgetXOVERMarginLeft - 5, widgetXOVERMarginTop + i * step + 5);
            }
            yZeroXOVER = yFromGainXOVER(0);
        }
        //PHASE ONLY 
        else if (peqViewMode === 1) {
            var localPhaseGap = Math.max(...phase_scale[xoverPhaseScaleType]) - Math.min(...phase_scale[xoverPhaseScaleType]);
            // displayVal("gap", localPhaseGap);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < phase_scale_line[xoverPhaseScaleType].length; i++) {
                var step = localPhaseGap / (phase_scale_line[xoverPhaseScaleType].length - 1);
                step = step * graphXOVERHeight / localPhaseGap;
                ctx.moveTo(widgetXOVERMarginLeft, widgetXOVERMarginTop + i * step);
                ctx.lineTo(widgetXOVERX - widgetXOVERMarginRight, widgetXOVERMarginTop + i * step);
                ctx.stroke();
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "right";
                if (phase_scale[xoverPhaseScaleType].includes(phase_scale_line[xoverPhaseScaleType][i]) != 0)
                    ctx.fillText(phase_scale_line[xoverPhaseScaleType][i].toString() + "°", widgetXOVERMarginLeft - 5, widgetXOVERMarginTop + i * step + 5);
            }
            yZeroXOVER = yFromGainXOVER(0);
        }
        //MAG + PHASE
        else if (peqViewMode === 2) {
            var localGainGap = Math.max(...gain_scaleXOVER[xoverGainScaleType]) - Math.min(...gain_scaleXOVER[xoverGainScaleType]);
            // displayVal("gap", localGainGap);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < gain_scaleXOVER_line[xoverGainScaleType].length; i++) {
                var step = localGainGap / (gain_scaleXOVER_line[xoverGainScaleType].length - 1);
                step = step * graphXOVERHeight / localGainGap;
                ctx.moveTo(widgetXOVERMarginLeft, widgetXOVERMarginTop + i * step);
                ctx.lineTo(widgetXOVERX - widgetXOVERMarginRightDual, widgetXOVERMarginTop + i * step);
                ctx.stroke();
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "right";
                if (gain_scaleXOVER[xoverGainScaleType].includes(gain_scaleXOVER_line[xoverGainScaleType][i]) != 0)
                    ctx.fillText(gain_scaleXOVER_line[xoverGainScaleType][i].toString(), widgetXOVERMarginLeft - 5, widgetXOVERMarginTop + i * step + 5);
            }
            yZeroXOVER = yFromGainXOVER(0);

            var localPhaseGap = Math.max(...phase_scale[xoverPhaseScaleType]) - Math.min(...phase_scale[xoverPhaseScaleType]);
            // displayVal("gap", localPhaseGap);
            ctx.strokeStyle = "#3e4954";
            for (var i = 0; i < phase_scale_line[xoverPhaseScaleType].length; i++) {

                var step = localPhaseGap / (phase_scale_line[xoverPhaseScaleType].length - 1);
                step = step * graphXOVERHeight / localPhaseGap;
                ctx.font = "12px Arial";
                ctx.fillStyle = "white";
                ctx.textAlign = "left";
                if (phase_scale[xoverPhaseScaleType].includes(phase_scale_line[xoverPhaseScaleType][i]) != 0)
                    ctx.fillText(phase_scale_line[xoverPhaseScaleType][i].toString() + "°", widgetXOVERX - widgetXOVERMarginRightDual + 5, widgetXOVERMarginTop + i * step + 5);
            }
        }

        //FREQUENCY AXE
        ctx.strokeStyle = "#3e4954";
        var j = 0;
        ctx.font = "12px Arial";
        ctx.fillStyle = "white";
        ctx.textAlign = "center";
        // displayVal("size widget Y", widgetPEQX);
        var a = widgetXOVERY;
        for (var i = 0; i < freq_scale_line.length; i++) {
            // displayVal("X", x - 1);
            ctx.moveTo(xFromFreqXOVER(freq_scale_line[i]) + widgetXOVERMarginLeft, widgetXOVERMarginTop);
            if (peqViewMode === 2) {
                a = graphXOVERHeight + widgetXOVERMarginTop + widgetXOVERMarginBottom;
                ctx.lineTo(xFromFreqXOVER(freq_scale_line[i]) + widgetXOVERMarginLeft, a - widgetXOVERMarginBottom);
            } else
                ctx.lineTo(xFromFreqXOVER(freq_scale_line[i]) + widgetXOVERMarginLeft, widgetXOVERY - widgetXOVERMarginBottom);
            ctx.stroke();
            if (freq_scale.includes(freq_scale_line[i]) != 0) {
                if (i === 0)
                    ctx.fillText(freq_scale_text[j].toString(), widgetXOVERMarginLeft, a - 10);
                else
                    ctx.fillText(freq_scale_text[j].toString(), xFromFreqXOVER(freq_scale_line[i]) + widgetXOVERMarginLeft, a - 10);
                j++;
            }
        }

        if (peqViewMode === 2)
            ctx.strokeRect(widgetXOVERMarginLeft, widgetXOVERMarginTop, widgetXOVERX - widgetXOVERMarginLeft - widgetXOVERMarginRightDual, a - widgetXOVERMarginTop - widgetXOVERMarginBottom);
        else
            ctx.strokeRect(widgetXOVERMarginLeft, widgetXOVERMarginTop, widgetXOVERX - widgetXOVERMarginLeft - widgetXOVERMarginRight, a - widgetXOVERMarginTop - widgetXOVERMarginBottom);

        //INITIALIZE HIGHPASS LOWPASS
        //ADD WHITE BORDER TRANSPARENT BACKGROUND AND NUMBER ON HIGHPASS AND LOWPASS
        if (peqViewMode != 1) {

            // HIGHPASS
            var divLabelGraphXOVERHighPass = document.createElement("div");
            divLabelGraphXOVERHighPass.id = "dragHighPass";
            divLabelGraphXOVERHighPass.className = "circleEq";

            var bgCircleXOVERHighPass = document.createElement("div");
            bgCircleXOVERHighPass.className = "bgCircleEq";

            var labelGraphXOVERHighPass = document.createElement("p");
            labelGraphXOVERHighPass.id = "labelHighPass";
            labelGraphXOVERHighPass.className = "labelEq";

            labelGraphXOVERHighPass.innerHTML = "H";
            $("#widgetXOVER").append(divLabelGraphXOVERHighPass);

            highPassDrag = $("#dragHighPass");

            $("#dragHighPass").append(bgCircleXOVERHighPass);
            $("#dragHighPass").append(labelGraphXOVERHighPass);

            // LOWPASS
            var divLabelGraphXOVERLowPass = document.createElement("div");
            divLabelGraphXOVERLowPass.id = "dragLowPass"
            divLabelGraphXOVERLowPass.className = "circleEq";

            var bgCircleXOVERLowPass = document.createElement("div");
            bgCircleXOVERLowPass.className = "bgCircleEq";

            var labelGraphXOVERLowPass = document.createElement("p");
            labelGraphXOVERLowPass.id = "labelLowPass";
            labelGraphXOVERLowPass.className = "labelEq";

            labelGraphXOVERLowPass.innerHTML = "L";
            $("#widgetXOVER").append(divLabelGraphXOVERLowPass);

            lowPassDrag = $("#dragLowPass");

            $("#dragLowPass").append(bgCircleXOVERLowPass);
            $("#dragLowPass").append(labelGraphXOVERLowPass);
        }

        //INITIALIZE TAB OF TEMP VALUE FOR DRAWING
        for (var i = 0; i < xoverCount; i++) {
            xoverTabMagX[i] = new Array(graphXOVERWidth);
            xoverTabPhaX[i] = new Array(graphXOVERWidth);
            for (var j = 0; j < graphXOVERWidth; j++) {
                xoverTabMagX[i][j] = 0;
                xoverTabPhaX[i][j] = 0;
            }
        }

        //SET INITIAL POSITION FOR EVERY XOVER DEPENDING ON THE DEFAULT VALUE
        $.fn.initiateXOVERDraggie();
        $.fn.initSlider();
        $.fn.setDataSoloXover(4, 99);
    }
}

//INITIALIZE THE DRAGGABILITY OF THE XOVER
$.fn.initiateXOVERDraggie = function() {
    //ENABLE HIGH PASS LOWW PASS TO BE DRAGGABLE AND SET FUNCTION TO peqDrag EVENTS
    highPassDrag = $("#dragHighPass").draggabilly({ containment: "#dragWidgetXOVER", axis: "x" });
    lowPassDrag = $("#dragLowPass").draggabilly({ containment: "#dragWidgetXOVER", axis: "x" });

    if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true)
        highPassDrag.draggabilly("enable");
    else
        highPassDrag.draggabilly("disable");

    if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true)
        lowPassDrag.draggabilly("enable");
    else
        lowPassDrag.draggabilly("disable");

    //EXECUTE AFTER RELEASE EQ
    highPassDrag.on("dragEnd", function() {
        //SEND EQ VALUES
    });
    lowPassDrag.on("dragEnd", function() {
        //SEND EQ VALUES
    });
    //GET THE DRAGGABILLY INSTANCE FROM A JQUERY OBJECT 
    highPassDraggie = highPassDrag.data("draggabilly");
    lowPassDraggie = lowPassDrag.data("draggabilly");
    //EXECUTE DURING THE peqDrag AND DROP OPERATION EQ
    highPassDrag.on("dragMove", function() {
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq = Math.round(freqFromXXOVER((highPassDraggie.position.x - widgetXOVERMarginLeft)));
        $.fn.setDataSoloXover(0, 2);
        // $.fn.setDataSoloXover(5, 2);
    });
    //EXECUTE DURING THE peqDrag AND DROP OPERATION EQ
    lowPassDrag.on("dragMove", function() {
        arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq = Math.round(freqFromXXOVER((lowPassDraggie.position.x - widgetXOVERMarginLeft)));
        $.fn.setDataSoloXover(1, 5);
        // $.fn.setDataSoloXover(6, 5);
    });
}

//REDRAW CURVES
$.fn.drawXOVERWidget = function(type, indice) {
    var c = document.getElementById("graphWidgetXOVER");
    if (c) {
        var ctx = c.getContext("2d");

        ctx.strokeStyle = '#00a3e0';
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.lineWidth = 2;
        ctx.beginPath();
        ctx.setLineDash([]);

        computeXOVERCoeff(type, indice);
        //IF HIGHPASS FILTER, WE ONLY COMPUTE HP VALUE, AND USE LP VALUE FROM MEMORY AND VICE VERSA
        ctx.beginPath();
        if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true || arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true) {
            //MAG ONLY
            if (peqViewMode === 0) {
                ctx.moveTo(-100, yFromGainXOVER($.fn.processXover(10, type, indice).magnitude));
                for (var i = 0; i < graphXOVERWidth; i++) {
                    var y = $.fn.processXover(i, type, indice);
                    ctx.lineTo(i, yFromGainXOVER(y.magnitude));
                    xoverTabMagX[type][i] = y.magnitude;
                    xoverTabPhaX[type][i] = y.phase;
                }
                var t = Math.round($.fn.processXover(graphXOVERWidth + 2, type, indice).magnitude);
                ctx.lineTo(graphXOVERWidth + 100, yFromGainXOVER(t));
                ctx.lineTo(graphXOVERWidth + 100, graphXOVERHeight + 100);
                ctx.lineTo(-100, graphXOVERHeight + 2)
                ctx.lineTo(-100, yFromGainXOVER($.fn.processXover(10, type, indice).magnitude));
                ctx.fillStyle = "rgba(83, 230, 246, 0.2)";
                ctx.fill("nonzero");
            }
            //PHASE ONLY 
            else if (peqViewMode === 1) {
                for (var i = 0; i < graphXOVERWidth; i++) {
                    var y = $.fn.processXover(i, type, indice);
                    xoverTabMagX[type][i] = y.magnitude;
                    xoverTabPhaX[type][i] = y.phase;
                }
            }
            //MAG + PHASE
            else if (peqViewMode === 2) {
                ctx.moveTo(-2, yFromGainXOVER($.fn.processXover(10, type, indice).magnitude));
                for (var i = 0; i < graphXOVERWidth; i++) {
                    var y = $.fn.processXover(i, type, indice);
                    ctx.lineTo(i, yFromGainXOVER(y.magnitude));
                    xoverTabMagX[type][i] = y.magnitude;
                    xoverTabPhaX[type][i] = y.phase;
                }
                var t = Math.round($.fn.processXover(graphXOVERWidth + 2, type, indice).magnitude);
                ctx.lineTo(graphXOVERWidth + 2, yFromGainXOVER(t));
                ctx.lineTo(graphXOVERWidth + 2, graphXOVERHeight + 2);
                ctx.lineTo(-10, graphXOVERHeight + 2)
                ctx.lineTo(-2, yFromGainXOVER($.fn.processXover(10, type, indice).magnitude));
                ctx.fillStyle = "rgba(83, 230, 246, 0.2)";
                ctx.fill("nonzero");
            }
            ctx.stroke();
        } else {
            // displayVal("true true enable", "test pass");
            for (var i = 0; i < xoverCount; i++) {
                for (var j = 0; j < graphXOVERWidth; j++) {
                    xoverTabMagX[i][j] = 0;
                    xoverTabPhaX[i][j] = 0;
                }
            }
        }

        ctx.beginPath();
        var valG = new Array(graphXOVERWidth);
        var valP = new Array(graphXOVERWidth);
        ctx.strokeStyle = 'rgba(254, 142, 0, 1)';
        ctx.lineWidth = 2;
        for (var i = 0; i < graphXOVERWidth; i++) {
            valG[i] = 0;
            valP[i] = 0;
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true) {
                valG[i] = valG[i] + xoverTabMagX[0][i];
                valP[i] = valP[i] + xoverTabPhaX[0][i];
            }
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true) {
                valG[i] = valG[i] + xoverTabMagX[1][i];
                valP[i] = valP[i] + xoverTabPhaX[1][i];
            }
        }
        //MAG ONLY
        if (peqViewMode === 0) {
            ctx.moveTo(0, yFromGainXOVER(valG[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromGainXOVER(valG[i]));
            }
        }
        //PHASE ONLY 
        else if (peqViewMode === 1) {
            ctx.moveTo(-100, yFromPhaseXOVER(0));
            ctx.lineTo(0, yFromPhaseXOVER(valP[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromPhaseXOVER(valP[i]));
            }
            ctx.setLineDash([15, 15]);
        }
        //MAG + PHASE
        else if (peqViewMode === 2) {
            ctx.moveTo(0, yFromGainXOVER(valG[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromGainXOVER(valG[i]));
            }
            ctx.setLineDash([]);
            ctx.strokeStyle = '#fe8e00';
            ctx.stroke();

            ctx.moveTo(-100, yFromPhaseXOVER(0));
            ctx.lineTo(-100, yFromPhaseXOVER(valP[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromPhaseXOVER(valP[i]));
            }
            ctx.lineTo(graphXOVERWidth + 100, yFromPhaseXOVER(valP[graphXOVERWidth]));
            ctx.lineTo(graphXOVERWidth + 100, yFromPhaseXOVER(0));
            ctx.setLineDash([10, 5]);
        }
        ctx.stroke();

        //DRAW SUM CURVE ON XOVER CURVE
        //SUM OF PEQ AND CROSSOVER FILTER
        ctx.beginPath();
        var valPEQG = new Array(graphXOVERWidth);
        var valPEQP = new Array(graphXOVERWidth);
        ctx.strokeStyle = "rgba(230, 230, 230, 1)";
        ctx.lineWidth = 2;
        for (var i = 0; i < graphXOVERWidth; i++) {
            valPEQG[i] = 0;
            valPEQP[i] = 0;
            for (var x = 0; x < eqCount; x++) {
                if (arrayEqParam[x].ena === true) {
                    valPEQG[i] = valPEQG[i] + peqTabMagX[x][i];
                    valPEQP[i] = valPEQP[i] + peqTabPhaX[x][i];
                }
            }
            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpEna === true) {
                valPEQG[i] = valPEQG[i] + xoverTabMagX[0][i];
                valPEQP[i] = valPEQP[i] + xoverTabPhaX[0][i];
            }

            if (arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpEna === true) {
                valPEQG[i] = valPEQG[i] + xoverTabMagX[1][i];
                valPEQP[i] = valPEQP[i] + xoverTabPhaX[1][i];
            }
        }

        //MAG ONLY
        if (peqViewMode === 0) {
            ctx.moveTo(0, yFromGainXOVER(valPEQG[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromGainXOVER(valPEQG[i]));
            }
            ctx.lineTo(graphXOVERWidth + 100, yFromGainXOVER(0));
            ctx.lineTo(graphXOVERWidth + 100, widgetXOVERY + 2);
            ctx.lineTo(-100, widgetXOVERY + 2);
            ctx.lineTo(-100, yFromGainXOVER(valPEQG[0]));
            ctx.closePath();
            ctx.fillStyle = "rgba(255, 255, 255, .1)";
            ctx.fill("nonzero");
            ctx.setLineDash([]);
            ctx.stroke();
        }
        //PHASE ONLY 
        else if (peqViewMode === 1) {
            ctx.moveTo(-100, yFromPhaseXOVER(0));
            ctx.lineTo(0, yFromPhaseXOVER(valPEQP[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromPhaseXOVER(valPEQP[i]));
            }
            ctx.lineTo(graphXOVERWidth + 100, yFromPhaseXOVER(valPEQP[graphXOVERWidth]));
            ctx.lineTo(graphXOVERWidth + 100, yFromPhaseXOVER(0));
            ctx.moveTo(-100, yFromGainXOVER(0));
            ctx.lineTo(-2, yFromGainXOVER(0));
            ctx.closePath();

            ctx.setLineDash([15, 15]);
            ctx.fillStyle = "rgba(255, 255, 255, .1)";
            ctx.fill("nonzero");
            ctx.stroke();
        }
        //MAG + PHASE
        else if (peqViewMode === 2) {
            ctx.moveTo(0, yFromGainXOVER(valPEQG[0]));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromGainXOVER(valPEQG[i]));
            }
            ctx.lineTo(graphXOVERWidth + 100, widgetXOVERY + 2);
            ctx.lineTo(-100, graphXOVERWidth + 100);
            ctx.lineTo(-100, yFromGainXOVER(valPEQG[0]));
            ctx.closePath();
            ctx.setLineDash([]);
            ctx.fillStyle = "rgba(255, 255, 255,.1)";
            ctx.fill("nonzero");
            ctx.setLineDash([]);
            ctx.stroke();

            ctx.moveTo(-100, yFromPhaseXOVER(0));
            for (var i = 0; i < graphXOVERWidth; i++) {
                ctx.lineTo(i, yFromPhaseXOVER(valPEQP[i]));
            }
            ctx.lineTo(graphXOVERWidth + 100, yFromPhaseXOVER(valPEQP[graphXOVERWidth]));

            ctx.setLineDash([10, 5]);
            ctx.stroke();
        }
        ctx.stroke();
    }
}

//SETUP THE LIMITER SOLO AREA AT THE FIRST LOADING OF THE PAGE
$.fn.setupLimiterSolo = function() {
    //ITEM FULL FOR BACKGROUND

    $("#limiterMainPanel").addClass("mainPanelLimiter");
    $("#limiterMainPanel").append($("<div>").prop({ id: "containerLimiter", className: "containerSoloLimiter container" }));

    //REAL TIME GRAPHIC AREA LIMITER
    $("#containerLimiter").append($("<div>").prop({ id: "outputPanelBackgroundLimiter", className: "outputPanelBackgroundLimiter" }));
    //FIRST LABEL TITLE "G-R dB"
    $("#outputPanelBackgroundLimiter").append($("<span>").prop({ id: "label1OutputLimiter", className: "label1OutLimiter" }));
    var label1 = "RMS Lim.";
    $("#label1OutputLimiter").html(label1);

    //SECOND LABEL TITLE "Peak dB"
    $("#outputPanelBackgroundLimiter").append($("<span>").prop({ id: "label2OutputLimiter", className: "label2OutLimiter" }));
    var label2 = "Peak Lim.";
    $("#label2OutputLimiter").html(label2);

    //THIRD LABEL TITLE "OUTPUT dBfs"
    $("#outputPanelBackgroundLimiter").append($("<span>").prop({ id: "label3OutputLimiter", className: "label3OutLimiter" }));
    var label3 = "Output dBfs";
    $("#label3OutputLimiter").html(label3);

    //VU METER G-R
    $("#outputPanelBackgroundLimiter").append($("<canvas>").prop({ id: "canvasVuMeterGRBGLimiter", className: "vuMeterRGCanvasLimiter", width: "40px", height: "100px" }));
    $("#outputPanelBackgroundLimiter").append($("<div>").prop({ id: "vuMeterGRBGLimiter", className: "vuMeterRGDivLimiter" }));
    $("#vuMeterGRBGLimiter").append($("<div>").prop({ id: "vuMeterGRBGLimiterCh", className: "limiterGRSoloVuMeter" }));

    //VU METER PEAK
    $("#outputPanelBackgroundLimiter").append($("<canvas>").prop({ id: "canvasVuMeterPeakBGLimiter", className: "vuMeterPeakCanvasLimiter", width: "40px", height: "100px" }));
    $("#outputPanelBackgroundLimiter").append($("<div>").prop({ id: "vuMeterPeakBGLimiter", className: "vuMeterPeakDivLimiter" }));
    $("#vuMeterPeakBGLimiter").append($("<div>").prop({ id: "vuMeterPeakBGLimiterCh", className: "limiterPeakSoloVuMeter" }));

    //VU METER LIMITER
    $("#outputPanelBackgroundLimiter").append($("<canvas>").prop({ id: "canvasVuMeterOutputBGLimiter", className: "vuMeterOutputCanvasLimiter", width: "40px", height: "100px" }));
    $("#outputPanelBackgroundLimiter").append($("<div>").prop({ id: "vuMeterOutputBGLimiter", className: "vuMeterOutputDivLimiter" }));
    $("#vuMeterOutputBGLimiter").append($("<div>").prop({ id: "vuMeterOutputBGLimiterCh", className: "limiterSoloVuMeter" }));


    //PARAMETERS AREA WITH A DIV FOR RMS STAGE
    $("#containerLimiter").append($("<div>").prop({ id: "rmsStageBackgroundLimiter", className: "rmsStageBackgroundLimiter" }));
    $("#rmsStageBackgroundLimiter").append($("<span>").prop({ id: "rmsStageLabelLimiter", className: "stageLabelBackgroundLimiter" }));
    $("#rmsStageBackgroundLimiter").append($("<button>").prop({ id: "rmsCalculator", className: "limiterCalc" }));
    $("#rmsCalculator").append($("<img>").prop({ id: "rmsCalcImg", src: "./img/Calculator.png", className: "limiterCalcIcon" }));

    var rmsStageTitle = "RMS stage";
    $("#rmsStageLabelLimiter").html(rmsStageTitle);

    var str = "";
    str += "<div class=\"row rowStageLimiter\">";
    str += "<div class=\"col-lg-4 col-md-12 bgLimiterParameterAreaSolo\">";
    str += "<h6 class=\"col-12\">Output (Vrms)</h6>";
    str += "<div class=\"row\" style=\"height: 12px;\">";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 thresRmsSoloLimiterBtnDown\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-sm\"><input id=\"thresRmsSoloLimiterInput\" type=\"number\" step=\"1\" class=\"inputFieldLimiter form-control form-control-sm\"></div>";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 thresRmsSoloLimiterBtnUp\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row nowrap\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"thresRmsSoloLimiterSlider\" class=\"col-10 col-sm-10 col-md-10 col-lg-10 sliderHorizontalLimiter\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";

    str += "<div class=\"col-lg-4 col-md-12 bgLimiterParameterAreaSolo\">";
    str += "<h6 class=\"col-12\">Attack (ms)</h6>";
    str += "<div class=\"row\" style=\"height: 12px;\">";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 attackRmsSoloLimiterBtnDown\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-sm\"><input id=\"attackRmsSoloLimiterInput\" type=\"number\" step=\"1\" class=\"inputFieldLimiter form-control form-control-sm\"></div>";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 attackRmsSoloLimiterBtnUp\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"attackRmsSoloLimiterSlider\" class=\"sliderHorizontalLimiter col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";

    str += "<div class=\"col-lg-4 col-md-12 bgLimiterParameterAreaSolo\">";
    str += "<h6 class=\"col-12\">Release (ms)</h6>";
    str += "<div class=\"row\" style=\"height: 12px;\">";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 releaseRmsSoloLimiterBtnDown\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-sm\"><input id=\"releaseRmsSoloLimiterInput\" type=\"number\" step=\"1\" class=\"inputFieldLimiter form-control form-control-sm\"></div>";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 releaseRmsSoloLimiterBtnUp\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"releaseRmsSoloLimiterSlider\" class=\"sliderHorizontalLimiter col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";
    str += "</div>";
    str += "</div>";

    $("#rmsStageBackgroundLimiter").append(str);

    //PARAMETERS AREA WITH A DIV FOR PEAK STAGE
    $("#containerLimiter").append($("<div>").prop({ id: "peakStageBackgroundLimiter", className: "peakStageBackgroundLimiter" }));
    $("#peakStageBackgroundLimiter").append($("<span>").prop({ id: "peakStageLabelLimiter", className: "stageLabelBackgroundLimiter" }));
    $("#peakStageBackgroundLimiter").append($("<button>").prop({ id: "peakCalculator", className: "limiterCalc" }));
    $("#peakCalculator").append($("<img>").prop({ id: "rmsCalcImg", src: "./img/Calculator.png", className: "limiterCalcIcon" }));

    var peakStageTitle = "Peak stage";
    $("#peakStageLabelLimiter").html(peakStageTitle);

    var str = "";
    str += "<div class=\"row rowStageLimiter\">";
    str += "<div class=\"col-lg-4 col-md-12 bgLimiterParameterAreaSolo container\">";
    str += "<h6 class=\"col-12\">Output (Vpeak)</h6>";
    str += "<div class=\"row\" style=\"height: 12px;\">";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 thresPeakSoloLimiterBtnDown\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-sm\"><input id=\"thresPeakSoloLimiterInput\" type=\"number\" step=\"1\" class=\"inputFieldLimiter form-control form-control-sm\"></div>";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 thresPeakSoloLimiterBtnUp\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"thresPeakSoloLimiterSlider\" class=\"sliderHorizontalLimiter col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";

    str += "<div class=\"col bgLimiterParameterAreaEmptySolo\">";
    str += "</div>";

    str += "<div class=\"col-lg-4 col-md-12 bgLimiterParameterAreaSolo\">";
    str += "<h6 class=\"col-12\">Release (ms)</h6>";
    str += "<div class=\"row\" style=\"height: 12px;\">";
    str += "</div>";
    str += "<div class=\"row\">";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 releasePeakSoloLimiterBtnDown\">&nbsp-&nbsp</button></div>";
    str += "<div class=\"col-sm\"><input id=\"releasePeakSoloLimiterInput\" type=\"number\" step=\"1\" class=\"inputFieldLimiter form-control form-control-sm\"></div>";
    str += "<div class=\"col-sm\"><button type=\"button\" class=\"btn btn-outline-dark btn-sm mb-2 releasePeakSoloLimiterBtnUp\">&nbsp+&nbsp</button></div>";
    str += "</div>";
    str += "<div class=\"row\" style=\"height: 32px;\">";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "<div id=\"releasePeakSoloLimiterSlider\" class=\"sliderHorizontalLimiter col-10 col-sm-10 col-md-10 col-lg-10\"></div>";
    str += "<div class=\"col col-lg-1\"></div>";
    str += "</div>";
    str += "</div>";
    str += "</div>";
    str += "</div>";

    $("#peakStageBackgroundLimiter").append(str);

    $("#thresRmsSoloLimiterInput").val(limiterRmsThresDefault);
    $("#attackRmsSoloLimiterInput").val(limiterRmsAttackDefault);
    $("#releaseRmsSoloLimiterInput").val(limiterRmsReleaseDefault);

    $("#thresPeakSoloLimiterInput").val(limiterPeakThresDefault);
    $("#releasePeakSoloLimiterInput").val(limiterPeakReleaseDefault);
}

//SETUP THE SPEAKER SOLO AREA AT THE FIRST LOADING OF THE PAGE
$.fn.setupSpeakerSolo = function() {

    if (demoMode === 0) {
        // $.fn.setDataSoloSpeaker(99);
    } else {
        var tempFolders = new foldersConstructor(demoFolderCount);
        for (var j = 0; j < demoFolderCount; j++) {
            tempFolders.folderList[j].name = "Folder " + (j + 1);
        }
        arrayAmplifier[soloAmplifierSelected].folderSpeaker = tempFolders;
        arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderCount = demoFolderCount;

        for (var a = 0; a < demoFolderCount; a++) {
            // var tempFolders = new foldersConstructor(demoFolderCount);
            filesCount = Math.floor(Math.random() * demoFileMaxCount);
            var tempFiles = new Array(filesCount);

            for (var j = 0; j < filesCount; j++) {
                tempFiles[j] = new fileConstructor(j);
                tempFiles[j].name = "File " + (j + 1);
            }
            arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[a].fileList = tempFiles;
            arrayAmplifier[soloAmplifierSelected].folderSpeaker.folderList[a].fileCount = filesCount;
        }
        $.fn.setDataSoloSpeaker(100);
    }
}

//SETUP THE GROUP ASSIGN AMP LIST 
$.fn.setupGroupAssign = function() {

    //GENERATE AMPLIFIER LIST
    var str = "";
    //HEADER OF THE ASSIGN GROUP TAB TABLE
    str += "<thead><tr><th>CHANNEL</th><th>G1</th><th>G2</th><th>G3</th><th>G4</th><th>G5</th><th>G6</th></tr></thead>";
    str += "<tbody>"

    var size = 1;
    //IF DEMO MODE ENABLE, CREATE AMPLIFIER
    switch (demoMode) {
        case 0:
            size = arrayAmplifier.length;
            break;
        case 1:
            size = arrayAmpSizeDemo;
            break;
    }

    for (var i = 0; i < size; i++) {
        str += "<tbody class=\"labels\">";
        str += "<tr>";
        str += "<td id=\"ampListIndex" + i + "\" colspan=\"7\">"
        if (i === 0)
            str += "<label id=\"assignGroupTabAmpName" + i + "\">" + arrayAmplifier[0].label + "</label>";
        else
            str += "<label id=\"assignGroupTabAmpName" + i + "\">" + discoveryList[i].desc + "</label>";
        str += "<button id=\"collapseAmpList" + i + "\" class=\"groupAssignAmpListSoloCollapse\"><div id=\"groupCollapseDiv" + i + "\" class=\"media\"><img id=\"groupCollapseImage" + i + "\" class=\"logoSetupSmallChevron\" src=\"./img/Up.png\"></button>";
        str += "</td>";
        str += "</tr>";
        str += "</tbody>";

        str += "<tbody class=\"hide\">";
        let amountOfChannel = channelCount;
        switch ($.fn.getModel(i)) {
            case 9:
                amountOfChannel = channel3Count;
                break;
            case 8:
                amountOfChannel = channel16Count;
                break;
            case 7:
                amountOfChannel = channel16Count;
                break;
            case 6:
                amountOfChannel = 1;
                break;
            case 5:
                amountOfChannel = 1;
                break;
            default:
                amountOfChannel = channelCount;
                break;
        }
        for (var j = 0; j < amountOfChannel; j++) {
            str += "<tr>";
            if (arrayAmplifier[i].channel[j].label) {
                if (arrayAmplifier[i].channel[j].label.length < 16)
                    str += "<td><span id=\"groupAssignLabelAmp" + i + "Channel" + j + "\" style=\"white-space: nowrap;\" class=\"channelGroupAssignTabField\" >" + arrayAmplifier[i].channel[j].label + "</label>";
                else
                    str += "<td><span id=\"groupAssignLabelAmp" + i + "Channel" + j + "\" class=\"channelGroupAssignTabField\" > Channel " + (j + 1) + "</label>";
            } else
                str += "<td><span id=\"groupAssignLabelAmp" + i + "Channel" + j + "\" class=\"channelGroupAssignTabField\" > Channel " + (j + 1) + "</label>";
            for (var k = 0; k < 6; k++) {
                if (arrayAmplifier[i].channel[j].group[k] === 1)
                    str += "<td><span id=\"groupAssignGroupAmp" + i + "Channel" + j + "Group" + k + "\" class=\"dotEnable\"></span></td>";
                else
                    str += "<td><span id=\"groupAssignGroupAmp" + i + "Channel" + j + "Group" + k + "\" class=\"dot\"></span></td>";
            }
            str += "</tr>";
        }
        str += "</tbody>";
    }
    str += "</tbody>"

    $("#assignGroupTabTable").html(str);

    //GENERATE AMPLIFIER SETUP TAB
    var str = "";
    //TITLE BAR
    str += "<div style=\"padding-top: 20px\"></div>";
    str += "<div class=\"container\">";
    str += "<div class=\"row no-gutters\">";
    str += "<div class=\"col-2\"></div>";
    str += "<div class=\"col-4\"><span id=\"groupAssignAmpSelectedName\"></span></div>";
    str += "<div class=\"col-4\"><span id=\"groupAssignAmpSelectedAddress\"></span></div>";
    str += "<div class=\"col-2\"></div>";
    str += "</div>";
    str += "</div>";
    str += "<div style=\"padding-top: 20px\"></div>";

    //MAIN CONTAINER
    str += "<div class=\"container\">";

    //GROUP LABEL BAR
    str += "<div class=\"row no-gutters\">";
    str += "<div class=\"col-2\">";
    str += "</div>";
    str += "<div class=\"col\"><span id=\"groupAssignAmpGroupLabel0\" class=\"full-text\"></span><span class=\"short-text\">G1</span></div>";
    str += "<div class=\"col\"><span id=\"groupAssignAmpGroupLabel1\" class=\"full-text\"></span><span class=\"short-text\">G2</span></div>";
    str += "<div class=\"col\"><span id=\"groupAssignAmpGroupLabel2\" class=\"full-text\"></span><span class=\"short-text\">G3</span></div>";
    str += "<div class=\"col\"><span id=\"groupAssignAmpGroupLabel3\" class=\"full-text\"></span><span class=\"short-text\">G4</span></div>";
    str += "<div class=\"col\"><span id=\"groupAssignAmpGroupLabel4\" class=\"full-text\"></span><span class=\"short-text\">G5</span></div>";
    str += "<div class=\"col\"><span id=\"groupAssignAmpGroupLabel5\" class=\"full-text\"></span><span class=\"short-text\">G6</span></div>";
    str += "</div>";

    let amountOfChannel = channelCount;
    switch ($.fn.getModel(0)) {
        case 9:
            amountOfChannel = channel3Count;
            break;
        case 8:
            amountOfChannel = channel16Count;
            break;
        case 7:
            amountOfChannel = channel16Count;
            break;
        case 6:
            amountOfChannel = channel1Count;
            break;
        case 5:
            amountOfChannel = channel1Count;
            break;
        default:
            amountOfChannel = channelCount;
            break;
    }

    str += "<div id=\"groupAssignAmplifierContentArea\">";

    // for (var i = 0; i < amountOfChannel; i++) {
    //     str += "<div class=\"row no-gutters\">";
    //     str += "<div class=\"col-2\"><span id=\"groupAssignAmpSelectedChannelLabel" + i + "\" class=\"full-text\"></span><span class=\"short-text\">CH" + i + "</span></div>";
    //     str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr0\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
    //     str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr1\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
    //     str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr2\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
    //     str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr3\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
    //     str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr4\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
    //     str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr5\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
    //     str += "</div>";
    // }

    str += "</div>";

    //MAIN CONTAINER END

    str += "</div>";
    $("#assignGroupTabContent").html(str);

    $.fn.setGroupAssignAmplifierContentArea(amountOfChannel);
}


$.fn.setGroupAssignAmplifierContentArea = function(num) {

    $("#groupAssignAmplifierContentArea").html("");
    var str = ""
    for (var i = 0; i < num; i++) {
        str += "<div class=\"row no-gutters\">";
        if (num == 3 && i > 0)
            str += "<div class=\"col-2\"><span id=\"groupAssignAmpSelectedChannelLabel" + i + "\" class=\"full-text\"></span><span class=\"short-text\">" + labelOverviewChannel3ch[i + 1] + "</span></div>";
        else
        //if CP703
        if (num == 3)
            str += "<div class=\"col-2\"><span id=\"groupAssignAmpSelectedChannelLabel" + i + "\" class=\"full-text\"></span><span class=\"short-text\">" + labelOverviewChannel3ch[i] + "</span></div>";
        else
            str += "<div class=\"col-2\"><span id=\"groupAssignAmpSelectedChannelLabel" + i + "\" class=\"full-text\"></span><span class=\"short-text\">CH" + (i + 1) + "</span></div>";
        str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr0\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
        str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr1\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
        str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr2\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
        str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr3\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
        str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr4\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
        str += "<div class=\"col\"><button id=\"GABtnCh" + i + "Gr5\" class=\"itemFullGroupAssignChannelBtn\"></button></div>";
        str += "</div>";
    }

    $("#groupAssignAmplifierContentArea").html(str);

}

//SETUP COPY CHANNEL PARAMETERS
$.fn.setupCopyChannelParam = function(type) {

    //COPY CHANNEL SOURCE CONTENT
    $("#copyChannelSourceContent").html("");

    if (type == 5 || type == 6) {
        $("#copyNotAvailable").html("Not available on plate amp");
        $("#copyNotAvailable").show();
        $(".copyTabContent").hide();
        return;
    }

    $("#copyNotAvailable").hide();
    $(".copyTabContent").show();
    $("#copyChannelSourceContent").append($("<table>").prop({ id: "CopyChannelSourceTable", className: "peqCopySource" }))

    if (type == 7 || type == 8) {
        for (var i = 0; i < channelCount; i++) {
            $("#CopyChannelSourceTable").append($("<tr>").prop({ id: "CopyChannelSourceTableRow" + i }));
            for (var j = 0; j < channelCount; j++) {
                var str = "";
                str += "<label for=\"inlineSourceRadio" + ((i * 4) + j) + "\" class=\"form-check-label peqCopyLabel\">&nbsp; Ch " + labelOverviewChannel[((i * 4) + j)] + " &nbsp</label>";
                str += "<input id=\"inlineSourceRadio" + ((i * 4) + j) + "\" class=\"copyChannelSourceRadio\" type=\"radio\" name=\"copyChannelOptions\">"
                $("#CopyChannelSourceTableRow" + i).append($("<td>").prop({ innerHTML: str }));
            }
        }
    } else if (type < 5) {
        $("#CopyChannelSourceTable").append($("<tr>").prop({ id: "CopyChannelSourceTableRow0" }));
        for (var j = 0; j < channelCount; j++) {
            var str = "";
            str += "<label for=\"inlineSourceRadio" + j + "\" class=\"form-check-label peqCopyLabel\">&nbsp; Ch " + labelOverviewChannel[j] + " &nbsp</label>";
            str += "<input id=\"inlineSourceRadio" + j + "\" class=\"copyChannelSourceRadio\" type=\"radio\" name=\"copyChannelOptions\">"
            $("#CopyChannelSourceTableRow0").append($("<td>").prop({ innerHTML: str }));
        }
    }

    //COPY CHANNEL CONTENT
    $("#copyChannelCopyContent").html("");

    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked0", className: "form-check" }))
    $("#copyChannelContentStacked0").append($("<input>").prop({ id: "copyChannelContentMixerCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked0").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentMixerCB", innerHTML: "Mixer" }))
    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked1", className: "form-check" }))
    $("#copyChannelContentStacked1").append($("<input>").prop({ id: "copyChannelContentGainCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked1").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentGainCB", innerHTML: "Gain" }))
    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked2", className: "form-check" }))
    $("#copyChannelContentStacked2").append($("<input>").prop({ id: "copyChannelContentDelayCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked2").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentDelayCB", innerHTML: "Delay" }))
    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked3", className: "form-check" }))
    $("#copyChannelContentStacked3").append($("<input>").prop({ id: "copyChannelContentPEQCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked3").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentPEQCB", innerHTML: "PEQ" }))
    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked4", className: "form-check" }))
    $("#copyChannelContentStacked4").append($("<input>").prop({ id: "copyChannelContentXOVERCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked4").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentXOVERCB", innerHTML: "XOVER" }))
    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked5", className: "form-check" }))
    $("#copyChannelContentStacked5").append($("<input>").prop({ id: "copyChannelContentLimiterCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked5").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentLimiterCB", innerHTML: "Limiter" }))
    $("#copyChannelCopyContent").append($("<div>").prop({ id: "copyChannelContentStacked6", className: "form-check" }))
    $("#copyChannelContentStacked6").append($("<input>").prop({ id: "copyChannelContentPresetCB", className: "form-check-input", type: "checkbox", value: "" }))
    $("#copyChannelContentStacked6").append($("<label>").prop({ className: "form-check-label", for: "copyChannelContentPresetCB", innerHTML: "Preset" }))

    //COPY DESTINATION

    $("#copyChannelDestContent").html("");

    $("#copyChannelDestContent").append($("<table>").prop({ id: "copyChannelDestTable", className: "peqCopySource" }))

    if (type == 7 || type == 8) {
        for (var i = 0; i < channelCount; i++) {
            $("#copyChannelDestTable").append($("<tr>").prop({ id: "copyChannelDestDestRow" + i }));
            for (var j = 0; j < channelCount; j++) {
                $("#copyChannelDestDestRow" + i).append($("<td>").prop({ type: "checkbox", innerHTML: "&nbsp Ch " + labelOverviewChannel[((i * 4) + j)] + " &nbsp<input id=\"copyChannelDest" + ((i * 4) + j) + "\" type=\"checkbox\" class=\"copyChannelDest\"/>" }));
            }
        }
    } else if (type < 5) {
        $("#copyChannelDestTable").append($("<tr>").prop({ id: "copyChannelDestRow0" }));
        for (var j = 0; j < channelCount; j++) {
            $("#copyChannelDestRow0").append($("<td>").prop({ type: "checkbox", innerHTML: "&nbsp Ch " + labelOverviewChannel[j] + " &nbsp<input id=\"copyChannelDest" + j + "\" type=\"checkbox\" class=\"copyChannelDest\"/>" }));
        }

    }

    if (type >= 0 && type < 5 || type == 7 || type == 8) {
        $("#copyChannelApply").html("");
        $("#copyChannelApply").append($("<button>").prop({ id: "copyChannelContentApply", className: "eqCopyApplyButton", innerHTML: "APPLY" }));
    }
}

/* Set the width of the side navigation to 250px */
function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    document.getElementById("main").style.marginRight = "250px";

    $(document).ready();
}

/* Set the width of the side navigation to 0 */
function closeNav() {
    $('.sidenav').toggleClass('active');
}

$.fn.draggieSetPosition = function(num) {
    // displayVal("num draggie set position", num);
    if (arrayEqParamDraggable[num])
        arrayEqParamDraggable[num].draggabilly('setPosition', xFromFreq(arrayEqParam[num].frequency) + widgetPEQMarginLeft, yFromGain(arrayEqParam[num].gain) + 6);
}

$.fn.draggieGroupSetPosition = function(num) {
    // displayVal("num draggie set position", num);
    arrayEqGroupParamDraggable[num].draggabilly('setPosition', xFromFreq(arrayEqGroupParam[num].frequency) + widgetPEQMarginLeft, yFromGain(arrayEqGroupParam[num].gain) + 6);
}

$.fn.draggieXOVERSetPosition = function(num) {
    switch (num) {
        case 0:
            if (highPassDrag)
                highPassDrag.draggabilly('setPosition', xFromFreqXOVER(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.hpFreq) + widgetXOVERMarginLeft, yFromGainXOVER(0) + 6);
            break;
        case 1:
            if (lowPassDrag)
                lowPassDrag.draggabilly('setPosition', xFromFreqXOVER(arrayAmplifier[soloAmplifierSelected].channel[soloChannelSelected].xover.lpFreq) + widgetXOVERMarginLeft, yFromGainXOVER(0) + 6);
            break;
        default:
            break;
    }
}


var bessel_coeff = [
    // order: 1
    [
        [-1, 0],
        [0, 0],
        [0, 0],
        [0, 0]
    ],

    // order: 2
    [
        [-1.101601327446325, 0.636009822940780],
        [0, 0],
        [0, 0],
        [0, 0]
    ],

    // order: 3
    [
        [-1.047409162950341, 0.999264438132800],
        [-1.322675802362066, 0],
        [0, 0],
        [0, 0]
    ],

    // order: 4
    [
        [-0.995208762612890, 1.257105737260073],
        [-1.370067828159648, 0.410249716777560],
        [0, 0],
        [0, 0]
    ],

    // order: 5
    [
        [-1.380877331649290, 0.717909590636350],
        [-0.957676552577410, 1.471124326897576],
        [-1.502316277745423, 0],
        [0, 0]
    ],

    // order: 6
    [
        [-1.571490416613821, 0.320896376876750],
        [-1.381858109025903, 0.971471898746610],
        [-0.930656530644320, 1.661863282687855],
        [0, 0]
    ],

    // order: 7
    [
        [-1.612038751019419, 0.589244501373040],
        [-1.378903203788025, 1.191566766560359],
        [-0.909867772040510, 1.836451335712793],
        [-1.684368163384248, 0]
    ],

    // order: 8
    [
        [-1.757408390223183, 0.272867573521960],
        [-1.636939408646247, 0.822795620374250],
        [-1.373841209680391, 1.388356567836560],
        [-0.892869713675890, 1.998325832067540]
    ]
];

$.fn.gainToPxl = function(gain) {
    return ((30 / 95) * parseInt(gain) + (80 / 95) * 30).toFixed(0);
};

//HIDE ALL MAIN PANELS
$.fn.hideMainPanels = function() {
    $(".containerGroup").hide();
    $("#sourceMainPanel").hide();
    $("#mixerMainPanel").hide();
    $("#gainMainPanel").hide();
    $("#delayMainPanel").hide();
    $("#peqMainPanel").hide();
    $("#xoverMainPanel").hide();
    $("#limiterMainPanel").hide();
    // $("#outputMainPanel").hide();
    $("#speakerMainPanel").hide();
    $(".containerCopy").hide();
};

//OPEN GROUP VIEW
$.fn.openGroupsView = function() {
    $(".containerSetup").hide();
    $(".containerOverview").hide();
    $(".containerMain").hide();
    $(".containerCopy").hide();
    $(".containerGroup").show();
};

//OPEN AMP VIEW
$.fn.openAmpView = function() {
    $(".containerSetup").hide();
    $(".containerGroup").hide();
    $(".containerCopy").hide();
    $(".containerOverview").show();
    $(".containerMain").show();
};

//OPEN SETUP VIEW
$.fn.openSetupView = function() {
    $(".containerOverview").hide();
    $(".containerMain").hide();
    $(".containerGroup").hide();
    $(".containerCopy").hide();
    $(".containerSetup").show();
}

//OPEN COPY VIEW
$.fn.openCopyView = function() {
    $(".containerOverview").hide();
    $(".containerMain").hide();
    $(".containerGroup").hide();
    $(".containerSetup").hide();
    $(".containerCopy").show();
}

//HIDE ALL GROUP PANELS
$.fn.hideGroupPanels = function() {
    $("#groupRegisterPanel").hide();
    $("#gainGroupPanel").hide();
    $("#delayGroupPanel").hide();
    $("#peqGroupPanel").hide();
    $("#groupEditPanel").hide();
};

//SHOW ALL GROUP PANELS
$.fn.showGroupPanels = function() {
    $("#groupRegisterPanel").show();
    $("#gainGroupPanel").show();
    $("#delayGroupPanel").show();
    $("#peqGroupPanel").show();
    $("#groupEditPanel").show();
};

//UPDATE CLOCK ON THE TOP TASKBAR
$.fn.updateClock = function() {
    var currentTime = new Date();
    var currentHours = currentTime.getHours();
    var currentMinutes = currentTime.getMinutes();
    var currentSeconds = currentTime.getSeconds();

    // Pad the minutes and seconds with leading zeros, if required
    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;

    // Choose either "AM" or "PM" as appropriate
    var timeOfDay = (currentHours < 12) ? "AM" : "PM";

    // Convert the hours component to 12-hour format if needed
    currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;

    // Convert an hours component of "0" to "12"
    currentHours = (currentHours == 0) ? 12 : currentHours;

    // Compose the string for display
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
    $("#localTimeValue").text(currentTimeString);

};

//RETURN X VALUE FROM FREQUENCY IN PEQ
function xFromFreq(frequency) {
    var x = 0;
    x = (Math.log10(frequency) - 1) * graphPEQWidth / scale;
    // displayValues("FREQ", frequency, "X", x);
    return x;
}

//RETURN FREQ VALUE FROM X IN PEQgraphPEQWidth
function freqFromX(x) {
    var f = 0;
    f = Math.pow(10, ((x * (scale / graphPEQWidth)) + 1));
    return f;
}

//RETURN Y VALUE FROM GAIN IN PEQ
function yFromGain(gain) {
    var y = 0;
    var gapGain = Math.max(...gain_scalePEQ[peqGainScaleType]) - Math.min(...gain_scalePEQ[peqGainScaleType]);
    y = -(graphPEQHeight / gapGain) * gain + graphPEQHeight * (Math.max(...gain_scalePEQ[peqGainScaleType]) / gapGain);
    return Math.round(y);
}

//RETURN Y VALUE FROM PHASE IN PEQ
function yFromPhase(phase) {
    var y = 0;
    if (peqViewMode == 2 && peqPhaseScaleType == 0)
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]) + 180;
    else if (peqViewMode == 2 && peqPhaseScaleType == 1)
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]) + 720;
    else
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);

    if (peqGainScaleType != 2) {
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);
    }
    // var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);
    y = -(graphPEQHeight / gapPhase) * phase + graphPEQHeight * (Math.max(...phase_scale[peqPhaseScaleType]) / gapPhase);
    return Math.round(y);
}

//RETURN GAIN VALUE FROM Y IN PEQ
function gainFromY(y) {
    var gain = 0;
    var gapGain = Math.max(...gain_scalePEQ[peqGainScaleType]) - Math.min(...gain_scalePEQ[peqGainScaleType]);
    gain = (y - graphPEQHeight * (Math.max(...gain_scalePEQ[peqGainScaleType]) / gapGain)) * -(gapGain / graphPEQHeight);
    return Math.round(gain * 100) / 100;
}

//RETURN PHASE VALUE FROM Y IN PEQ
function phaseFromY(y) {
    var gain = 0;
    if (peqViewMode == 2 && peqPhaseScaleType == 0)
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]) + 180;
    else if (peqViewMode == 2 && peqPhaseScaleType == 1)
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]) + 720;
    else
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);
    if (peqGainScaleType != 2) {
        var gapPhase = Math.max(...phase_scale[peqPhaseScaleType]) - Math.min(...phase_scale[peqPhaseScaleType]);
    }
    gain = (y - graphPEQHeight * (Math.max(...phase_scale[peqPhaseScaleType]) / gapPhase)) * -(gapPhase / graphPEQHeight);
    return Math.round(gain * 100) / 100;
}

// XOVER COORDINATE
//RETURN X VALUE FROM FREQUENCY IN XOVER
function xFromFreqXOVER(frequency) {
    var x = 0;
    x = (Math.log10(frequency) - 1) * graphXOVERWidth / scale;
    // displayValues("FREQ", frequency, "X", x);
    return x;
}

//RETURN FREQ VALUE FROM X IN graphXOVERWidth
function freqFromXXOVER(x) {
    var f = 0;
    f = Math.pow(10, ((x * (scale / graphXOVERWidth)) + 1));
    return f;
}

//RETURN Y VALUE FROM GAIN IN XOVER
function yFromGainXOVER(gain) {
    var y = 0;
    var gapGain = Math.max(...gain_scaleXOVER[xoverGainScaleType]) - Math.min(...gain_scaleXOVER[xoverGainScaleType]);
    y = -(graphXOVERHeight / gapGain) * gain + graphXOVERHeight * (Math.max(...gain_scaleXOVER[xoverGainScaleType]) / gapGain);
    return Math.round(y);
}

//RETURN Y VALUE FROM PHASE IN XOVER
function yFromPhaseXOVER(phase) {
    var y = 0;
    var gapPhase = Math.max(...phase_scale[xoverPhaseScaleType]) - Math.min(...phase_scale[xoverPhaseScaleType]);
    y = -(graphXOVERHeight / gapPhase) * phase + graphXOVERHeight * (Math.max(...phase_scale[xoverPhaseScaleType]) / gapPhase);
    return Math.round(y);
}

//RETURN GAIN VALUE FROM Y IN XOVER
function gainFromYXOVER(y) {
    var gain = 0;
    var gapGain = Math.max(...gain_scaleXOVER[xoverGainScaleType]) - Math.min(...gain_scaleXOVER[xoverGainScaleType]);
    gain = (y - graphXOVERHeight * (Math.max(...gain_scaleXOVER[xoverGainScaleType]) / gapGain)) * -(gapGain / graphXOVERHeight);
    return Math.round(gain * 100) / 100;
}

//RETURN PHASE VALUE FROM Y IN XOVER
function phaseFromYXOVER(y) {
    var gain = 0;
    var gapPhase = Math.max(...phase_scale[xoverPhaseScaleType]) - Math.min(...phase_scale[xoverPhaseScaleType]);
    gain = (y - graphXOVERHeight * (Math.max(...phase_scale[xoverPhaseScaleType]) / gapPhase)) * -(gapPhase / graphXOVERHeight);
    return Math.round(gain * 100) / 100;
}

//DISPLAY ONE VALUE IN CONSOLE (PARAM1, PARAM2) PARAM1 TEXT, PARAM2 VALUE
function displayVal(a, b) {
    var text = "VAR " + a + " : ";
    console.log(text + b);
}

//DISPLAY TWO VALUES IN CONSOLE (PARAM1, PARAM2, PARAM3, PARAM4) PARAM1 TEXT, PARAM2 VALUE, PARAM3 TEXT, PARAM4 VALUE
function displayValues(a, b, c, d) {
    var text = "VAR " + a + " : " + b + " \\ VAR " + c + " : " + d;
    console.log(text);
}

//CONVERT Q TO BW OCTAVE FOR PEQ
function BWfromQ(Q) {
    var bw = 0;
    var log2 = Math.log10(2);
    var q2 = Q * Q;
    bw = Math.log10((Math.sqrt(4 * q2 + 1) + 2 * q2 + 1) / (2 * q2)) / log2;
    return Math.round(bw * 1000) / 1000;
}

//CONVERT BW OCTAVE TO Q FOR PEQ
function QfromBW(bw_oct) {
    var q = 0;
    var bw = Math.pow(2, bw_oct);
    q = Math.sqrt(bw) / (bw - 1);
    return Math.round(q * 100) / 100;
}


//COMPUTE COMPLEX VALUE FOR SUM OF ZEROS AND SUM OF POLES IN PEQ COMPUTATION OPERATION
function evalCoefs(coefs, freq) {
    var len = coefs.length;
    var fx = freq / fS;
    // displayVal("length coef",len);
    var res = 0;
    for (var idx = 0; idx < len; idx++)
        res = math.add(res, math.multiply(coefs[idx], math.exp(math.complex(0, -idx * fx * 2 * math.pi))));
    return res
}

//COMPUTE PEQ COEFFICIENTS (A0, A1, A2, B0, B1, B2) AND SAVE IT
function computePEQCoeff(num) {
    switch (arrayEqParam[num].type) {
        case 0:
            BellSymCalcCoefficients(num);
            break;
        case 1:
            BellASymCalcCoefficients(num);
            break;
        case 2:
            NotchCalcCoefficients(num);
            break;
        case 3:
            LowShelf1CalcCoefficients(num);
            break;
        case 4:
            LowShelf2CalcCoefficients(num);
            break;
        case 5:
            HighShelf1CalcCoefficients(num);
            break;
        case 6:
            HighShelf2CalcCoefficients(num);
            break;
        case 7:
            AllPass1CalcCoefficients(num);
            break;
        case 8:
            AllPass2CalcCoefficients(num);
            break;
        case 9:
            Highpass1CalcCoefficients(num);
            break;
        case 10:
            Highpass2CalcCoefficients(num);
            break;
        case 11:
            Highpass2VariQCalcCoefficients(num);
            break;
        case 12:
            Lowpass1CalcCoefficients(num);
            break;
        case 13:
            Lowpass2CalcCoefficients(num);
            break;
        case 14:
            Lowpass2VariQCalcCoefficients(num);
            break;
        case 15:
            Bandpass2CalcCoefficients(num);
            break;
        default:
            displayVal("filter not found", num);
    }
}

// RETURN MAGNITUDE IN DB FOR A FREQUENCY f AND A PEQ NUMBER num
function getMagInDb(f, num) {
    // displayVal("Frequesncy asked", f);
    // displayVal("TYPE EQ",arrayEqParam[num].type);
    var invert = 0;
    switch (arrayEqParam[num].type) {
        case 0: //'Bell-Sym':
            break;
        case 1: //'Bell-ASym':
            invert = 1;
            break;
        case 2: //'Notch':
            invert = 1;
            break;
        case 3: //'Low-Shelving 6dB/oct':
            break;
        case 4: //'Low-Shelving 12dB/oct':
            break;
        case 5: //'High-Shelving 6dB/oct':
            break;
        case 6: //'High-Shelving 12dB/oct':
            break;
        case 7: //'All-Pass 90°':
            invert = 1;
            break;
        case 8: //'All-Pass 180°':
            invert = 1;
            break;
        case 9: //'High-Pass 6dB/oct':
            invert = 1;
            break;
        case 10: //'High-Pass 12dB/oct':
            invert = 1;
            break;
        case 11: //'High-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case 12: //'Low-Pass 6dB/oct':
            invert = 1;
            break;
        case 13: //'Low-Pass 12dB/oct':
            invert = 1;
            break;
        case 14: //'Low-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case 15: //'Band-Pass':
            invert = 1;
            break;
        default:
            displayVal("filter not found", arrayEqParam[num].type);
    }
    var aVect = [];
    aVect[0] = arrayEqParam[num].a.a0;
    aVect[1] = arrayEqParam[num].a.a1;
    aVect[2] = arrayEqParam[num].a.a2;
    var bVect = [];
    bVect[0] = arrayEqParam[num].b.b0;
    bVect[1] = arrayEqParam[num].b.b1;
    bVect[2] = arrayEqParam[num].b.b2;
    var resZeros = evalCoefs(aVect, f);
    var resPoles = evalCoefs(bVect, f);
    var res = math.divide(resZeros, resPoles);
    var tempMag = 0;
    tempMag = math.abs(res);
    tempMag = 20 * Math.log10(tempMag);
    if (invert)
        tempMag = -tempMag;
    return tempMag;
}

// RETURN PHASE IN DEGREE FOR A FREQUENCY f AND A PEQ NUMBER num
function getPhaInDg(f, num) {
    // displayVal("TYPE EQ",arrayEqParam[num].type);
    var invert = 0;
    switch (arrayEqParam[num].type) {
        case '0': //'Bell-Sym':
            break;
        case '1': //'Bell-ASym':
            invert = 1;
            break;
        case '2': //'Notch':
            invert = 1;
            break;
        case '3': //'Low-Shelving 6dB/oct':
            break;
        case '4': //'Low-Shelving 12dB/oct':
            break;
        case '5': //'High-Shelving 6dB/oct':
            break;
        case '6': //'High-Shelving 12dB/oct':
            break;
        case '7': //'All-Pass 90°':
            invert = 1;
            break;
        case '8': //'All-Pass 180°':
            invert = 1;
            break;
        case '9': //'High-Pass 6dB/oct':
            invert = 1;
            break;
        case '10': //'High-Pass 12dB/oct':
            invert = 1;
            break;
        case '11': //'High-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case '12': //'Low-Pass 6dB/oct':
            invert = 1;
            break;
        case '13': //'Low-Pass 12dB/oct':
            invert = 1;
            break;
        case '14': //'Low-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case '15': //'Band-Pass':
            invert = 1;
            break;
        default:
            console.log("filter not found");
    }
    var aVect = [];
    aVect[0] = arrayEqParam[num].a.a0;
    aVect[1] = arrayEqParam[num].a.a1;
    aVect[2] = arrayEqParam[num].a.a2;
    var bVect = [];
    bVect[0] = arrayEqParam[num].b.b0;
    bVect[1] = arrayEqParam[num].b.b1;
    bVect[2] = arrayEqParam[num].b.b2;
    var resZeros = evalCoefs(aVect, f);
    var resPoles = evalCoefs(bVect, f);
    var res = math.divide(resZeros, resPoles);
    var tempMag = 0;
    tempMag = math.arg(res);
    tempMag = tempMag * (180 / Math.PI);
    if (invert)
        tempMag = -tempMag;
    return tempMag;
}

$.fn.processPEQ = function(x, num) {

    var tempMag = 0;
    var tempPha = 0;
    var f = 0;
    f = freqFromX(x);
    var invert = 0;
    switch (arrayEqParam[num].type) {
        case 0: //'Bell-Sym':
            break;
        case 1: //'Bell-ASym':
            invert = 1;
            break;
        case 2: //'Notch':
            invert = 1;
            break;
        case 3: //'Low-Shelving 6dB/oct':
            break;
        case 4: //'Low-Shelving 12dB/oct':
            break;
        case 5: //'High-Shelving 6dB/oct':
            break;
        case 6: //'High-Shelving 12dB/oct':
            break;
        case 7: //'All-Pass 90°':
            invert = 1;
            break;
        case 8: //'All-Pass 180°':
            invert = 1;
            break;
        case 9: //'High-Pass 6dB/oct':
            invert = 1;
            break;
        case 10: //'High-Pass 12dB/oct':
            invert = 1;
            break;
        case 11: //'High-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case 12: //'Low-Pass 6dB/oct':
            invert = 1;
            break;
        case 13: //'Low-Pass 12dB/oct':
            invert = 1;
            break;
        case 14: //'Low-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case 15: //'Band-Pass':
            invert = 1;
            break;
        default:
            displayVal("filter not found", arrayEqParam[num].type);
    }
    var aVect = [];
    aVect[0] = arrayEqParam[num].a.a0;
    aVect[1] = arrayEqParam[num].a.a1;
    aVect[2] = arrayEqParam[num].a.a2;
    var bVect = [];
    bVect[0] = arrayEqParam[num].b.b0;
    bVect[1] = arrayEqParam[num].b.b1;
    bVect[2] = arrayEqParam[num].b.b2;
    var resZeros = evalCoefs(aVect, f);
    var resPoles = evalCoefs(bVect, f);
    var res = math.divide(resZeros, resPoles);
    tempMag = math.abs(res);
    tempMag = 20 * Math.log10(tempMag);
    if (invert)
        tempMag = -tempMag;

    tempPha = math.arg(res);
    tempPha = tempPha * (180 / Math.PI);
    if (invert)
        tempPha = -tempPha;

    return {
        magnitude: tempMag,
        phase: tempPha,
    };
}

// PROCESS PEQ PARAM GROUP
$.fn.processPEQGroup = function(x, num) {

    var tempMag = 0;
    var tempPha = 0;
    var f = 0;
    f = freqFromX(x);
    var invert = 0;
    switch (arrayEqGroupParam[num].type) {
        case 0: //'Bell-Sym':
            break;
        case 1: //'Bell-ASym':
            break;
        case 2: //'Notch':
            invert = 1;
            break;
        case 3: //'Low-Shelving 6dB/oct':
            break;
        case 4: //'Low-Shelving 12dB/oct':
            break;
        case 5: //'High-Shelving 6dB/oct':
            break;
        case 6: //'High-Shelving 12dB/oct':
            break;
        case 7: //'All-Pass 90°':
            invert = 1;
            break;
        case 8: //'All-Pass 180°':
            invert = 1;
            break;
        case 9: //'High-Pass 6dB/oct':
            invert = 1;
            break;
        case 10: //'High-Pass 12dB/oct':
            invert = 1;
            break;
        case 11: //'High-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case 12: //'Low-Pass 6dB/oct':
            invert = 1;
            break;
        case 13: //'Low-Pass 12dB/oct':
            invert = 1;
            break;
        case 14: //'Low-Pass VariQ 12dB/oct':
            invert = 1;
            break;
        case 15: //'Band-Pass':
            invert = 1;
            break;
        default:
            displayVal("filter not found", arrayEqGroupParam[num].type);
    }
    var aVect = [];
    aVect[0] = arrayEqGroupParam[num].a.a0;
    aVect[1] = arrayEqGroupParam[num].a.a1;
    aVect[2] = arrayEqGroupParam[num].a.a2;
    var bVect = [];
    bVect[0] = arrayEqGroupParam[num].b.b0;
    bVect[1] = arrayEqGroupParam[num].b.b1;
    bVect[2] = arrayEqGroupParam[num].b.b2;
    var resZeros = evalCoefs(aVect, f);
    var resPoles = evalCoefs(bVect, f);
    var res = math.divide(resZeros, resPoles);
    tempMag = math.abs(res);
    tempMag = 20 * Math.log10(tempMag);
    if (invert)
        tempMag = -tempMag;

    tempPha = math.arg(res);
    tempPha = tempPha * (180 / Math.PI);
    if (invert)
        tempPha = -tempPha;

    return {
        magnitude: tempMag,
        phase: tempPha,
    };
}

//HIDE ALL DIV IN PEQ PARAMETERS AREA
$.fn.clearPEQParamArea = function() {
    for (var i = 0; i < eqCount; i++) {
        var id = "#parametersAreaEQ" + i;
        $(id).hide();
    }
    $("#parametersAreaEQ99").hide();
    $("#parametersAreaEQ100").hide();
    $("#parametersAreaEQ200").hide();
}

//HIDE ALL DIV IN PEQ GROUP PARAMETERS AREA
$.fn.clearPEQGroupParamArea = function() {
    for (var i = 0; i < eqCount; i++) {
        var id = "#parametersAreaEQGroup" + i;
        $(id).hide();
    }
    $("#parametersAreaEQ99").hide();
    $("#parametersAreaEQ100").hide();
    // $("#parametersAreaEQGroup99").hide();
    // $("#parametersAreaEQGroup100").hide();
    $("#parametersAreaEQ200").show();
}

//PEQ COMPUTATION

//CONSTRUCTOR OF PARAMETRIC EQ
function EqParam(e, f, g, q, t, a, b, x, y) {
    this.ena = e;
    this.frequency = f;
    this.gain = g;
    this.q = q;
    this.bw = BWfromQ(q);
    this.type = t;
    this.a = a;
    this.b = b;
    this.xLock = x;
    this.yLock = y;
}

//CONSTRUCTOR OF PARAMETRIC EQ
function XoverParam(e, f, g, q, t, x, y) {
    this.ena = e;
    this.frequency = f;
    this.gain = g;
    this.q = q;
    this.bw = BWfromQ(q);
    this.type = t;
    //CROSSOVER CASCADE FILTER FROM 1th AND 2nd ORDER SO THEY HAVE MULTIPLE COEFFICIENTS A012 ET B012
    this.a = new Array();
    this.b = new Array();
    this.xLock = x;
    this.yLock = y;
}

//CONSTRUCTOR OF A PARAM FOR PEQ
function AParam() {
    this.a0 = 0;
    this.a1 = 0;
    this.a2 = 0;
}

//CONSTRUCTOR OF B PARAM FOR PEQ
function BParam() {
    this.b0 = 0;
    this.b1 = 0;
    this.b2 = 0;
}


// ----------------------------------------------------------------------------
// Filter #0: Bell Symmetric
function BellSymCalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var gainEq = -1 * arrayEqParam[eqNum].gain;
    var qEq = arrayEqParam[eqNum].q;
    //AMPLITUDE
    var A = Math.pow(10, gainEq / 20);
    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var sx = Math.sin(wx);
    var alpha = sx * sx / (wx * qEq);

    if (A >= 1) {
        var beta = A * alpha;
        var k = -2 * c0;

        arrayEqParam[eqNum].b.b0 = 1 + beta;
        arrayEqParam[eqNum].b.b1 = k;
        arrayEqParam[eqNum].b.b2 = 1 - beta;
        arrayEqParam[eqNum].a.a0 = 1 + alpha;
        arrayEqParam[eqNum].a.a1 = k;
        arrayEqParam[eqNum].a.a2 = 1 - alpha;
    } else {
        var beta = alpha / A;
        var k = -2 * c0;

        arrayEqParam[eqNum].b.b0 = 1 + alpha;
        arrayEqParam[eqNum].b.b1 = k;
        arrayEqParam[eqNum].b.b2 = 1 - alpha;
        arrayEqParam[eqNum].a.a0 = 1 + beta;
        arrayEqParam[eqNum].a.a1 = k;
        arrayEqParam[eqNum].a.a2 = 1 - beta;
    }
}

// ----------------------------------------------------------------------------
// Filter #1: Bell Asymmetric
function BellASymCalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var gainEq = arrayEqParam[eqNum].gain;
    var qEq = arrayEqParam[eqNum].q;
    //AMPLITUDE
    var A = Math.pow(10, gainEq / 20);
    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var sx = Math.sin(wx);
    var alpha = sx * sx / (wx * qEq);
    var k = -2 * c0;
    var g = A * alpha;

    arrayEqParam[eqNum].b.b0 = 1 + g;
    arrayEqParam[eqNum].b.b1 = k;
    arrayEqParam[eqNum].b.b2 = 1 - g;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = k;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// ----------------------------------------------------------------------------
// Filter #2: Notch
function NotchCalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var qEq = arrayEqParam[eqNum].q;

    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var sx = Math.sin(wx);
    var alpha = sx * sx / (wx * qEq);
    var k = -2 * c0;

    arrayEqParam[eqNum].b.b0 = 1;
    arrayEqParam[eqNum].b.b1 = k;
    arrayEqParam[eqNum].b.b2 = 1;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = k;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// ----------------------------------------------------------------------------
// Filter #3: Low-Shelving 6dB/oct
function LowShelf1CalcCoefficients(eqNum) {
    // Standard first order
    var freqEq = arrayEqParam[eqNum].frequency;
    var gainEq = -1 * arrayEqParam[eqNum].gain;

    var A = Math.pow(10, gainEq / 20);
    var wx = Math.PI * (freqEq / fS);
    var cx = Math.cos(wx);
    var sx = Math.sin(wx);

    if (A >= 1) {
        var g = A * sx;

        arrayEqParam[eqNum].b.b0 = g + cx;
        arrayEqParam[eqNum].b.b1 = g - cx;
        arrayEqParam[eqNum].a.a0 = sx + cx;
        arrayEqParam[eqNum].a.a1 = sx - cx;
    } else {
        A = 1 / A;

        arrayEqParam[eqNum].b.b0 = sx + cx;
        arrayEqParam[eqNum].b.b1 = sx - cx;
        arrayEqParam[eqNum].a.a0 = A * sx + cx;
        arrayEqParam[eqNum].a.a1 = A * sx - cx;
    }

    arrayEqParam[eqNum].a.a2 = 0;
    arrayEqParam[eqNum].b.b2 = 0;
}

// ----------------------------------------------------------------------------
// Filter #4  Low-Shelving 12dB/oct
function LowShelf2CalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var gainEq = -1 * arrayEqParam[eqNum].gain;

    var A = Math.pow(10, gainEq / 20);
    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    // Improved precision for the term 1-c0, necessary when
    // using float calculations instead of double.
    var sx = Math.sin(wx);
    var c1 = 2 * sx * sx;
    var alpha = c1 / (Math.sqrt(2) * wx);

    if (A >= 1) {
        var k = c1 * (A - 1) / 2 + 1;
        var g = Math.sqrt(A) * alpha;

        arrayEqParam[eqNum].b.b0 = k + g;
        arrayEqParam[eqNum].b.b1 = c1 * (A + 1) - 2;
        arrayEqParam[eqNum].b.b2 = k - g;
        arrayEqParam[eqNum].a.a0 = 1 + alpha;
        arrayEqParam[eqNum].a.a1 = -2 * c0;
        arrayEqParam[eqNum].a.a2 = 1 - alpha;
    } else {
        A = 1 / A;
        var k = c1 * (A - 1) / 2 + 1;
        var g = Math.sqrt(A) * alpha;

        arrayEqParam[eqNum].b.b0 = 1 + alpha;
        arrayEqParam[eqNum].b.b1 = -2 * c0;
        arrayEqParam[eqNum].b.b2 = 1 - alpha;
        arrayEqParam[eqNum].a.a0 = k + g;
        arrayEqParam[eqNum].a.a1 = c1 * (A + 1) - 2;
        arrayEqParam[eqNum].a.a2 = k - g;
    }
}

// ----------------------------------------------------------------------------
// Filter #5  High-Shelving 6dB/oct
function HighShelf1CalcCoefficients(eqNum) {
    // Standard first order
    var freqEq = arrayEqParam[eqNum].frequency;
    var gainEq = -1 * arrayEqParam[eqNum].gain;

    var A = Math.pow(10, gainEq / 20);
    var wx = Math.PI * (freqEq / fS);
    var cx = Math.cos(wx);
    var sx = Math.sin(wx);

    if (A >= 1) {
        arrayEqParam[eqNum].b.b0 = sx + A * cx;
        arrayEqParam[eqNum].b.b1 = sx - A * cx;
        arrayEqParam[eqNum].a.a0 = sx + cx;
        arrayEqParam[eqNum].a.a1 = sx - cx;
    } else {
        A = 1 / A;

        arrayEqParam[eqNum].b.b0 = sx + cx;
        arrayEqParam[eqNum].b.b1 = sx - cx;
        arrayEqParam[eqNum].a.a0 = sx + A * cx;
        arrayEqParam[eqNum].a.a1 = sx - A * cx;
    }

    arrayEqParam[eqNum].a.a2 = 0;
    arrayEqParam[eqNum].b.b2 = 0;
}

// ----------------------------------------------------------------------------
// Filter #6  High-Shelving 12dB/oct
function HighShelf2CalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var gainEq = -1 * arrayEqParam[eqNum].gain;

    var A = Math.pow(10, gainEq / 20);
    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var sx = Math.sin(wx);
    var alpha = 2 * sx * sx / (Math.sqrt(2) * wx);
    var cx = 1 + c0;

    if (A >= 1) {
        var k = cx * (A - 1) / 2 + 1;
        var g = Math.sqrt(A) * alpha;

        arrayEqParam[eqNum].b.b0 = k + g;
        arrayEqParam[eqNum].b.b1 = 2 - cx * (A + 1);
        arrayEqParam[eqNum].b.b2 = k - g;
        arrayEqParam[eqNum].a.a0 = 1 + alpha;
        arrayEqParam[eqNum].a.a1 = -2 * c0;
        arrayEqParam[eqNum].a.a2 = 1 - alpha;
    } else {
        A = 1 / A;
        var k = cx * (A - 1) / 2 + 1;
        var g = Math.sqrt(A) * alpha;

        arrayEqParam[eqNum].b.b0 = 1 + alpha;
        arrayEqParam[eqNum].b.b1 = -2 * c0;
        arrayEqParam[eqNum].b.b2 = 1 - alpha;
        arrayEqParam[eqNum].a.a0 = k + g;
        arrayEqParam[eqNum].a.a1 = 2 - cx * (A + 1);
        arrayEqParam[eqNum].a.a2 = k - g;
    }
}

// ----------------------------------------------------------------------------
// Filter #7  All-Pass 90°
function AllPass1CalcCoefficients(eqNum) {
    // Standard first order
    var freqEq = arrayEqParam[eqNum].frequency;

    var w0 = 2 * Math.PI * (freqEq / fS);
    var c0 = Math.cos(w0);
    var s0 = Math.sin(w0);
    var a = -c0 / (1 + s0);

    arrayEqParam[eqNum].b.b0 = a;
    arrayEqParam[eqNum].b.b1 = 1;
    arrayEqParam[eqNum].a.a0 = 1;
    arrayEqParam[eqNum].a.a1 = a;

    arrayEqParam[eqNum].a.a2 = 0;
    arrayEqParam[eqNum].b.b2 = 0;
}

// ----------------------------------------------------------------------------
// Filter #8  All-Pass 180°
function AllPass2CalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var qEq = arrayEqParam[eqNum].q;

    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var sx = Math.sin(wx);
    var alpha = sx * sx / (wx * qEq);

    arrayEqParam[eqNum].b.b0 = 1 - alpha;
    arrayEqParam[eqNum].b.b1 = -2 * c0;
    arrayEqParam[eqNum].b.b2 = 1 + alpha;
    arrayEqParam[eqNum].a.a0 = arrayEqParam[eqNum].b.b2;
    arrayEqParam[eqNum].a.a1 = arrayEqParam[eqNum].b.b1;
    arrayEqParam[eqNum].a.a2 = arrayEqParam[eqNum].b.b0;
}

// ----------------------------------------------------------------------------
// Filter #9  High-Pass 6dB/oct
function Highpass1CalcCoefficients(eqNum) {
    // Standard first order
    var freqEq = arrayEqParam[eqNum].frequency;

    var wx = Math.PI * (freqEq / fS);
    var cx = Math.cos(wx);
    var sx = Math.sin(wx);

    arrayEqParam[eqNum].b.b0 = cx;
    arrayEqParam[eqNum].b.b1 = -cx;
    arrayEqParam[eqNum].a.a0 = sx + cx;
    arrayEqParam[eqNum].a.a1 = sx - cx;

    arrayEqParam[eqNum].a.a2 = 0;
    arrayEqParam[eqNum].b.b2 = 0;
}

// ----------------------------------------------------------------------------
// Filter #10: High-Pass 12dB/oct
function Highpass2CalcCoefficients(eqNum) {
    var q = Math.sqrt(2);

    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;

    var w0 = 2 * Math.PI * (freqEq / fS);
    var c0 = Math.cos(w0);
    var alpha = Math.sin(w0) / q;
    var c1 = 1 + c0;

    arrayEqParam[eqNum].b.b0 = c1 / 2;
    arrayEqParam[eqNum].b.b1 = -c1;
    arrayEqParam[eqNum].b.b2 = c1 / 2;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = -2 * c0;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// ----------------------------------------------------------------------------
// Filter #11  High-Pass VariQ 12dB/oct
function Highpass2VariQCalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var qEq = arrayEqParam[eqNum].q;

    var w0 = 2 * Math.PI * (freqEq / fS);
    var c0 = Math.cos(w0);
    var alpha = Math.sin(w0) / (2 * qEq);
    var c1 = 1 + c0;

    arrayEqParam[eqNum].b.b0 = c1 / 2;
    arrayEqParam[eqNum].b.b1 = -c1;
    arrayEqParam[eqNum].b.b2 = c1 / 2;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = -2 * c0;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// ----------------------------------------------------------------------------
// Filter #12  Low-Pass 6dB/oct
function Lowpass1CalcCoefficients(eqNum) {
    // Standard first order
    var freqEq = arrayEqParam[eqNum].frequency;

    var wx = Math.PI * (freqEq / fS);
    var cx = Math.cos(wx);
    var sx = Math.sin(wx);

    arrayEqParam[eqNum].b.b0 = sx;
    arrayEqParam[eqNum].b.b1 = sx;
    arrayEqParam[eqNum].a.a0 = sx + cx;
    arrayEqParam[eqNum].a.a1 = sx - cx;

    arrayEqParam[eqNum].a.a2 = 0;
    arrayEqParam[eqNum].b.b2 = 0;
}

// ----------------------------------------------------------------------------
// Filter #13: Low-Pass 12dB/oct
function Lowpass2CalcCoefficients(eqNum) {
    var q = Math.sqrt(2);

    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;

    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var alpha = Math.sin(w0) / q;
    // Improved precision for the term 1-c0, necessary when
    // using float calculations instead of double.
    var sx = Math.sin(wx);
    var c1 = 2 * sx * sx;

    arrayEqParam[eqNum].b.b0 = c1 / 2;
    arrayEqParam[eqNum].b.b1 = c1;
    arrayEqParam[eqNum].b.b2 = c1 / 2;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = -2 * c0;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// ----------------------------------------------------------------------------
// Filter #14  Low-Pass VariQ 12dB/oct
function Lowpass2VariQCalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var qEq = arrayEqParam[eqNum].q;

    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var alpha = Math.sin(w0) / (2 * qEq);
    // Improved precision for the term 1-c0, necessary when
    // using float calculations instead of double.
    var sx = Math.sin(wx);
    var c1 = 2 * sx * sx;

    arrayEqParam[eqNum].b.b0 = c1 / 2;
    arrayEqParam[eqNum].b.b1 = c1;
    arrayEqParam[eqNum].b.b2 = c1 / 2;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = -2 * c0;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// ----------------------------------------------------------------------------
// Filter #15: Band-Pass 6dB/oct
function Bandpass2CalcCoefficients(eqNum) {
    // Standard biquad, both numerator and denominator 2nd order
    var freqEq = arrayEqParam[eqNum].frequency;
    var qEq = arrayEqParam[eqNum].q;

    var wx = Math.PI * (freqEq / fS);
    var w0 = 2 * wx;
    var c0 = Math.cos(w0);
    var sx = Math.sin(wx);
    var alpha = sx * sx / (wx * qEq);

    arrayEqParam[eqNum].b.b0 = alpha;
    arrayEqParam[eqNum].b.b1 = 0;
    arrayEqParam[eqNum].b.b2 = -alpha;
    arrayEqParam[eqNum].a.a0 = 1 + alpha;
    arrayEqParam[eqNum].a.a1 = -2 * c0;
    arrayEqParam[eqNum].a.a2 = 1 - alpha;
}

// =============================================================================
// XOVER Filter #0-11: Butterworth 6dB/oct to Linkwitz-Riley 48dB/oct
// Compute a butterworth filter up to 8th order and put the coefficients
// in the supplied array. The coefficient array must be at least length 4.
function ButterworthLinkwitzRileyCalcCoefficients(type, indice) {
    var order = 0;
    var linkwitz = 0;
    if (indice > 7)
        linkwitz = 1

    switch (parseInt(indice)) {
        case 0:
            order = 1;
            break;
        case 1:
            order = 2;
            break;
        case 2:
            order = 3;
            break;
        case 3:
            order = 4;
            break;
        case 4:
            order = 5;
            break;
        case 5:
            order = 6;
            break;
        case 6:
            order = 7;
            break;
        case 7:
            order = 8;
            break;
        case 8:
            order = 2;
            break;
        case 9:
            order = 4;
            break;
        case 10:
            order = 6;
            break;
        case 11:
            order = 8;
            break;
        default:
            break;
    }

    // Remove all filters
    if (type == 0) {
        highPassEqParam.a.length = 0;
        highPassEqParam.b.length = 0;
        var wx = Math.PI * (highPassEqParam.frequency / fS);
        var sx = Math.sin(wx);
        var w0 = 2 * wx;
        var s0 = Math.sin(w0);
        var c0 = Math.cos(w0);
        var sx2 = sx * sx;
    } else {
        lowPassEqParam.a.length = 0;
        lowPassEqParam.b.length = 0;
        var wx = Math.PI * (lowPassEqParam.frequency / fS);
        var sx = Math.sin(wx);
        var w0 = 2 * wx;
        var s0 = Math.sin(w0);
        var c0 = Math.cos(w0);
        var sx2 = sx * sx;
    }

    var n = order;

    if (linkwitz == 1)
        n = n / 2; // Constructed from 2 half-order Butterworths

    var nk = n / 2; // number of biquad sections
    for (var k = 1; k <= nk; k++) {
        var a = new AParam();
        var b = new BParam();
        b.b0 = 1.0;
        a.a0 = 1.0;

        var alpha = s0 * Math.cos(Math.PI * (n - 2 * k + 1) / (2 * n));
        var a0 = 1 + alpha;
        var A;

        if (type == 0) {
            A = (1 + c0) / a0;

            b.b1 = -A;
            A /= 2;
        } else {
            A = sx2 / a0;
            b.b1 = 2 * A;
        }

        b.b0 = A;
        b.b2 = A;
        a.a1 = -2 * c0 / a0;
        a.a2 = (1 - alpha) / a0;

        if (type == 0) {
            highPassEqParam.a.push(a);
            highPassEqParam.b.push(b);
            if (linkwitz) {
                highPassEqParam.a.push(a);
                highPassEqParam.b.push(b);
            }
        } else {

            lowPassEqParam.a.push(a);
            lowPassEqParam.b.push(b);
            if (linkwitz) {
                lowPassEqParam.a.push(a);
                lowPassEqParam.b.push(b);
            }
        }
    }

    // Add the necessary sections to complete odd order filters
    if (n % 2 != 0) {
        // displayVal("n value for n%2 !=0", n);
        if (linkwitz == 1) {
            // displayVal("linkwitz test ok", linkwitz);
            if (type == 0) {
                //HIGHPASS2VARIQ : _filters.push_back(new FilterHighpass2VariQ(_f, 0, 0.5));
                let freqEq = highPassEqParam.frequency;
                let qEq = 0.5;

                let w0 = 2 * Math.PI * (freqEq / fS);
                let c0 = Math.cos(w0);
                let alpha = Math.sin(w0) / (2 * qEq);
                let c1 = 1 + c0;

                let a = new AParam();
                let b = new BParam();

                b.b0 = c1 / 2;
                b.b1 = -c1;
                b.b2 = c1 / 2;
                a.a0 = 1 + alpha;
                a.a1 = -2 * c0;
                a.a2 = 1 - alpha;

                highPassEqParam.a.push(a);
                highPassEqParam.b.push(b);
            } else {
                //LOWPASS2VARIQ : _filters.push_back(new FilterLowpass2VariQ(_f, 0, 0.5));
                let freqEq = lowPassEqParam.frequency;
                let qEq = 0.5;

                let wx = Math.PI * (freqEq / fS);
                let w0 = 2 * wx;
                let c0 = Math.cos(w0);
                let alpha = Math.sin(w0) / (2 * qEq);
                // Improved precision for the term 1-c0, necessary when
                // using float calculations instead of double.
                let sx = Math.sin(wx);
                let c1 = 2 * sx * sx;

                let a = new AParam();
                let b = new BParam();

                b.b0 = c1 / 2;
                b.b1 = c1;
                b.b2 = c1 / 2;
                a.a0 = 1 + alpha;
                a.a1 = -2 * c0;
                a.a2 = 1 - alpha;

                lowPassEqParam.a.push(a);
                lowPassEqParam.b.push(b);
            }
        } else {
            if (type == 0) {
                //FILTERHIGHPASS1 : _filters.push_back(new FilterHighpass1(_f, 0, 0));
                let freqEq = highPassEqParam.frequency;

                let wx = Math.PI * (freqEq / fS);
                let cx = Math.cos(wx);
                let sx = Math.sin(wx);

                let a = new AParam();
                let b = new BParam();

                b.b0 = cx;
                b.b1 = -cx;
                a.a0 = sx + cx;
                a.a1 = sx - cx;
                a.a2 = 0;
                b.b2 = 0;

                highPassEqParam.a.push(a);
                highPassEqParam.b.push(b);
            } else {
                //FILTERLOWPASS1 : _filters.push_back(new FilterLowpass1(_f, 0, 0));
                // Standard first order
                let freqEq = lowPassEqParam.frequency;

                let wx = Math.PI * (freqEq / fS);
                let cx = Math.cos(wx);
                let sx = Math.sin(wx);

                let a = new AParam();
                let b = new BParam();

                b.b0 = sx;
                b.b1 = sx;
                a.a0 = sx + cx;
                a.a1 = sx - cx;
                a.a2 = 0;
                b.b2 = 0;

                lowPassEqParam.a.push(a);
                lowPassEqParam.b.push(b);
            }
        }
    }
}

// ----------------------------------------------------------------------------
// XOVER Filter #12-18: Bessel 12dB/oct to Bessel 48dB/oct
// type = 0 => HIGHPASS type = 1 => LOWPASS
function BesselCalcCoefficients(type, indice) {

    var n = indice - 1;
    var wx = 0;
    var w0 = 0;

    // Remove all filters
    if (type == 0) {
        highPassEqParam.a.length = 0;
        highPassEqParam.b.length = 0;
        wx = Math.PI * (highPassEqParam.frequency / fS);
        w0 = 2 * wx;
    } else {
        lowPassEqParam.a.length = 0;
        lowPassEqParam.b.length = 0;
        wx = Math.PI * (lowPassEqParam.frequency / fS);
        w0 = 2 * wx;
    }

    for (var i = 0; i < 4; ++i) {
        var a = bessel_coeff[n][i][0];
        // displayVal("bessel A coef", bessel_coeff[n][i][0]);
        var b = bessel_coeff[n][i][1];
        // displayVal("bessel B coef", bessel_coeff[n][i][1]);

        var coeff_a = new AParam();
        var coeff_b = new BParam();
        coeff_b.b0 = 1.0;
        coeff_a.a0 = 1.0;

        //HIGHPASS FILTER TEST
        if (type == 0) {
            if (a != 0) {
                if (b == 0) {
                    // First order section
                    let sx = Math.sin(wx);
                    let cx = Math.cos(wx);
                    let ax = -a * cx;
                    let a0 = ax + sx;

                    coeff_b.b0 = ax / a0;
                    coeff_b.b1 = -coeff_b.b0;
                    coeff_a.a1 = (sx - ax) / a0;
                } else {
                    // Second order section
                    let p = a * a + b * b;
                    let c0 = Math.cos(w0);
                    let s0 = Math.sin(w0);
                    let cx = 1 + c0;
                    let a0 = cx * (p - 1) + 2 * (1 - a * s0);

                    coeff_b.b0 = p * cx / a0;
                    coeff_b.b1 = -2 * coeff_b.b0;
                    coeff_b.b2 = coeff_b.b0;
                    coeff_a.a1 = 2 * (2 - cx * (p + 1)) / a0;
                    coeff_a.a2 = (cx * (p - 1) + 2 * (1 + a * s0)) / a0;
                }
                highPassEqParam.a.push(coeff_a);
                highPassEqParam.b.push(coeff_b);
            }
        } else {
            if (a != 0) {
                if (b == 0) {
                    // First order section
                    let sx = Math.sin(wx);
                    let cx = Math.cos(wx);
                    let ax = -a * sx;
                    let a0 = ax + cx;

                    coeff_b.b0 = ax / a0;
                    coeff_b.b1 = coeff_b.b0;
                    coeff_a.a1 = (ax - cx) / a0;
                } else {
                    // Second order section
                    let p = a * a + b * b;
                    let sx = Math.sin(wx);
                    let c0 = 2 * sx * sx; // = 1-cos(w0)
                    let s0 = Math.sin(w0);
                    let a0 = c0 * (p - 1) + 2 * (1 - a * s0);

                    coeff_b.b0 = p * c0 / a0;
                    coeff_b.b1 = 2 * coeff_b.b0;
                    coeff_b.b2 = coeff_b.b0;
                    coeff_a.a1 = 2 * (c0 * (p + 1) - 2) / a0;
                    coeff_a.a2 = (c0 * (p - 1) + 2 * (1 + a * s0)) / a0;
                }
                lowPassEqParam.a.push(coeff_a);
                lowPassEqParam.b.push(coeff_b);
            }
        }
    }
}
//COMPUTE XOVER A AND B ARRAYS OF COEFFICIENT
function computeXOVERCoeff(type, indice) {
    if (indice < 12)
        ButterworthLinkwitzRileyCalcCoefficients(type, indice);
    else
        BesselCalcCoefficients(type, indice - 10);
}

//PROCESS XOVER VALUE FOR MAG AND PHA WITH FREQ freq (0 TO 22000) AND TYPE type ( 0 = HP & 1 = LP )
$.fn.processXover = function(x, type) {
    var tempMag = 0;
    var tempPha = 0;

    var lgt = (type == 0) ? highPassEqParam.a.length : lowPassEqParam.a.length;

    for (var i = 0; i < lgt; i++) {
        if (type == 0) {
            var aVect = [];
            aVect[0] = highPassEqParam.a[i].a0;
            aVect[1] = highPassEqParam.a[i].a1;
            aVect[2] = highPassEqParam.a[i].a2;
            var bVect = [];
            bVect[0] = highPassEqParam.b[i].b0;
            bVect[1] = highPassEqParam.b[i].b1;
            bVect[2] = highPassEqParam.b[i].b2;
        } else {
            var aVect = [];
            aVect[0] = lowPassEqParam.a[i].a0;
            aVect[1] = lowPassEqParam.a[i].a1;
            aVect[2] = lowPassEqParam.a[i].a2;
            var bVect = [];
            bVect[0] = lowPassEqParam.b[i].b0;
            bVect[1] = lowPassEqParam.b[i].b1;
            bVect[2] = lowPassEqParam.b[i].b2;
        }
        var f = freqFromXXOVER(x);
        var resZeros = evalCoefs(aVect, f);
        var resPoles = evalCoefs(bVect, f);
        var res = math.divide(resZeros, resPoles);
        tempMag = tempMag + (20 * Math.log10(math.abs(res)));
        tempPha = tempPha + (math.arg(res) * (180 / Math.PI));
    }
    tempMag = -tempMag;
    tempPha = -tempPha;
    return {
        magnitude: tempMag,
        phase: tempPha,
    };
}

//CONSTRUCTOR OF AMPLIFIER
function amplifierConstructor() {
    this.channel = new Array(channel16Count);
    for (var i = 0; i < channel16Count; i++) {
        this.channel[i] = new channelConstructor();
    }
    this.oem = false;
    this.local = 0;
    this.label = "";
    this.model = "";
    this.network = new networkConstructor();
    this.discovery = new discoveryConstructor();
    this.folderSpeaker = new foldersConstructor(defaultFolderCount);
    this.folderGlobal = new foldersConstructor(defaultFolderCount);
    this.cloud = new cloudConstructor();
    this.streaming = new streamingConstructor();
    this.desc = "";
    this.stereo = new stereoConstructor();
    this.bridge = new bridgeConstructor();
    this.hardwareVersion = "";
    this.serial = "";
    this.signalGenerator = new signalGeneratorConstructor();
    this.hiZ = new Array(channel16Count);
    for (var i = 0; i < channel16Count; i++) {
        this.hiZ[i] = false;
    }
    this.amp_stage_disabled = false;
    this.frontPanelLocked = false;
}

//CONSTRUCTOR OF SIGNAL GENERATOR
function signalGeneratorConstructor() {
    var freq_gen = new Object();
    freq_gen.frequency = 1000;
    freq_gen.gain = -60.0;
    var pink_gen = new Object();
    pink_gen.gain = -60.0;
    this.frequencyGenerator = freq_gen;
    this.pinkNoise = pink_gen;
}

//CONSTRUCTOR OF MIXER
function mixerConstructor() {
    var gainArr = new Array(maxMixerInput);
    for (var i = 0; i < maxMixerInput; i++) {
        gainArr[i] = -10.0;
    }
    this.gain = gainArr;
}

//CONSTRUCTOR OF BRIDGE
function bridgeConstructor() {
    this.bridge12 = false;
    this.bridge34 = false;
    this.bridge56 = false;
    this.bridge78 = false;
    this.bridge910 = false;
    this.bridge1112 = false;
    this.bridge1314 = false;
    this.bridge1516 = false;
}

//CONSTRUCTOR OF STEREO
function stereoConstructor() {
    this.stereo12 = false;
    this.stereo34 = false;
}

//CONSTRUCTOR OF CLOUD
function cloudConstructor() {
    this.enable = false;
    this.device_name = "";
    this.username = "";
    this.password = "";
}

//CONSTRUCTOR OF STREAMING
function streamingConstructor() {
    this.spotify = new spotifyConstructor();
    this.airplay = new airplayConstructor();
}

//CONSTRUCTOR OF SPOTIFY
function spotifyConstructor() {
    this.device_name = "";
    this.email = "";
    this.password = "";
    this.enable = false;
}

//CONSTRUCTOR OF AIRPLAY
function airplayConstructor() {
    this.device_name = "";
    this.password = "";
    this.enable = false;
}

//CONSTRUCTOR OF NETWORK
function networkConstructor() {
    this.lan = new lanConstructor();
    this.wlan = new wlanConstructor();
}

//CONSTRUCTON OF LAN
function lanConstructor() {
    this.ip = "";
    this.mask = "";
    this.gw = "";
    this.dhcp = false;
}

//CONSTRUCTOR OF WLAN
function wlanConstructor() {
    this.ssid = "CP_WIFI";
    this.password = "cloudpower";
    this.wpa_version = 2;
    this.channel = 6;
    this.enable = false;
}

//CONSTRUCTOR OF DISCOVERY
function discoveryConstructor() {
    this.hw_addr = "null";
    this.ip_addr = "null";
    this.desc = "null";
    this.alive = "null";
    this.last_report_time = 0;
    this.model = "null";
    this.cloud_device_name = "null";
}

// CONSTRUCTOR OF CHANNEL
function channelConstructor() {
    this.source = new sourceConstructor();
    this.gain = new gainConstructor();
    this.delay = new delayConstructor();
    this.peq = new peqConstructor(eqCount);
    this.xover = new xoverConstructor();
    this.limiter = new limiterConstructor();
    this.mixer = new mixerConstructor();
    //CHANNEL BELONGS TO GROUP : 0 NOT IN THE GROUP, 1 IN THE GROUP

    this.group = new Array(6);

    for (var i = 0; i < 6; i++) {
        this.group[i] = 0;
    }
    this.label = "";
    this.preset = "";
}

//CONSTRUCTOR OF SOURCE
function sourceConstructor() {
    //SOURCE MAPPING : AN1 = 0 / AN2 = 1 / AN3 = 2 / AN4 = 3 / DA1 = 4 / DA2 = 5 / DA3 = 6 / DA4 = 7
    this.primary = parseInt(4);
    this.secondary = parseInt(0);
}

//CONSTRUCTOR OF GAIN
function gainConstructor() {
    this.gain = 0.0;
    this.muteEna = false;
    this.polarityEna = false;
}

//CONSTRUCTOR OF DELAY
function delayConstructor() {
    this.delay = 0.0;
    this.delayEna = false;
}

//CONSTRUCTOR OF PEQS 
function peqConstructor(peqCount) {
    this.peq = new Array(peqCount);
    for (var i = 0; i < peqCount; i++) {
        this.peq[i] = new EqParam(eqEnaDefault, eqFreqDefaultInit[i], eqGainDefault, eqQDefault, eqTypeDefault, new AParam(), new BParam(), eqXLockDefault, eqYLockDefault);
    }
}

//CONSTRUCTOR OF XOVER
function xoverConstructor() {
    this.hpEna = false;
    this.lpEna = false;
    this.lpFreq = lowPassDefaultFrequency;
    this.lpType = lowPassDefaultType;
    this.hpFreq = highPassDefaultFrequency;
    this.hpType = highPassDefaultType;
    this.a = new AParam();
    this.b = new BParam()
    this.hpSpeakerPresetOveride = false;
    this.hpSpeakerPresetFreq = 0;
    this.hpSpeakerPresetFreqLimit = 0;
    this.lpSpeakerPresetOveride = false;
    this.lpSpeakerPresetFreq = 0;
    this.lpSpeakerPresetFreqLimit = 0;
}

//CONSTRUCTOR OF LIMITER
function limiterConstructor() {
    this.rmsThres = limiterRmsThresDefault;
    this.rmsAttack = limiterRmsAttackDefault;
    this.rmsRelease = limiterRmsReleaseDefault;

    this.peakThres = limiterPeakThresDefault;
    this.peakRelease = limiterPeakReleaseDefault;
}

//OVERIDE TOSTRING FUNCTION TO DISPLAY CHANNELCONSTRUCTOR
channelConstructor.prototype.toString = function() {
    return "" + this.source.primary + this.source.secondary + this.gain.gain + this.delay.delay + this.peq.peq[0].frequency + this.xover.lpFreq + this.limiter.rmsThres;
}

// //CONSTRUCTOR OF GROUP
function groupConstructor() {
    this.gain = new gainConstructor()
    this.delay = new delayConstructor();
    this.peq = new Array(peqCount);
    for (var i = 0; i < peqCount; i++) {
        this.peq[i] = new EqParam(eqEnaDefault, eqFreqDefaultInit[i], eqGainDefault, eqQDefault, eqTypeDefault, new AParam(), new BParam(), eqXLockDefault, eqYLockDefault);
    }
    this.enable = true;
    this.label = "GRP_" + makeid(5);
}

function makeid(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

function makeidCapital(length) {
    var result = '';
    var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var charactersLength = characters.length;
    for (var i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

function makeip() {
    var result = "" + (Math.floor(Math.random() * 255));
    return result;
}

//CONSTRUCTOR OF FOLDERS
function foldersConstructor(count) {
    this.folderList = new Array(count);
    this.folderCount = count;
    for (var i = 0; i < count; i++) {
        this.folderList[i] = new folderConstructor(i, defaultFileCount);
    }
}

function folderConstructor(arg, count) {
    this.name = "" + defaultFolderName + arg;
    this.fileCount = count;
    this.fileList = new Array(count);
    for (var i = 0; i < count; i++) {
        this.fileList[i] = new fileConstructor(i);
    }
}

function fileConstructor(arg) {
    this.name = "" + defaultFileName + arg;
    this.version = "" + defaultVersionName;
    this.desc = "" + defaultDesc;
}

//CONSTRUCTOR OF DISCOVERED AMPLIFIER
function discoveredAmpConstructor(arg) {
    this.hw_addr = arg.hw_addr;
    this.ip_addr = arg.ip_addr;
    this.desc = arg.desc;
    this.alive = arg.alive;
    this.last_report_time = arg.last_report_time;
    this.model = arg.model;
    this.cloud_device_name = arg.cloud_device_name;
}

//CONSTRUCTOR OF DISCOVERED AMPLIFIER
function discoveredAmpDemoConstructor() {
    this.hw_addr = "AA:BB:CC:DD:EE:" + makeidCapital(2);
    this.ip_addr = "192.168.0." + makeip();
    this.desc = "";
    this.alive = true;
    this.last_report_time = 123456789;
    this.model = "";
    this.model = "";
}