﻿// DEBUG
function _empty() {}
var callee	= _empty;
var debug		= _empty;
var trace		= _empty;
function TRACE_SET(b) {}
function DEBUG_SET(b) {}
// CHECK
function checkNumber(e) {
	var keyCode = (window.event) ? e.keyCode : e.which;
	if ((keyCode > 95 && keyCode < 106) || // pavé numérique
			(keyCode > 44 && keyCode < 58)	|| // inser, suppr, 0/9
			(keyCode == 8 || keyCode == 9 || keyCode == 13 || keyCode == 46)	|| // back, tab, return, supprimer
			(keyCode == 16 || keyCode == 17 || keyCode == 18)	|| // shift, ctrl, alt
			(keyCode == 106 || keyCode == 220)	|| // *
			(keyCode > 35 && keyCode < 41)	) { // flèches, fin et début
		return true;
	}
	return false;
}
function sendPhoneNumber(e) {
	var keyCode = (window.event) ? e.keyCode : e.which;
	if ((keyCode > 95 && keyCode < 106) || // pavé numérique
			(keyCode > 44 && keyCode < 58)	|| // inser, suppr, 0/9
			(keyCode == 8 || keyCode == 9 || keyCode == 46)	|| // back, tab, supprimer
			(keyCode == 16 || keyCode == 17 || keyCode == 18)	|| // shift, ctrl, alt
			(keyCode == 106 || keyCode == 220)	|| // *
			(keyCode > 35 && keyCode < 41)	) { // flèches, fin et début
		
		if (Memorised) {
			Memorised = false;
			EditPhoneNo.value = '';		
		}
		return true;
	}
	else if (keyCode == 13) BtnDial_onclick();	// Return
	return false;
}
function isPinCode(value) {
	return value.match(/\d{12}/) == value;
}
// PREFIX '0'+ 9 chiffres
// PREFIX '00'+ 7 à 15 chiffres
function isPhoneNumber(value) {
	return value.match(/0\d{9}/) == value || value.match(/00\d{7,15}/) == value;
}

// VaxSIPUserAgent
function UpdateComboAudioIn() {
	while (ComboAudioIn.length > 0) ComboAudioIn.remove(0);  			
	oOption = document.createElement("OPTION"); 
	oOption.text= "Default Device"; 
	oOption.value = -1; 
	ComboAudioIn.add(oOption); 
	for (DeviceId = 0; DeviceId < VaxSIPUserAgentCAB.GetAudioInDevTotal(); DeviceId++) {
		oOption = document.createElement("OPTION"); 
		oOption.text= VaxSIPUserAgentCAB.GetAudioInDevName(DeviceId); 
		oOption.value= DeviceId; 
		ComboAudioIn.add(oOption); 
	}	
	ComboAudioIn.selectedIndex = 0;
}
function UpdateComboAudioOut() {
	while (ComboAudioOut.length > 0) ComboAudioOut.remove(0);		
	oOption = document.createElement("OPTION"); 
	oOption.text= "Default Device"; 
	oOption.value = -1; 
	ComboAudioOut.add(oOption); 	
	for (DeviceId = 0; DeviceId < VaxSIPUserAgentCAB.GetAudioOutDevTotal(); DeviceId++) {
		oOption = document.createElement("OPTION"); 
		oOption.text= VaxSIPUserAgentCAB.GetAudioOutDevName(DeviceId); 
		oOption.value= DeviceId; 
		ComboAudioOut.add(oOption); 
	}	
	ComboAudioOut.selectedIndex = 0;
}
function AddToListLines(value) {
	 oOption = document.createElement("OPTION"); 
	 oOption.text = value; 
	 oOption.value = 0; 
	 ListLines.add(oOption); 
}
function FindLine() {
	LineNo = ListLines.selectedIndex;
	if (LineNo == -1)	return -1;
	if (!VaxSIPUserAgentCAB.IsLineBusy(LineNo)) return LineNo;
	for (LineNo = 0; LineNo < 7; LineNo++)
		if (!VaxSIPUserAgentCAB.IsLineBusy(LineNo)) return LineNo;
	return -1;
}
function ChangeImgSize(objectId, value) {
	imgString = 'FgImg = document.getElementById("'+objectId+'Fg")';	
	eval(imgString);	
	imgString = 'BgImg = document.getElementById("'+objectId+'Bg")';	
	eval(imgString);
	FgImg.style.left = BgImg.offsetLeft+2;
	FgImg.style.top = BgImg.offsetTop+2;
	FgImg.width = (BgImg.width-4)/100*value;
	FgImg.height = BgImg.height-4;
}

