var client = null;
document.addEventListener("DOMContentLoaded", function(event) {
	client = new TVox.Client({
		url: '172.16.93.195' //please, insert here your domain
	});
	
	globalUsername= null;
	
	toggleForm(client.state == 'LOGIN_REQUIRED');
	
	subscribeToLoginStateEvents();
	subscribeToCallsEvents();
	eventListenersUI();
	eventListenersCallButtonsUI();
	call1 = null;
	call2 = null;
	channel1= null;
	channel2= null;
	document.getElementById('container_call_2').style.display ='none';
	document.getElementById('container_call_1').style.display ='none';
	document.getElementById('deviceSelectionSection').style.display = 'none';
	document.getElementById('phoneManagedByTVoxClient').checked = client.phone.managedByTVoxClient;
});

function showHideLoginType(type) {
	document.getElementById('classicLogin').style.display=type=='classic' ? 'block':'none';
	document.getElementById('externalLogin').style.display=type=='external' ? 'block':'none';
	
}

function eventListenersCallButtonsUI(){
	document.getElementById('phoneManagedByTVoxClient').addEventListener('change', ()=>{
		client.phone.managedByTVoxClient = document.getElementById('phoneManagedByTVoxClient').checked;
	}, false);
	
	// ------------------------------- ACTION PER CALL ---------------------------
	document.getElementById('answerButton1').addEventListener('click', ()=>{
		console.log('answer clicked for call 1');
			answerCall('1');
	});
	document.getElementById('answerButton2').addEventListener('click', ()=>{
		console.log('answer clicked for call 2');
			answerCall('2');
		});
	document.getElementById('dropButton1').addEventListener('click', ()=>{
		console.log('drop clicked for call 1');
			dropCall('1');
	});
	document.getElementById('dropButton2').addEventListener('click', ()=>{
		console.log('drop clicked for call 2');
			dropCall('2');
		});
	document.getElementById('holdButton1').addEventListener('click', ()=>{
		console.log('hold clicked for call 1');
			toggleHold('1', true);
	});
	document.getElementById('holdButton2').addEventListener('click', ()=>{
		console.log('hold clicked for call 2');
			toggleHold('2', true);
		});
	document.getElementById('unholdButton1').addEventListener('click', ()=>{
		console.log('unhold clicked for call 1');
			toggleHold('1',false);
	});
	document.getElementById('unholdButton2').addEventListener('click', ()=>{
		console.log('unhold clicked for call 2');
			toggleHold('2', false);
		});

	document.getElementById('transferButton1').addEventListener('click', ()=>{
		console.log('transfer clicked for call 1');
			transfCall('1');
	});
	document.getElementById('transferButton2').addEventListener('click', ()=>{
		console.log('tranfer clicked for call 2');
			transfCall('2');
	});
	
	// ------------------------------- DTMF PER CALL 1 ---------------------------
	
	document.getElementById('dtmf1_1').addEventListener('click', ()=>{
		console.log('dtmf 1 clicked for call 1');
			sendDTMF('1','1');
	});
	document.getElementById('dtmf2_1').addEventListener('click', ()=>{
		console.log('dtmf 2 clicked for call 1');
			sendDTMF('1','2');
	});
	document.getElementById('dtmf3_1').addEventListener('click', ()=>{
		console.log('dtmf 3 clicked for call 1');
			sendDTMF('1','3');
	});
	document.getElementById('dtmf4_1').addEventListener('click', ()=>{
		console.log('dtmf 4 clicked for call 1');
			sendDTMF('1','4');
	});
	document.getElementById('dtmf5_1').addEventListener('click', ()=>{
		console.log('dtmf 5 clicked for call 1');
			sendDTMF('1','5');
	});
	document.getElementById('dtmf6_1').addEventListener('click', ()=>{
		console.log('dtmf 6 clicked for call 1');
			sendDTMF('1','6');
	});
	document.getElementById('dtmf7_1').addEventListener('click', ()=>{
		console.log('dtmf 7 clicked for call 1');
			sendDTMF('1','7');
	});
	document.getElementById('dtmf8_1').addEventListener('click', ()=>{
		console.log('dtmf 8 clicked for call 1');
			sendDTMF('1','8');
	});
	document.getElementById('dtmf9_1').addEventListener('click', ()=>{
		console.log('dtmf 9 clicked for call 1');
			sendDTMF('1','9');
	});
	document.getElementById('dtmf0_1').addEventListener('click', ()=>{
		console.log('dtmf 0 clicked for call 1');
			sendDTMF('1','0');
	});
	document.getElementById('dtmf*_1').addEventListener('click', ()=>{
		console.log('dtmf * clicked for call 1');
			sendDTMF('1','*');
	});
	document.getElementById('dtmf#_1').addEventListener('click', ()=>{
		console.log('dtmf # clicked for call 1');
			sendDTMF('1','#');
	});
	
		
	// ------------------------------- DTMF PER CALL 2 ---------------------------	
	document.getElementById('dtmf1_2').addEventListener('click', ()=>{
		console.log('dtmf 1 clicked for call 2');
			sendDTMF('2','1');
	});
	document.getElementById('dtmf2_2').addEventListener('click', ()=>{
		console.log('dtmf 2 clicked for call 2');
			sendDTMF('2','2');
	});
	document.getElementById('dtmf3_2').addEventListener('click', ()=>{
		console.log('dtmf 3 clicked for call 2');
			sendDTMF('2','3');
	});
	document.getElementById('dtmf4_2').addEventListener('click', ()=>{
		console.log('dtmf 4 clicked for call 2');
			sendDTMF('2','4');
	});
	document.getElementById('dtmf5_2').addEventListener('click', ()=>{
		console.log('dtmf 5 clicked for call 2');
			sendDTMF('2','5');
	});
	document.getElementById('dtmf6_2').addEventListener('click', ()=>{
		console.log('dtmf 6 clicked for call 2');
			sendDTMF('2','6');
	});
	document.getElementById('dtmf7_2').addEventListener('click', ()=>{
		console.log('dtmf 7 clicked for call 2');
			sendDTMF('2','7');
	});
	document.getElementById('dtmf8_2').addEventListener('click', ()=>{
		console.log('dtmf 8 clicked for call 2');
			sendDTMF('2','8');
	});
	document.getElementById('dtmf9_2').addEventListener('click', ()=>{
		console.log('dtmf 9 clicked for call 2');
			sendDTMF('2','9');
	});
	document.getElementById('dtmf0_2').addEventListener('click', ()=>{
		console.log('dtmf 0 clicked for call 2');
			sendDTMF('2','0');
	});
	document.getElementById('dtmf*_2').addEventListener('click', ()=>{
		console.log('dtmf * clicked for call 2');
			sendDTMF('2','*');
	});
	document.getElementById('dtmf#_2').addEventListener('click', ()=>{
		console.log('dtmf # clicked for call 2');
			sendDTMF('2','#');
	});
	
	document.getElementById('dropGenericTransferButton1').addEventListener('click', ()=>{
		console.log('drop Generic transfer button clicked for call1');
			cancelTransferChannel('1');
	});
	document.getElementById('transferGenericButton1').addEventListener('click', ()=>{
		console.log('merge contacts clicked for call 1');
			mergeCall('1');
		});
		
		document.getElementById('dropGenericTransferButton2').addEventListener('click', ()=>{
		console.log('drop Generic transfer button clicked for call2');
			cancelTransferChannel('2');
	});
	document.getElementById('transferGenericButton2').addEventListener('click', ()=>{
		console.log('merge contacts clicked for call 2');
			mergeCall('2');
		});
}


function mergeCall(idx){
	if(idx=='1'){
		call1.callSipForTransferInstance.transfer();
		document.getElementById('channel1').style.display='none';
	}else {
		call2.callSipForTransferInstance.transfer();
		document.getElementById('channel2').style.display='none';
	}
}

function cancelTransferChannel(idx) {
	if(idx=='1'){
		call1.callSipForTransferInstance.terminate();
		document.getElementById('channel1').style.display='none';
		document.getElementById('callbar1').style.display='block';
	} else {
		call2.callSipForTransferInstance.terminate();
		document.getElementById('channel2').style.display='none';
		document.getElementById('callbar2').style.display='block';
	}
}

function transfCall(idx, blind = false, numToBlind = ''){
	if(!blind && call1 !== null && call2 !== null){
		if(idx =='1') {
			call1.transferToCall(call2).then((result) =>{
				console.log('attended transfer call1 with call2 result: ' + result);
			});
		} else {
			call2.transferToCall(call1).then((result) =>{
				console.log('attended transfer call2 with call1 result: ' + result);
			});
		}
	} else {
		if(!blind) {
			console.warn('attended transfer not available cause only one call up: ');
		}
	}
	if(blind && numToBlind != ''){
		if(idx =='1') {
			call1.transferToNumber(numToBlind).then((result) =>{
			console.log('transfer blind call1 with number result: ' + result);
			});
		} else {
			call2.transferToNumber(numToBlind).then((result) =>{
				console.log('transfer blind call2 with number result: ' + result);
			});
		}
	}
}