var timerId = 0;
var ProgressBarTimer = 0;

function Online() {
	var FromURI = "";		
  if (BtnOnline.value == "Offline") {
		clearTimeout(timerId);
		clearTimeout(ProgressBarTimer);
		ChangeImgSize("SpkProgBar", 0);
		ChangeImgSize("MicProgBar", 0);		
		FirstDial = false;	
		BtnOnline.value = "Online";
		VaxSIPUserAgentCAB.UnInitialize();		
		while (ComboAudioIn.length > 0) ComboAudioIn.remove(0);
		while (ComboAudioOut.length > 0) ComboAudioOut.remove(0);

		while (ListLines.length > 0) ListLines.remove(0);
		vOnLine = false;        
    return;
	}
	//VaxSIPUserAgentCAB.SetDomainKey("trIAL-LICENSE-KEY");	
	VaxSIPUserAgentCAB.SetDomainKey(vK);	
	/***** Constructing SIP From URI for IP Telephony ***********/		
	if (DisplayName == "") {
		FromURI = vL + " <sip:" + vL + "@" + vI + ">";
		}
	else {
		FromURI = DisplayName + " <sip:" + vL + "@" + vI + ">";
	}
	/********************************************************************
		Listen Port: default SIP port 5060.
 		SIP Proxy: SIP Proxy IP or FQDN provided by your sevIce provider.
 		OutboundProxy: SIP outbound/NAT proxy IP or FQDN provided by your 
		             sevIce provider to use SIP phone behind the NAT.
	*********************************************************************/	
	MyIP = VaxSIPUserAgentCAB.GetMyIP();
	debug(callee(1)+' '+vL +' &lt;sip:'+ vL +'@'+ vI +'&gt; '+ MyIP, 'red'); 

	for (ListenPortSIP = 5060; ListenPortSIP < 7000; ListenPortSIP++) {
		Result = VaxSIPUserAgentCAB.Initialize(0, MyIP, ListenPortSIP, FromURI, SIPOutboundProxy, vI, vL, vP, 1, 7);
		if (!Result) {
			if (VaxSIPUserAgentCAB.GetVaxObjectError() != 11) {
				ErrorMessage();
				break;
			}
		} else {
			break;
		}
	}

	if (ListenPortSIP >= 7000) {
		alert("Cann't open SIP communication port.");
		return;
	}
		
	if (Result) {
		ListenPortRTP = 7000;
		ErrorCount = 0;
				
		for (LineNo = 0; LineNo < 7; LineNo++) {
			if (!VaxSIPUserAgentCAB.OpenLine(LineNo, 0, MyIP, ListenPortRTP)) {
				if (VaxSIPUserAgentCAB.GetVaxObjectError() == 11) {
					ErrorCount++;
					LineNo--;
				}
				else {
					ErrorMessage();
					Result = FALSE;
					break;
				}
			}		
			ListenPortRTP += 2;  // It is importent to increament RTP Listen Port by 2
			if (ErrorCount >= (7 + 500)) { // If unable to open more than 500 ports.
				alert("Unable to open RTP communication port.");
				return;
			}
		}// for
	}
	
	if (Result) {
		if (RegisterToSIPProxy) {
			if (!VaxSIPUserAgentCAB.RegisterToProxy(3600)) {
				ErrorMessage();
				return;
			}
		}

		BtnOnline.value = "Offline";					
		CheckEchoCancel_onclick();		
		VaxSIPUserAgentCAB.DeselectAllVoiceCodec();
				
		//VaxSIPUserAgentCAB.SelectVoiceCodec(0);	// GSM610
		//VaxSIPUserAgentCAB.SelectVoiceCodec(1);	// iLBC
		//VaxSIPUserAgentCAB.SelectVoiceCodec(2);	// G711A
		//VaxSIPUserAgentCAB.SelectVoiceCodec(3);	// G711U
		VaxSIPUserAgentCAB.EnableKeepAlive(10);
		
		UpdateComboAudioIn();
		UpdateComboAudioOut();
		
		timerId = setTimeout("TimerTick()", 1000);
		ProgressBarTimer = setTimeout("ProgressBarTick()", 20);
		vOnLine = true;
	}
}
function AddToStatusLogList(value) {
 	if (ListStatusLog.value.length == 0)
	ListStatusLog.value = ListStatusLog.value + value;
	else
		ListStatusLog.value = ListStatusLog.value + "\n" + value;
	ListStatusLog.scrollTop = ListStatusLog.scrollHeight; 
} 