function sendDTMF(idx, value){
	if(idx =='1') {
		call1.sendDTMF(value).then((result) =>{
			console.log('answer result: ' + result);
		});
	} else {
		call2.sendDTMF(value).then((result) =>{
			console.log('answer result: ' + result);
		});
	}
}

function answerCall(idx){
	if(idx =='1') {
		call1.answer().then((result) =>{
			console.log('answer result: ' + result);
		});
	} else {
		call2.answer().then((result) =>{
			console.log('answer result: ' + result);
		});
	}
}

function toggleHold(idx, setHold){
	if(idx =='1' && setHold) {
		call1.hold().then((result) =>{
			console.log('hold result: ' + result);
		});
	} 
	if(idx =='1' && !setHold) {
		call1.unhold().then((result) =>{
			console.log('unhold result: ' + result);
		});
	} 
	
	if(idx =='2' && setHold) {
		call2.hold().then((result) =>{
			console.log('hold result: ' + result);
		});
	} 
	if(idx =='2' && !setHold) {
		call2.unhold().then((result) =>{
			console.log('unhold result: ' + result);
		});
	} 
}
function dropCall(idx){
	if(idx =='1') {
		call1.terminate().then((result) =>{
			console.log('terminate result: ' + result);
		});
	} else {
		call2.terminate().then((result) =>{
			console.log('terminate result: ' + result);
		});
	}
}


function eventListenersUI(){
	// listener for UI
	// login button
	document.getElementById('loginButton').addEventListener('click', ()=>{
		loginUser('classic');
	});
	// logout button
	document.getElementById('logoutButton').addEventListener('click', ()=>{
		logoutUser()
	});
	// dial button
	document.getElementById('dialButton').addEventListener('click', () =>{
		dialNumber();
	});
	//search button
	document.getElementById('searchButton').addEventListener('click', () =>{
		searchContacts();
	});
	//load call history
	document.getElementById('loadCallHistoryButton').addEventListener('click', () =>{
		loadCallHistory();
	});
	// login type
	document.getElementById('loginType').addEventListener("change", ()=>{
		document.getElementById('errorLogin').innerHTML = "";
		let value = document.getElementById('loginType').value;
		this.showHideLoginType(value);
	});
	document.getElementById('loginExternalButton').addEventListener('click', ()=>{
		loginUser('external');
	});
	document.getElementById('videoButton').addEventListener('click', ()=> {
		dialNumber(true);
	})
}

function updateCallInfoState(callId, state){
	if(call1 != null && call1.id == callId){
		document.getElementById('connectionState_1').innerHTML = state;
	} else {
		if(call2 != null && call2.id == callId){
			document.getElementById('connectionState_2').innerHTML = state;
		}
	}
}

function updateCallInfoStats(callId){
	if(call1 != null && call1.id == callId){
		document.getElementById('stats_1').innerHTML = 'Go to console, to look the results filter using "CALL STATS received: "';
	} else {
		if(call2 != null && call2.id == callId){
			document.getElementById('stats_2').innerHTML = 'Go to console, to look the results filter using "CALL STATS received: "';
		}
	}
}

function subscribeToCallsEvents(){
	// subscribe to event newcall to receive calls information
	client.phone.on('newcall', (call) => {
		console.log('event: received new call: ',call);
		//manage only sip call
		// if(call.type == 'SIP'){
			// call is a CallSip instance
			console.log('my currentcall: ', call);
			index = '0';
			if(call1== null){
				call1= call;
				index = '1';
				updateInfoForCall('1', true);
				if(call.type == 'WEBRTC') {
					updateAdvancedInfoForWebRTCCall('1', true);
				} else {
					updateAdvancedInfoForWebRTCCall('1', false);
				}
			} else {
				if(call2 == null) {
					call2= call;
					index = '2';
					updateInfoForCall('2', true);
					if(call.type == 'WEBRTC'){
						updateAdvancedInfoForWebRTCCall('2', true);
					} else {
						updateAdvancedInfoForWebRTCCall('2', false);
					}
				} else {
					console.warn('just have 2 calls in progress');
				}
			}
			if(call.type == 'WEBRTC' && index!= '0'){
				console.log('subscribe to connection manager for webrtc call and start to send events');
				updateCallInfoStats(call.id);
				call.connectionManager.on("state", function(state){ 
					console.info("state received: ", state);
					updateCallInfoState(call.id,state);
				})
				.on("connection_error", function(state){ 
					console.info("connection error received: ", state);
				})
				.on("local_audio_level", function(state){ 
					console.info("local_audio_level received: ", state);
				})
				.on("remote_audio_level", function(state){ 
					console.info("remote_audio_level received: ", state);
				})
				.on("stats", function(state){ 
					console.info("CALL STATS received: ", state);
				})
				//call.connectionManager.startLocalAudioLevel();
				//call.connectionManager.startRemoteAudioLevel();
				call.connectionManager.startConnectionStats();
				toggleAllConnectionManagerEvents(true, index);
				
			}

			function updateDisplay(display) {
				if(display.number){
					let element = document.getElementById('number'+index);
					if(element) {
						element.innerHTML ='number: ' + display.number;
					}
				}
				if(display.name){
					let element = document.getElementById('displayName'+index);
					if(element) {
						element.innerHTML ='name: ' + display.name;
					}
				}
				if(display.company){
					let element = document.getElementById('displayCompany'+index);
					if(element) {
						element.innerHTML ='company: ' + display.company;
					}
				}
			}

			if(call.lookup.display) {
				updateDisplay(call.lookup.display);
			}

			call.lookup.on("update_display", updateDisplay);
		//})
		//subscribe to call events
		call.on("accepted", function(){
			console.log("call event - call accepted with callId "+ call.lookup.display.number);
		})
		.on("ended", function() {
			//event for ended call: go to update objects and calls UI
			console.log("call event - ended", call);
			index = '0';
			try {
				call.connectionManager.stopRemoteAudioLevel();
				call.connectionManager.stopLocalAudioLevel();
				call.connectionManager.stopConnectionStats();
			} catch(e) {}
			if(call1 && call.id == call1.id){
				 call1 = null;
				 updateInfoForCall('1', false);
				 updateAdvancedInfoForWebRTCCall('1', false);
			}
			if(call2 && call.id == call2.id) {
				 call2 = null;
				 updateInfoForCall('2', false);
				 updateAdvancedInfoForWebRTCCall('2', false);
			}
			if(call2 != null && call1 == null){
				call1 = call2;
				updateInfoForCall('1', true);
				if(call1.type == 'WEBRTC'){
					updateAdvancedInfoForWebRTCCall('1', true);
				}
				call2 = null;
				updateInfoForCall('2', false);	
				updateAdvancedInfoForWebRTCCall('2', false);
			}
			
			toggleAllConnectionManagerEvents(false, index);
		 })
		.on("change_features", function(features) {
			//event for call features changed: go to update call buttons bar
			console.log("call event  - new features", features, call);
			if(call1 && call1.id == call.id){
				updateButtonsFromFeatures('1', call);
			}
			if(call2 && call2.id == call.id){
				updateButtonsFromFeatures('2', call);
			} 
		 })
		 .on("new_call_for_transfer", function() {
			 console.log("call event - new call for transfer received ");
		 });
	});

	client.phone.on('tvoxclient_state_change', (state, detail) => {		
		document.getElementById('tvoxclientinfo').innerHTML = state + " - " + JSON.stringify(detail);
	});

	client.phone.on('device_change', () => {
		updateInfoDevices();
	});
}

function toggleAllConnectionManagerEvents(start, index){
	//if(index
	
}