var Memorised = false;
function BtnDial_onclick() {
	if (!isPhoneNumber(EditPhoneNo.value)) {
		openBrWindow('../PopUp/Default.aspx?mess=Numéro de téléphone non valide.');
		//alert("Numéro de téléphone non valide.");
		return;
	}
	
	for (var i = 0; i < EditPhoneNo.value.length; i++)
		VaxSIPUserAgentCAB.DigitDTMF(ListLines.selectedIndex, EditPhoneNo.value.charAt(i));
		
	if (BtnDial.disabled) {
		Memorised = true;
		return;
	}
		
	/*******************************************************
         Constructing SIP To URI for IP Telephony:
                  sip:PhoneNumber@SIP Proxy
  ********************************************************/	
	ToURI = "sip:" + (FirstDial?'':vPC) + EditPhoneNo.value + "@" + vI;	

	LineNo = FindLine();
	if (LineNo == -1) {
		alert("No line is free");
		return;
	}					
	InputDeviceId  = ComboAudioIn.options[ComboAudioIn.selectedIndex].value;
	OutputDeviceId = ComboAudioOut.options[ComboAudioOut.selectedIndex].value;
			
	if (!VaxSIPUserAgentCAB.Connect(LineNo, ToURI, InputDeviceId, OutputDeviceId))
		ErrorMessage();
	else {
		ListLines.options[LineNo].text = "Line-" + (LineNo + 1) + "    :    " + "CONNECTING";
		//EditPhoneNo.value ='';
		DisplayInfo.innerHTML = "Appel en cours...";
		BtnDial.style.display="none";
		BtnHangUp.style.display="block";
		Memorised = true;
		//FirstDial = true;
	}
}
function BtnHangUp_onclick() {
  if (!VaxSIPUserAgentCAB.Disconnect(ListLines.selectedIndex))
		ErrorMessage();
	BtnDial.style.display="block";
	BtnHangUp.style.display="none";
}
function BtnDialPad_onclick(Key) {
	if (Memorised) {
		Memorised = false;
		EditPhoneNo.value = '';		
	}
	if (Key.match(/[0-9*#]/)== Key) EditPhoneNo.value += Key;
	VaxSIPUserAgentCAB.DigitDTMF(ListLines.selectedIndex, Key);
}
function CheckEchoCancel_onclick() {
   if (CheckEchoCancel.checked)
		VaxSIPUserAgentCAB.EnableEchoNoiseCancellation();
	else
		VaxSIPUserAgentCAB.DisableEchoNoiseCancellation();
}
function CheckSpkMute_onclick() {
 VaxSIPUserAgentCAB.MuteSpk(CheckSpkMute.checked);
}
function CheckMicMute_onclick() {
  VaxSIPUserAgentCAB.MuteMic(CheckMicMute.checked);
}
function BtnSpkVolUp_onclick() {
  SpkVol = EditSpkVol.value;
  if (SpkVol == 10) return;
  
  SpkVol++;
  EditSpkVol.value = SpkVol;  
  /***************************************************************
	SetSpkVolume method requires Volume value from 0 to 255 range    
	but the slider range is 0 to 10, so we multiply the slider value 
	to 25 to get the required value to pass to SetSpkVolume method   

	    For more detail, please see the method details document
  *****************************************************************/  
  VaxSIPUserAgentCAB.SetSpkVolume(SpkVol * 25);
}
function BtnSpkVolDown_onclick() {
  SpkVol = EditSpkVol.value;
  if (SpkVol == 0) return;
  
  SpkVol--;
  EditSpkVol.value = SpkVol;
  /***************************************************************
	SetSpkVolume method requires Volume value from 0 to 255 range    
	but the slider range is 0 to 10, so we multiply the slider value 
	to 25 to get the required value to pass to SetSpkVolume method   

	    For more detail, please see the method details document
  *****************************************************************/    
  VaxSIPUserAgentCAB.SetSpkVolume(SpkVol * 25);
}
function BtnMicVolUp_onclick() {
  MicVol = EditMicVol.value;
  if (MicVol == 10) return;
  
  MicVol++;
  
  EditMicVol.value = MicVol;  
  /***************************************************************
	SetMicVolume method requires Volume value from 0 to 255 range    
	but the slider range is 0 to 10, so we multiply the slider value 
	to 25 to get the required value to pass to SetMicVolume method   

	  For more detail, please see the method details document
  *****************************************************************/   
  VaxSIPUserAgentCAB.SetMicVolume(MicVol * 25);
}
function BtnMicVolDown_onclick() {
  MicVol = EditMicVol.value;
  if (MicVol == 0) return;
    
  MicVol--;
  EditMicVol.value = MicVol;  
  /***************************************************************
	SetMicVolume method requires Volume value from 0 to 255 range    
	but the slider range is 0 to 10, so we multiply the slider value 
	to 25 to get the required value to pass to SetMicVolume method   

	  For more detail, please see the method details document
  *****************************************************************/  
  VaxSIPUserAgentCAB.SetMicVolume(MicVol * 25);
}
function BtnClearLog_onclick() {
	ListStatusLog.value = "";
}
function ProgressBarTick() {
	ProgressBarTimer = setTimeout("ProgressBarTick()", 20);
	ChangeImgSize("SpkProgBar", VaxSIPUserAgentCAB.GetSpkSoundLevel());
	ChangeImgSize("MicProgBar", VaxSIPUserAgentCAB.GetMicSoundLevel());
}
function UpdateLineList(LineNo) {
	for (LineCount = 0; LineCount < 7; LineCount++) {
		if (LineCount == LineNo) continue;
	
		if (VaxSIPUserAgentCAB.IsLineBusy(LineCount) == 1 && VaxSIPUserAgentCAB.IsLineHold(LineCount) == 0) {
			VaxSIPUserAgentCAB.HoldLine(LineCount);
		}
	}

	if (VaxSIPUserAgentCAB.IsLineHold(LineNo))
		VaxSIPUserAgentCAB.UnHoldLine(LineNo);
}	
function TimerTick() {
  var ItemText = "";		
	timerId = setTimeout("TimerTick()", 1000);	
	if (ListLines.length == 0) {
		for (LineNo = 0; LineNo < 7; LineNo++) {
			AddToListLines("Line-" + (LineNo + 1) + "    :    FREE");
		}

		ListLines.selectedIndex = 0;
	}

	UpdateLineList(ListLines.selectedIndex);
		
	for (ItemNo = 0; ItemNo < ListLines.length; ItemNo++) {
		ItemText = "Line-" + (ItemNo + 1) + "    :    ";
								
		if (!VaxSIPUserAgentCAB.IsLineOpen(ItemNo)) {
		    if (ListLines.options[ItemNo].text.indexOf("CLOSE") == -1) {
			    ListLines.options[ItemNo].text = ItemText + "CLOSE";
			}
		}
		else if (VaxSIPUserAgentCAB.IsLineBusy(ItemNo)) {
			if (VaxSIPUserAgentCAB.IsWaveFilePlaying(ItemNo)) {
				if (ListLines.options[ItemNo].text.indexOf("PLAY") == -1) {
			        ListLines.options[ItemNo].text = ItemText + "PLAY";
			    }
			}
			else if (VaxSIPUserAgentCAB.IsLineHold(ItemNo)) {
				if (ListLines.options[ItemNo].text.indexOf("HOLD") == -1)  {
			        ListLines.options[ItemNo].text = ItemText + "HOLD";
			    }
			}
			else {
				if (ListLines.options[ItemNo].text.indexOf("BUSY") == -1 && ListLines.options[ItemNo].text.indexOf("CONNECTING") == -1) {
			        ListLines.options[ItemNo].text = ItemText + "BUSY";
			    }
			}
		}
		else {
			if (ListLines.options[ItemNo].text.indexOf("FREE") == -1) {
			    ListLines.options[ItemNo].text = ItemText + "FREE";
			}
		}	
	}	// for
}
function ErrorMessage() {
	VaxError = VaxSIPUserAgentCAB.GetVaxObjectError();
	switch(VaxError) {
		case 10: alert("You are not online, please click the 'Online' button first to dial/receive the calls.");
			break;
		case 11: alert("Cann't open local communication port. Another softphone (x-Ten, x-lite, skype etc) is already running. Please close it first.");
			break;
		case 12: alert("License Key is not valid.");
			break;
		case 13: alert("Fail to initialize VaxVoIP task window.");
			break;
		case 14: alert("Cann't access Input/Mic device or device is already in use.");
			break;
		case 15: alert("Cann't access Output/Speaker device or device is already in use.");
			break;
		case 16: alert("Input/Mic device is not open."); 
			break;
		case 17: alert("Output/Speaker device is not open."); 
			break;
		case 18: alert("Your sound device does not support mic volume."); 
			break;
		case 19: alert("Your sound device does not support speaker volume."); 
			break;
		case 20: alert("Recording media initialization fail.");
			break;
		case 21: alert("Cann't open the wave file.");
			break;
		case 22: alert("Provided SIP URI is not valid.");
			break;
		case 23: alert("Codec is not supported.");
			break;
		case 24: alert("Error to create SDP (Session Description Protocol) request.");
			break;
		case 25: alert("Error to create CONNECTION request. Please check the provided SIP URI is valid.");
			break;
		case 26: alert("Error to create REGISTER request. Please check the provided SIP URI is valid.");
			break;
		case 27: alert("Error to create UN-REGISTER request. Please check the provided SIP URI is valid.");
			break;
		case 28: alert("Error to create DISCONNECT request.");
			break;
		case 29: alert("Line No is not valid.");
			break;
		case 30: alert("Line is already busy.");
			break;
		case 31: alert("Line is not open.");
			break;
		case 32: alert("Invalid Call-Id.");
			break;			
		case 33: alert("Provided value is not valid.");
			break;			
		case 34: alert("Selected line is not in voice session.");
			break;			
		case 35: alert("Fail to read wave file.");
			break;			
		case 36: alert("Fail to write wave file.");
			break;			
		case 37: alert("Unsupported wave file format.");
			break;
	}
}
function OnTryingToRegister() { trace(callee(1)); AddToStatusLogList("Trying to register."); }
function OnSuccessToRegister() { trace(callee(1)); AddToStatusLogList("Registered successfully."); }
function OnFailToRegister() { trace(callee(1)); AddToStatusLogList("Fail to register."); }
function OnTryingToReRegister() { trace(callee(1)); AddToStatusLogList("Trying to re-register."); }
function OnSuccessToReRegister() { trace(callee(1)); AddToStatusLogList("Re-registered successfully."); }
function OnFailToReRegister() { 	trace(callee(1)); AddToStatusLogList("Fail to re-register."); }
function OnTryingToUnRegister() { trace(callee(1)); AddToStatusLogList("Trying to un-register."); }
function OnSuccessToUnRegister() { trace(callee(1)); AddToStatusLogList("Unregistered successfully."); }
function OnFailToUnRegister() { trace(callee(1)); AddToStatusLogList("Fail to un-register."); }
function OnIncomingDiagnostic(MsgSIP, FromIP, FromPort) {
	trace(callee(1));
	// SIP/2.0 200 OK (X-Asterisk-HangupCause: Normal Clearing)
	// SIP/2.0 481 Call leg/transaction does not exist
	if (Connecting && MsgSIP.indexOf('X-Asterisk-HangupCause: Normal Clearing') > -1) { Connecting = false; disconnectCall(); }
}
function OnOutgoingDiagnostic(MsgSIP, ToIP, ToPort) { trace(callee(1)); }
function OnMsgNOTIFY(Msg) { trace(callee(1)); }
function OnConnecting(LineNo) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Connecting."); }
var Connecting = false;
function OnSuccessToConnect(LineNo, ToRTPIP, ToRTPPort) {
	trace(callee(1));
  if (LineNo != ListLines.selectedIndex) {
		VaxSIPUserAgentCAB.HoldLine(LineNo);
		ListLines.options[LineNo].text = "Line-" + (LineNo + 1) + "    :    " + "HOLD";
	}
	else
		ListLines.options[LineNo].text = "Line-" + (LineNo + 1) + "    :    " + "BUSY";
	
	AddToStatusLogList("Line-" + (LineNo + 1) + ": Success to connect.");
        
  VaxSIPUserAgentCAB.SetSpkVolume(EditSpkVol.value * 25);
  VaxSIPUserAgentCAB.SetMicVolume(EditMicVol.value * 25);
  Connecting = true;
}
function OnFailToConnect(LineNo) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Fail to connect."); }
function OnDisconnectCall(LineNo) { trace(callee(1));  AddToStatusLogList("Line-" + (LineNo + 1) + ": Hung up."); Connecting = false; disconnectCall(); }
function OnCallTransferAccepted(LineNo) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Transfer accepted."); }
function OnPlayWaveDone(LineNo) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Play wave file done."); }
function OnDTMFDigit(LineNo, Digit) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Key-pressed: " + Digit); }
function OnProvisionalResponse(LineNo, StatusCode, ReasonPhrase) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Response: " + ReasonPhrase + "."); }
function OnRedirectionResponse(LineNo, StatusCode, ReasonPhrase, Contact) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Response: " + ReasonPhrase + "."); }
function OnServerFailureResponse(LineNo, StatusCode, ReasonPhrase) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Response: " + ReasonPhrase + "."); }
function OnGeneralFailureResponse(LineNo, StatusCode, ReasonPhrase) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Response: " + ReasonPhrase + "."); }
function OnRequestFailureResponse(LineNo, StatusCode, ReasonPhrase) { trace(callee(1)); AddToStatusLogList("Line-" + (LineNo + 1) + ": Response: " + ReasonPhrase + "."); }