function subscribeToLoginStateEvents(){
	// subscribe to login event
	client.on('logged_in', () => {
		// user is logged in the client
		console.log('event: logged in');
		document.getElementById('loginEvent').innerHTML ='Logged in';
		document.getElementById('loginButton').disabled = true;
		document.getElementById('loginExternalButton').disabled = true;
		updateUserInfoLogged('User logged: '+ client.user.info.username);
	})
	.on('logged_out', () => {
		// user is logged out from the client
		console.log('event: logged out');
		toggleForm(true);
		document.getElementById('loginEvent').innerHTML ='Logged out';
		document.getElementById('loginButton').disabled = false;
		document.getElementById('loginExternalButton').disabled = false;
		resetUserStatus();
		updateUserInfoLogged('User logged out: '+ client.user.info.username);		
	})
	.on('login_in_progress', () => {
		// login for user is in progress.. waiting
		console.log('event: login in progress');
		document.getElementById('loginEvent').innerHTML ='Login in progress';
		document.getElementById('loginButton').disabled = true;
		document.getElementById('loginExternalButton').disabled = true;
		updateUserInfoLogged('Login in progress for user: '+ globalUsername );		
	})
	.on('login_failed', (error) => {
		// login failed, update UI to show login form
		console.log('event: login failed');
		toggleForm(true,false);
		document.getElementById('loginEvent').innerHTML =  'Logged failed, retry';
		document.getElementById('loginButton').disabled = false;
		document.getElementById('loginExternalButton').disabled = false;
		updateUserInfoLogged(' ERROR >> ' + JSON.stringify(error) + '<br>Login failed for: '+ globalUsername);		
	})
	.on("ready", function() {
		// user is ready to use 
        console.log("event: ready... client is ready to use");
		toggleForm(false);
		updateUserInfoLogged('Client ready for user: '+ client.user.info.username);
		updateInfoDevices(true);
		client.user.statusMonitor.start();
        // now we can use client attribute to interact with tvox
    });

	function resetUserStatus() {
		if (phoneStatusInterval) {
			clearInterval(phoneStatusInterval);
		}
		document.getElementById('user_phone_status').children[0].innerHTML = "";
		document.getElementById('user_phone_status_value').innerHTML = "";
		document.getElementById('user_phone_status_duration').innerHTML = "";

		document.getElementById('user_presence_status').children[0].innerHTML = "";
		document.getElementById('user_presence_status_value').innerHTML = "";
	}

	var phoneStatusInterval;
	var userPhoneStatusDurationElement = document.getElementById('user_phone_status_duration');
	client.user.statusMonitor.on("phone_status_changed", function(data){
		console.log("event: phone_status_changed... ", data);

		var node = document.createElement("li");
		node.innerHTML = JSON.stringify(data);
		document.getElementById('user_phone_status').children[0].prepend(node);
		document.getElementById('user_phone_status_value').innerHTML = data.status;

		if (phoneStatusInterval) {
			clearInterval(phoneStatusInterval);
		}
		phoneStatusInterval = setInterval(function() {
			userPhoneStatusDurationElement.innerHTML = millisecondsToStr(data.timeInStateMillis);
		}, 100);
	});

	client.user.statusMonitor.on("presence_status_changed", function(data){
		console.log("event: presence_status_changed... ", data);

		var node = document.createElement("li");
		node.innerHTML = JSON.stringify(data);
		document.getElementById('user_presence_status').children[0].prepend(node);
		document.getElementById('user_presence_status_value').innerHTML = data.status;
	});
}

function millisecondsToStr( milliseconds ) {
    let temp = milliseconds / 1000;
    const years = Math.floor( temp / 31536000 ),
          days = Math.floor( ( temp %= 31536000 ) / 86400 ),
          hours = Math.floor( ( temp %= 86400 ) / 3600 ),
          minutes = Math.floor( ( temp %= 3600 ) / 60 ),
          seconds = temp % 60;

    if ( days || hours || seconds || minutes ) {
      return ( years ? years + "y " : "" ) +
      ( days ? days + "d " : "" ) +
      ( hours ? hours + "h " : ""  ) +
      ( minutes ? minutes + "m " : "" ) +
      Number.parseFloat( seconds ).toFixed( 2 ) + "s";
    }

    return "< 1s";
}

function updateInfoDevices(addListenerForDeviceChange) {
	console.log('check devices available. If I have just one device, hide the select menu, otherwise, go to populate options');
	document.getElementById('deviceSelectionSection').style.display = 'block';
	console.log('device in use: ', client.phone.device);
	document.getElementById('deviceInUse').innerHTML = client.phone.device.label +' - ' + client.phone.device.type +' - '+ client.phone.device.exten;
	if(client.phone.availableDevice.length > 1){
		console.log('receive more one 1 device available, prepare the select options', client.phone.availableDevice);
		document.getElementById('deviceType').style.display='block';
		document.getElementById('deviceSectionTitle').style.display='block';
		generateOptionWithAvailableDevices();
		if(addListenerForDeviceChange) {
			addListenerForDevicesSelection();
		}
	} else {
		console.log('just one available device, no select to show');
		document.getElementById('deviceType').style.display='none';
		document.getElementById('deviceSectionTitle').style.display='none';
	}
	if(client.phone.device.type == 'WEBRTC'){
		document.getElementById('videoButton').style.display='none'; // funzionalità non implementata al momento
	} else {
		document.getElementById('videoButton').style.display='none';
	}
}
function addListenerForDevicesSelection(){
	document.getElementById('deviceType').addEventListener("change", ()=>{
		let value = document.getElementById('deviceType').value;
		console.log('new device to use:' + value);
		document.getElementById('errorDevice').innerHTML='';
		client.phone.useDevice(client.phone.availableDevice[value]).then((result) => {
			console.log('change device to use result: ' + result);
			if(result){
				updateInfoDevices()
			} else {
				console.error('useDevice return false, change device does not work');
				document.getElementById('errorDevice').innerHTML ='Change Device Failed, retry';
			
			}
		}).catch((error) =>{
			console.error('useDevice failed: exception received', error);
			document.getElementById('errorDevice').innerHTML ='Change Device Failed, retry';
		});
	});
}
function generateOptionWithAvailableDevices(){
	selectElement = document.getElementById('deviceType');
	while (selectElement.options.length > 0) {
        selectElement.remove(0);
    }
	for (let i = 0; i < client.phone.availableDevice.length; i++) {
		option = document.createElement("option");
		option.value = i;
		option.innerHTML = client.phone.availableDevice[i].label +' - '+client.phone.availableDevice[i].exten;
		document.getElementById('deviceType').appendChild(option);
	}
	document.getElementById('deviceType').value = client.phone.availableDevice.indexOf(client.phone.device);
	console.log('value selected:', document.getElementById('deviceType').value);
}

function loadCallHistory() {
	//search call history items: first page with size 10
	client.user.getCallHistory({'pageNumber':1,'pageSize':10}).then(function(result) {
		let value = [];
   result
       .on("data", function(data, index, total){
             console.log("callHistory - result - DATA received: ", data);
			 if(value.length==0){
				 
			 value.push(data.data);
			 }
         })
      .on("error", function(error) {
             console.error("callHistory - result - ERROR");
         })
      .on("complete", function() {
             console.log("callHistory - result - COMPLETE");
         });
	});
}
// method to search contact
function searchContacts() {
	var textToSearch = document.getElementById("textToSearch").value;
	textToSearch = textToSearch.trim();
	// toSearch: text digited by user
	// pageNumber to search
	// pageSize: dimension of page
	client.user.searchContact({'pageNumber':1,'pageSize':10, 'toSearch':textToSearch})
	.then(function(result) {
		let value = [];
   result
       .on("data", function(data, index, total){
             console.log("searchContact - result - DATA", data);
			 if(value.length==0){
				 
			 value.push(data.data);
			 }
         })
      .on("error", function(error) {
             console.error("searchContact - result - ERROR");
         })
      .on("complete", function() {
             console.log("searchContact - result - COMPLETE");
         });
})
	.catch(function(error) {
     console.error("searchContact - ERROR", error);
});

}

function dialNumber(videoCall = false){
	var number = document.getElementById("numToDial").value;
	number = number.trim();
	if(number != "" && !isNaN(number)) {
		if(client.phone.device.type == 'SIP'){
			//check if there is a call enabled for transfer SIP
			if(call1!= null && call1.isDialForTransferEnabled()){
				console.log('there is the possibility to transfer: prepare a channel');
				call1.dialForTransfer(number).then((result) => {
					if(result){
						console.log('transfer channel obtained ' + result);
						document.getElementById('callbar1').style.display = 'none';
						document.getElementById('channel1').style.display = 'block';
						//subscribe to event ended of call for transfer
						call1.callSipForTransferInstance.on("ended",() => {
							console.log('received ended on transfer instance');
							document.getElementById('callbar1').style.display = 'block';
							document.getElementById('channel1').style.display = 'none';
						});
					}
				}).catch((error) =>{
					console.error('error received on dial for transfer');
				});
			} else {			
				console.log('it is not possible to transfer enabled: made a normal dial');
				client.phone.device.dial(number);
			}
		} else {
			// dispositivo webrtc
			//device in use is WEBRTC... made different request for dial
			console.log('use webrtc device, made different request for dial');
			if(videoCall){
				console.info('user want start a video call');
				let videoContainer = document.getElementById('videoContainerCall1');
				if(call1!= null){
					videoContainer = document.getElementById('videoContainerCall2');
				}
				client.phone.device.dialVideo(number, number,);
			} else {
				client.phone.device.dialAudio(number);
			}
		}
	} else {
		alert('number not valid');
	}
}

function updateButtonsFromFeatures(idx, call){
	document.getElementById('holdButton'+idx).style.display = call.hasFeature('HOLD') ? 'block' : 'none';
	document.getElementById('unholdButton'+idx).style.display = call.hasFeature('UNHOLD') ? 'block' : 'none';	
	document.getElementById('dtmfBar'+idx).style.display = call.hasFeature('GENERATE_DTMF') ? 'block' : 'none';	
	document.getElementById('transferButton'+idx).style.display = call.hasFeature('TRANSFER_ATTENDED') ? call.deviceType == 'SIP' ? 'block' : (call1!= null && call2!= null ? 'block'  : 'none') : 'none';	
	document.getElementById('dropButton'+idx).style.display = call.hasFeature('CANCEL') ? 'block' : 'none';
	document.getElementById('answerButton'+idx).style.display = call.hasFeature('ANSWER') ? 'block' : 'none';
}

function updateAdvancedInfoForWebRTCCall(idx, show){
	var call = idx == '1' ? call1 : call2;
	document.getElementById('container_call_advanced_webRTC_'+idx).style.display = show? 'block' :'none';
}


function updateInfoForCall(idx, show) {
	var call = idx == '1' ? call1 : call2;

	document.getElementById('container_call_'+idx).style.display = show? 'block' :'none';
	if(call) {
		document.getElementById('callDirection'+idx).innerHTML = 'direction: ' + call.direction;
		updateButtonsFromFeatures(idx, call);
	}
	
	document.getElementById('channel'+idx).style.display = idx === '1' ? channel1 != null  ? 'block': 'none' : channel2 != null ? 'block' : 'none';
	/*if(call.lookup.display.service){
		document.getElementById('serviceName'+idx).innerHTML ='service: ' + call.lookup.display.company;
	}*/
}	

function updateUserInfoLogged(label){
	document.getElementById('userInfoLogged').innerHTML = label;
}

function toggleForm(showLoginForm, changeType=true){
	
	if(showLoginForm){
		document.getElementById('loginForm').style.display= 'block';
		document.getElementById('logoutForm').style.display='none';
		document.getElementById('loggedSection').style.display='none';
		if(changeType) {
			showHideLoginType('classic');
		}
	} else {
		document.getElementById('loginForm').style.display= 'none';
		document.getElementById('logoutForm').style.display= 'block';
		document.getElementById('loggedSection').style.display='block';
	}
	
}

function logoutUser(){
	client.logout();
}

function loginUser(type){
	if(type == 'classic'){
	let username = document.getElementById("username").value;
		globalUsername = username;
		let password = document.getElementById("password").value;
		  if (username == "" || password  == "") {
			document.getElementById('errorLogin').innerHTML ='Username and password must be filled!!';
			return;
		  }
		client.login({username: username,password: password}); //invoke login method
	} else {
		let username = document.getElementById("accessToken").value;
		globalUsername = username;
		if (username == "" ) {
			document.getElementById('errorLogin').innerHTML ='Access token must be filled!!';
			return;
		  }
		  client.login({externalSessionId: username}); //invoke login method
	}
}