<?PHP

### SET THE PHONE NUMBER - BASED ON A BUNCH OF RANDOM VARS -- NED TO CLEAN ###

/// LIVE:
$master_config_type = "LIVE";
if(stristr($master_config_type,"LIVE")) {

	$tmp_sql = "SELECT * FROM phone_numbers WHERE memberid = '".$_SESSION['member']['memberid']."' AND status = 'ACTIVE';";
	$tmp_member_phone = readTHECASHIER($tmp_sql);

	$_SESSION['authorization']['phone']['country_code'] = $tmp_member_phone->calling_code;
	$_SESSION['authorization']['phone']['number'] = $tmp_member_phone->number;

/// DEV:
} else {

	if($_GET['dev'] == 'shahid'){
	    $_SESSION['authorization']['phone']['country_code'] = "880";
	    $_SESSION['authorization']['phone']['number'] = "1714066603";
	}
	
	if($_GET['call'] == 'db'){
	    $_SESSION['authorization']['phone']['country_code'] = "85";
	    $_SESSION['authorization']['phone']['number'] = "262084463";
	}
	
	if($_GET['call'] == 'js'){
	    $_SESSION['authorization']['phone']['country_code'] = "66";
	    $_SESSION['authorization']['phone']['number'] = "880083265";
	}
	
	if($_GET['call'] == 'pm'){
	    $_SESSION['authorization']['phone']['country_code'] = "61";
	    $_SESSION['authorization']['phone']['number'] = "403778000";
	}
	
	if($_GET['call'] == 'sw'){
	    $_SESSION['authorization']['phone']['country_code'] = "66";
	    $_SESSION['authorization']['phone']['number'] = "896871869";
	}
}

?>

<script type='text/javascript'>


String.prototype.trim = function() { 
	return this.replace(/^\s+|\s+$/, ''); 
}

var numberToDial = "";

var tableSteps = "";
tableSteps = tableSteps+"<center>";
/// START TABLE 0
tableSteps = tableSteps+"<table style='width:750px;' border='0'>";
tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td class='voice_td_1' colspan='2' border='1'>";


/// START TABLE 1
tableSteps = tableSteps+"<table style='width:100%; border-width:1px; border-style:solid; border-color:#006600; padding:0px; spacing:0px; margin:0px'>";
tableSteps = tableSteps+"<tr id='registeredNumber'>";
tableSteps = tableSteps+"<td style='padding:3px; padding-top:5px; padding-left:5px;'>";

tableSteps = tableSteps+"<span style='font-family:verdana; font-size:11px; font-weight:bold; color:#005500;'>";
tableSteps = tableSteps+"Your Registered Phone Number:";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+" ";
tableSteps = tableSteps+"<span style='font-size:14px; font-weight:bold; font-family:verdana; color:#009900;'>";
tableSteps = tableSteps+"+";
tableSteps = tableSteps+"<span id='numberToCall'>";
tableSteps = tableSteps+"<? echo $_SESSION['authorization']['phone']['country_code'] . "&nbsp;" . $_SESSION['authorization']['phone']['number']; ?>";
//tableSteps = tableSteps+"XX/00000000";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;&nbsp;<span class='voice_text_1' id='callmeTxt4'>(<a href=\"javascript:editPhoneNumber()\">edit</a>)</span>";

tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"<td colspan='1' align='right' style='padding:3px; padding-top:5px; padding-right:5px; color:#008800; font-size:11px; font-weight:bold; font-family:verdana;'>";

tableSteps = tableSteps+"<span id='attemptStatus'>";
tableSteps = tableSteps+"</span>";

tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";
tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td id='editRegisteredNumber' class='voice_td_2' colspan='2'>";

tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";
tableSteps = tableSteps+"</table>";
/// END TABLE 1

tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";
tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td class='voice_td_1' colspan='2' border='1'>";

/// START TABLE 2
tableSteps = tableSteps+"<table style='width:100%; border-width:1px; border-style:solid; border-color:#006600; padding:0px; spacing:0px; margin:0px'>";

tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td style='padding:3px; padding-top:12px; padding-left:5px; text-align:center;'>";
tableSteps = tableSteps+"<?php echo outputSelectCountryAVT($name_of_field='AVT_COUNTRY_ISO3',$session_value=$_SESSION['avt']['country_iso3'],$css_class='select_style_avt');?>";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";



tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td style='padding:3px; padding-top:12px; padding-left:5px; text-align:center;'>";
tableSteps = tableSteps+"<nobr>";
tableSteps = tableSteps+"<span style='font-family:verdana; font-size:14px; font-weight:bold; color:#6B3CB7;'>";
tableSteps = tableSteps+"...and then set your <u>Customer's Telephone Number</u>:";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"</nobr>";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";




tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td style='padding:3px; padding-top:12px; padding-left:5px; text-align:center;'>";

tableSteps = tableSteps+"<span id='numberToCall'>";
//tableSteps = tableSteps+"<?php echo outputSelectCallingCode($name_of_field='CALLING_CODE',$session_value=$_SESSION['avt']['calling_code'],$css_class='select_style_avt');?>";
tableSteps = tableSteps+"<span style='font-size:22px;' id='AVT_COUNTRY_CALLING_CODE'>+<?php echo $_SESSION['avt']['calling_code'];?></span>";
tableSteps = tableSteps+"&nbsp;";
tableSteps = tableSteps+"<span style='font-size:24px; font-weight:bold; font-family:verdana; color:#009900;'>";
tableSteps = tableSteps+"/";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;";
tableSteps = tableSteps+"<input class='avt_telephone_field' type='text' name='phonenumber2' id='AVT_LOCAL_NUMBER' value='<? echo $_SESSION['avt']['local_number']; ?>' onkeyup='onChangeLocalNumber(this);' />";
tableSteps = tableSteps+"</span>";

tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";



tableSteps = tableSteps+"</tr>";
tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td colspan='2' style='padding-top:10px; color:#888888; font-weight:normal; font-size:11px; text-align:center;'>";
tableSteps = tableSteps+"<b>Format:</b> +COUNTRY CODE <b>/</b> LOCAL-TELEPHONE-NUMBER (USA Example: +<u>1/9175551212</u>, etc.)";
tableSteps = tableSteps+"</td>";

tableSteps = tableSteps+"<td colspan='1' align='right' style='padding:3px; padding-top:5px; padding-right:5px; color:#008800; font-size:11px; font-weight:bold; font-family:verdana;'>";
tableSteps = tableSteps+"<span id='attemptStatus'>";
tableSteps = tableSteps+"</span>";

tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";

tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td class='voice_td_2' colspan='2'>";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";

tableSteps = tableSteps+"</table>";
/// END TABLE 2


tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";
tableSteps = tableSteps+" ";
tableSteps = tableSteps+"<tr>";


tableSteps = tableSteps+"<td id='callback_voice_td_3' class='voice_td_3' style='width:60%; font-size:14px; font-family:verdana;arial; font-weight:normal;'>";
tableSteps = tableSteps+"<nobr>";
tableSteps = tableSteps+"<span class='underline' id='step1'>";
tableSteps = tableSteps+"Step 1.";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;&nbsp;";
tableSteps = tableSteps+"<span id='callmeTxt1'>";
tableSteps = tableSteps+"Click this";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;";
tableSteps = tableSteps+"<span id='callme'>";
tableSteps = tableSteps+"<button  class='submit_button_16px' style='font-weight:bold; color:#006600;' onclick='makePhoneCall();' type='button' name='call' value='Call Me!'>";
tableSteps = tableSteps+"\"Start This Sales Call Now!\"";
tableSteps = tableSteps+"</button>";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"<span id='callmeTxt2'>";
tableSteps = tableSteps+"&nbsp;";
tableSteps = tableSteps+"button.";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;&nbsp;";
tableSteps = tableSteps+"<span id='callmestatus'></span>";
tableSteps = tableSteps+"</nobr>";
tableSteps = tableSteps+"</td>";


tableSteps = tableSteps+"<td style='width:40%;' align='right'>";
tableSteps = tableSteps+"<span id='callmeTxt3'></span>";
tableSteps = tableSteps+"</td>";


tableSteps = tableSteps+"</tr><tr>";


tableSteps = tableSteps+"<td id='callback_voice_td_4' class='voice_td_4' colspan='2' align='left' style='font-size:12px; font-family:verdana;arial; font-weight:normal; color:#BBBBBB; height:auto; vertical-align:top; padding-top:10px; line-height:22px;'>";
tableSteps = tableSteps+"Within few seconds, <? echo $_SESSION['template']['company']['simple_name']; ?>'s <span  style='font-size:14px;'><b><i>e-TERMINAL.NET<sup><span style='font-size:10px; font-weight:normal;'>&nbsp;&#8480;</span></sup></i></b></span> will call your Registered Phone Number,<br>and link you to your customer. (For your protection, your phone number is <u>never revealed</u> in this process.";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";

tableSteps = tableSteps+"<tr  id='callback_voice_td_4B'>";
tableSteps = tableSteps+"</tr>";

tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td id='callback_voice_td_5' class='voice_td_5' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal; padding-top:18px;'>";
tableSteps = tableSteps+"<span class='notUnderline' id='step2'>";
tableSteps = tableSteps+"Step 2.";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;&nbsp;";
tableSteps = tableSteps+"<span style='color:#AAAAAA;'>Connect to your customer.</span>";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";	
					
					
tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td id='callback_voice_td_6' class='voice_td_6' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal; padding-top:22px;'>";
tableSteps = tableSteps+"<span class='notUnderline' id='step3'>";
tableSteps = tableSteps+"Step 3.";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;&nbsp;";
//tableSteps = tableSteps+"<span style='color:#AAAAAA;'>Wait and listen for your customer to join the call.</span>";
tableSteps = tableSteps+"<span style='color:#AAAAAA;'>When you are ready:</span> <button type='button' class='submit_button_16px' style='color:#AAAAAA;' disabled='true' name='record' value='PAYNOW'>Click here to <b>LAUNCH the Payment Process.</b></button>";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";

/*
tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td id='callback_voice_td_7' class='voice_td_6' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal;'>";
tableSteps = tableSteps+"<span class='notUnderline' id='step4'>";
tableSteps = tableSteps+"Step 4.";
tableSteps = tableSteps+"</span>";
tableSteps = tableSteps+"&nbsp;&nbsp;";
tableSteps = tableSteps+"<span style='color:#AAAAAA;'>Any time you are ready:</span> <input type='button' disabled='true' name='record' value='Click Here to Start the Actual Payment Process.'>";
tableSteps = tableSteps+"</td>";
tableSteps = tableSteps+"</tr>";
*/

tableSteps = tableSteps+"<tr>";
tableSteps = tableSteps+"<td id='callback_voice_td_8' class='voice_td_6' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal;'>";
//tableSteps = tableSteps+"<span class='notUnderline' id='step5'>";
//tableSteps = tableSteps+"Step 4.";
//tableSteps = tableSteps+"</span>";
//tableSteps = tableSteps+"&nbsp;&nbsp;";
//tableSteps = tableSteps+"<input type='button' disabled='true' name='payment' value='TRANSFER customer to BANGK! - complete the sale, now...'>";
tableSteps = tableSteps+"</td>";

tableSteps = tableSteps+"</tr><tr>";

tableSteps = tableSteps+"<td id='callback_voice_td_9' class='voice_td_6' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal;'>";
//tableSteps = tableSteps+"<span class='notUnderline' id='step6'>";
//tableSteps = tableSteps+"Step 6.";
//tableSteps = tableSteps+"</span>";
//tableSteps = tableSteps+"&nbsp;&nbsp;";
//tableSteps = tableSteps+"<input type='button' disabled='true' name='reconnect' value='ACCEPT RETURNING CUSTOMER'>";
tableSteps = tableSteps+"</td>";

tableSteps = tableSteps+"</tr><tr>";

tableSteps = tableSteps+"<td id='callback_voice_td_10' class='voice_td_6' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal;'>";
tableSteps = tableSteps+"</td>";

tableSteps = tableSteps+"</tr>";
tableSteps = tableSteps+"</table>";
/// END TABLE 0
tableSteps = tableSteps+"</center>";
/// END

//var rowHangup = "<tr><td id='callback_voice_td_10' class='voice_td_6' colspan='2' style='font-size:14px; font-family:verdana;arial; font-weight:normal;'><span class='notUnderline' id='step7'>Step 5.</span>&nbsp;&nbsp;<input type='button' disabled='true' name='hangup' value='Click to HANGUP when you are finished with your call.'></td></tr>";

var tableStartCallRecord = "<span class='underline' id='step4'>Step 3</span>&nbsp;&nbspWhen you are ready: <button  class='submit_button_16px' style='font-weight:bold; color:#006600;' onclick='displayGuidedAVTScript(this);' type='button' name='startCallRecord' value='Start Recording'>Click Here to Launch the PCI-Compliant Payment Process...</button><br><br><div id='guidedAVTScript'></div>";

var tableStartPayment = "<span class='underline' id='step5'>Step 55.</span>&nbsp;&nbsp;<button  class='submit_button_13px' style='font-weight:bold; color:#006600;' onclick='avtPaymentProcess();' type='button' name='callPayment' value='Start Payment'>\"TRANSFER customer to BANGK! - complete the sale, now...\"</button>";

var tableStartCallReconnect = "<span class='underline' id='step6'>STEP 4.</span>&nbsp;&nbsp;<button  class='submit_button_18px' style='font-weight:bold; color:#006600;' onclick='avtCallReconnect(\"unpark\");' type='button' name='startCallReconnect' value='ACCEPT RETURNING CUSTOMER'>\"Click to ACCEPT RETURNING CUSTOMER NOW!\"</button>";

var tableCallHangup = "<button  class='submit_button_18px' style='font-weight:bold; color:#AB0025;' onclick='hangupPhoneCall(this);' type='button' name='hangup' value='HANGUP'><u>Click here to <b>HANGUP</b></u> when you are finished with your call.</button>";

var tableCallHangup_INSUFFICIENT = "";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "<br>";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "<button  class='submit_button_18px' style='font-weight:bold; color:#AB0025;' onClick=\"tryNewCard()\" type='button' name='NEW_CARD' value='NEW_CARD'>";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "DO NOT HANG-UP, click here to <u>try a NEW CARD</u>!";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "</button>";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "<br>";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "<button  class='submit_button_18px' style='font-weight:bold; color:#AB0025;' onclick='hangupPhoneCall(this);' type='button' name='hangup' value='HANGUP'>";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "<u>Click here to <b>HANGUP</b</u> when you are finished with your call.";
tableCallHangup_INSUFFICIENT = tableCallHangup_INSUFFICIENT + "</button>";

var rowGuidedAVT = "<tr><td id='callback_voice_td_11' class='voice_td_6' colspan='2'></td></tr>";

/*

<tr><td class='voice_td_4' align='right'><nobr><span style='color:#FF5F46; font-size:12px; font-weight:normal; font-family:arial; text-decoration:none;'><a href='javascript:onclick=\"cancelEdit()\"'>Click here to Hang-Up & Redial</a>.</span></nobr></td></tr>

*/

window.phoneCallRequest = null;
window.statusRequest 	= null;
window.checkFileRequest = null;
window.answeredRequest  = null;

window.uuid 		= "";
window.calling_attempt 	= 0;
window.gateway_attempt 	= 1;
window.hangup_count 	= 0;

window.uuid_check_limit = 60;   //in seconds
window.uuid_check_time 	= window.uuid_check_limit;

window.countingDownInterval = null;
window.is_ringing = false;
window.is_finished = false;
window.uuid_sessions = new Array();
/*
//INTERVAL VARIABLES

var checkCallingStatusInterval;
var hangingUpInterval;

//GLOBAL VARIABLES
window.call_sessions = new Array();



var hanging_up_limit = 4; //in seconds

var hanging_up_attempt = hanging_up_limit;

*/

window.avtPhoneCallRequest  = null;
window.uuid_bleg 		= "";
window.uuid_bleg_answered_time = 0;
window.countingDownAVTPhoneInterval = null;
window.session_check_time = 0;
window.countingDownReturningCustomerInterval = null;
window.returning_customer_check_time_max = 35;  //in seconds
window.returning_customer_check_time = window.returning_customer_check_time_max;

window.paymentProcessCompleted = false;
//if B_LEG hangs up then hangup a-leg
//number of tries before to hangup a-leg
var number_of_tries_to_hangup_aleg = 3;

window.PAYMENT_STATUS = "FAILED";

window.avt_country_code = "";
window.avt_calling_code = "";
window.avt_local_number = "";

window.CC_INPUT_NUMBER_OF_ATTEMPT = 0;

function tryNewCard(){    
    var temp = '<br><br><div id="guidedAVTScript">';
    temp += '<span id="AVT_SCRIPT">';
    temp += '<table style="width:750px; border-color:#CC0000; border-style:solid; border-width:0px; line-height:25px; font-family:helvetica; color:#320080; font-size:24px; font-weight:bold; vertical-align:top; border-collapse:collapse;" width="400">';
    temp += '<tbody>';
    temp += '<tr>';
    temp += '<td style="border-width:2px; border-color:#CC0000; border-style:solid; padding:20px; text-align:left; vertical-align:top; line-height:35px;" colspan="2">';
    temp += '<table style="width:100%;">';
    temp += '<tbody>';
    temp += '<tr>';
    temp += '<td>';
    temp += '<nobr><span style="font-family:verdana; font-size:30px; font-weight:bold; color:#999999;">YOU SAY:</span></nobr>';
    temp += '</td>';
    temp += '<td style="border-width:0px; border-color:#CC0000; border-style:solid; padding:0px; text-align:right; vertical-align:middle;"><span id="loading"></span>';
    temp += '</td>';
    temp += '</tr>';
    temp += '</tbody>';
    temp += '</table>';
    temp += '<hr>';
    temp += '<span id="OPERATOR_SAYS" style="line-height:42px;"></span>';
    temp += '</td>';
    temp += '</tr>';
    temp += '<tr>';
    temp += '<td style="border-width:2px; border-color:#CC0000; border-style:solid; padding:20px; text-align:left; vertical-align:top; line-height:35px;" colspan="2">';
    temp += '<nobr><span style="font-family:verdana; font-size:24px; font-weight:normal; color:#999999;">Customer Response Navigation:</span></nobr>';
    temp += '<hr>';
    temp += '<span id="CUSTOMER_SAYS"></span>';
    temp += '</td>';
    temp += '</tr>';
    temp += '</tbody>';
    temp += '</table>';
    temp += '</span>';
    temp += '</div>';
    
    $('callback_voice_td_6').innerHTML = "<span class='notUnderline' id='step4'>Step 3.</span>&nbsp;&nbsp;<span style='color:#BBBBBB;'>PCI Compliant Payment Process: </span><button class='submit_button_16px' style='color:#303080;' disabled>In progress...</button>" + temp;
    
    $('callback_voice_td_8').innerHTML = "";
    $('callback_voice_td_9').innerHTML = "";
    $('callback_voice_td_10').innerHTML = "";       

    if(window.PAYMENT_STATUS == "DECLINED" || window.PAYMENT_STATUS == "INSUFFICIENT"){
        avtGotoSlide('3');
    }
    else if(window.PAYMENT_STATUS == "INCOMPLETE" ){
        avtGotoSlide('12');
    }

    resetAVT();
}

function resetAVT(){
    //reset cc input attempts
    window.CC_INPUT_NUMBER_OF_ATTEMPT = 0;
    window.paymentProcessCompleted = false;

    window.countingDownReturningCustomerInterval = null;
}

function validateCustomerPhoneNumber(){        
	if( (window.avt_calling_code == "") || (window.avt_calling_code == null) ) {
		alert('Please Select Calling Code');
		return false;
	}        
        var number = document.getElementById("AVT_LOCAL_NUMBER").value;
        if(number == '' || number ==null){
            alert('Please enter phone number!');
            return false;
        } 
        window.avt_local_number = number;        
        return true;
}

function makePhoneCall() {
	resetCountingDown();
	window.uuid=generateUUID();
	window.uuid_sessions.push(window.uuid);
	window.uuid_bleg = '';
        window.paymentProcessCompleted = false;
        window.countingDownReturningCustomerInterval = null;
	// if try one gateway for 3 times, change it to another gateway
	if((window.calling_attempt%2) == 0 && window.calling_attempt != 0) window.gateway_attempt++;
        
        if(!validateCustomerPhoneNumber()) return;        

	// initialize the variables
	window.calling_attempt++;		
	window.uuid_check_time 	= window.uuid_check_limit;	
	window.is_ringing 		= false;
	window.is_finished 		= false;
	window.hangup_count 	= 0;
	
	// set the default stage of call me environment
	//$('callme').value = 'Calling...';
	$('callme').innerHTML = "<button  class='submit_button_16px' style='color:#888888;' onclick='' type='button' name='call' value='Call Me!' disabled>Please answer your phone when it rings...</button>";
	$('callme').disabled = true;
	//$('step1').className = "notUnderline";
	//$('step2').className = "underline";
	//$('step3').className = "notUnderline";
	$('callmeTxt1').innerHTML = "";
	$('callmeTxt2').innerHTML = "";
	$('callmeTxt3').innerHTML = "<input type='button' class='submit_button_16px' style='color:#FF6960;' id='cancelCalling' name='cancelCalling' value='Cancel / Hang-Up' onClick='cancelCalling();'>";
	
	//$('callmeTxt4').innerHTML = "";
	$('callmestatus').innerHTML = "";
	if(window.calling_attempt > 2) {
		$('attemptStatus').innerHTML = "<span style='font-family:helvetica; font-size:11px; font-weight:normal; color:#572386;'>Call Attempt: " + window.calling_attempt + " of 4</span>";
	} else {
		$('attemptStatus').innerHTML = "<span style='font-family:helvetica; font-size:11px; font-weight:normal; color:#572386;'>Call Attempt: " + window.calling_attempt + "</span>";
	}

	
	numberToDial = document.getElementById("numberToCall").innerHTML;
	numberToDial = numberToDial.replace(/\+/g, '');
        numberToDial = numberToDial.replace(/&nbsp;/g, '');


	var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
	
	var response = "";
	window.phoneCallRequest = new Ajax.Request(url + "?gateway=" + window.gateway_attempt + "&uuid=" + window.uuid + "&assisted_virtual_terminal=yes&known_business_number=" + numberToDial + "&avt_calling_code=" + window.avt_calling_code + "&avt_local_number=" + window.avt_local_number, {
		method: 'get',
		asynchronous: true,
		onLoading: function() {
			window.countingDownInterval = setInterval("countingDown()", 1000); 
		},
		onLoaded: function() {			
		},
		onSuccess: function(transport) {
			response = transport.responseText;
						
			if(response.indexOf("<response>") >= 0) {
				window.gateway_attempt = response.substring(response.indexOf("<gateway>")+9,response.indexOf("</gateway>"));
				response = response.substring(response.indexOf("<response>")+10,response.indexOf("</response>"));
				
				// start to check calling status from freeswitch				
				checkCallingStatus(window.uuid);

			// if not response normally, try to make another phone call
			} else if(response.indexOf("failed") >= 0) {
				changeToUnableToProcess();
				return;
			} else {
				//gateway_attempt++;
                                if(window.calling_attempt<5) makePhoneCall();
			}
			
		}
	});
	
}

function resetCountingDown() {
    if(window.countingDownInterval!=null){
        window.uuid_check_time 	= window.uuid_check_limit;
        clearInterval(window.countingDownInterval); 
    }
}

function countingDown() {

	if(
	($('callme').disabled != 'undefined') &&
	($('callme').disabled != null)
	) {
		if($('callme').disabled==true) {
			$('callmestatus').innerHTML = window.uuid_check_time + " seconds.";
			window.uuid_check_time--;
		
			// counting down to zero, wait for another try
			if(window.uuid_check_time==0) {	
				$('callmestatus').innerHTML = "Please hold, we are trying a new phone line.";	
				$('cancelCalling').disabled = true;
				clearInterval(window.countingDownInterval);
			}
		} else {
			clearInterval(window.countingDownInterval);                       
		}
	}
}

function countingDownForReturningCustomer() { 
        if($('returningCustomerCountDown')){
            $('returningCustomerCountDown').innerHTML = window.returning_customer_check_time + " seconds";
        }
        window.returning_customer_check_time--;

        // counting down to zero, enable reconnect button
        if(window.returning_customer_check_time==0) {
                if($('step5')) $('step5').className = "notUnderline";
                if($('step4')) $('step4').className = "notUnderline";
                $('callback_voice_td_6').innerHTML = "<span class='notUnderline' id='step4'>Step 3.</span>&nbsp;&nbsp;<span style='color:#BBBBBB;'>PCI Compliant Payment Process: </span><button class='submit_button_16px' style='color:#303080;' disabled>In progress...</button>";
                //reset timer
                window.returning_customer_check_time = window.returning_customer_check_time_max;
                $('callback_voice_td_9').innerHTML = tableStartCallReconnect;
                $('returning_customer').innerHTML = "";
                clearInterval(window.countingDownReturningCustomerInterval);
        }
}

function sessionTimer(action) {
    if(action == 'START'){
        window.session_check_time = 0; 
        if(window.countingDownAVTPhoneInterval!=null){ 
            clearInterval(window.countingDownAVTPhoneInterval);
        }
        window.countingDownAVTPhoneInterval = setInterval("countingDownAVTPhone()", 1000);
    }

    var sessionTimerResponse = "";
    var sessionTimerURL = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/e-terminal/e-terminal_logs.php'; ?>";

    var sessionTimerRequest = new Ajax.Request(sessionTimerURL + "?ACTION="+action+"_TIMER&UUID=" + window.uuid + "&UUID_BLEG=" + window.uuid_bleg + "&business_hash=<? echo $_SESSION['account']['hash'];?>" + "&memberid=<? echo $_SESSION['member']['memberid'];?>" + "&known_business_number=" + numberToDial + "&avt_calling_code=" + window.avt_calling_code + "&avt_local_number=" + window.avt_local_number + "&start_timestamp=" + window.uuid_bleg_answered_time, {
            method: 'get',
            onSuccess: function(transport) {
                    sessionTimerResponse = transport.responseText;
                    //console.log("sessionTimerResponse=", sessionTimerResponse);
            }
    });
}

function countingDownAVTPhone() {
    window.session_check_time++;
    if($('callAVTPhoneStatus')){        
        $('callAVTPhoneStatus').innerHTML = sec2hms(window.session_check_time);// parseInt($('callAVTPhoneStatus').innerHTML) + 1;
        
    }
}

function stopAVTPhoneRequest() {
    if(window.avtPhoneCallRequest != null)
        window.avtPhoneCallRequest.abort();
}

function cancelCalling() {
	if(window.phoneCallRequest != null)
		window.phoneCallRequest.abort();
	if(window.statusRequest != null)
		window.statusRequest.abort();
	if(window.checkFileRequest != null)
		window.checkFileRequest.abort();
	if(window.answeredRequest != null)
		window.answeredRequest.abort();

	if($('cancelCalling') != undefined) {
		$('cancelCalling').value = "Hanging-up...";	
		$('cancelCalling').disabled = true;
	}

	if($('cancelCallingConnected') != undefined) {
		$('cancelCallingConnected').value = "Hanging-up...";	
		$('cancelCallingConnected').disabled = true;
	}
	
	window.calling_attempt=0;

	dropCall(window.uuid);
	setTimeout("hangingUp()", 3000); 
}

function hangingUp() {
	tryAgainRedial();					
}

function dropCall(uuid) {
        //console.log("dropCall>window.uuid_bleg=", window.uuid_bleg);
        if(window.uuid_bleg != ""){            
            if(window.uuid == uuid) sessionTimer('STOP');
            else window.uuid_bleg = "";
        }
	var killResponse = "";
	var kill_url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
	
	var killRequest = new Ajax.Request(kill_url + "?command=kill&uuid=" + uuid, {
		method: 'get',
		onSuccess: function(transport) {
			killResponse = transport.responseText;
                        if(window.uuid_bleg != ''){
                            if(uuid != window.uuid_bleg){
                                //hangsup customer when operator hanged up
                                //dropCall(window.uuid_bleg);
                            }
                        }
		}
	});
}

function checkCallingStatus(uuid) {
    //console.log("checkCallingStatus");
	var statusResponse = "";	
	var check_status_url = '<? echo "https://" . $_SESSION["template"]["company"]["host_www"] . "/link_authorizations/freeswitch.auth"; ?>';

	// still don't answer the phone, try a new line
	if(window.uuid_check_time==0) {								
		if(window.calling_attempt == 4) {
			window.calling_attempt == 0;
			cancelCalling();
		} else {
			dropCall(uuid);
			setTimeout("makePhoneCall()", 5000);
		}		
		return;
	}

	window.statusRequest = new Ajax.Request(check_status_url + "?command=check&uuid=" + uuid, {
		method: 'get',		
		onSuccess: function(transport) {
			statusResponse = transport.responseText;
		
			if(statusResponse.indexOf("<Answer-State>") >= 0) {
				statusResponse = statusResponse.substring(statusResponse.indexOf("<Answer-State>")+14,statusResponse.indexOf("</Answer-State>"));				

				// if the status is ealry, set the is_ringing variable
				if(statusResponse.trim()!="" && !window.is_ringing)
		  			window.is_ringing = true;

		  		// if the phone has been hangup too soon
		  		if(window.is_ringing && statusResponse.trim()=="")
		  		{
		  			clearInterval(window.countingDownInterval);
		  			dropCall(window.uuid);
		  			changeToUnableToProcess();
		  			window.calling_attempt=0;
		  			return;
		  		}

		  		// if the phone has been answered
				if(statusResponse.trim()=="answered")
		  		{
		  			clearInterval(countingDownInterval);
		  			$('callmestatus').innerHTML = "";

		  			$('step1').className = "notUnderline";
		  			
		  			$('callback_voice_td_4').innerHTML = "";
		  			
					$('callback_voice_td_3').innerHTML = "<nobr><span class='notUnderline' id='step2'>Step 1.</span>&nbsp;&nbsp;<span style='color:#BBBBBB;'>You are now connected to the <b><? echo  $_SESSION['template']['company']['domain']; ?></b></span></nobr>";

					var step_4B = "";
					step_4B = step_4B+"<td class='voice_td_4' colspan='2' align='left' style='font-size:12px; font-family:verdana;arial; font-weight:normal; color:#BBBBBB; height:auto; vertical-align:top; padding-top:6px; padding-bottom:5px; line-height:34px;'>";
					step_4B = step_4B+"<span style='font-size:40px; font-family:verdana,arial; font-weight:bold; color:#CC0000; vertical-aign:top; padding-top:0px;'>";
					step_4B = step_4B+"<i>";
					step_4B = step_4B+"e";
					step_4B = step_4B+"</i>";
					step_4B = step_4B+"</span>"
					step_4B = step_4B+"<span style='font-size:34px; font-family:verdana,arial; font-weight:bold; color:#CCCCCC; vertical-aign:top; padding-top:0px;'>";
					step_4B = step_4B+"-TERMINAL.NET";
					
					step_4B = step_4B+"<sup><span style='font-size:14px; font-weight:normal;'>&nbsp;&#8480;</span></sup>";
					step_4B = step_4B+"</span>";
					step_4B = step_4B+"<br>";
					step_4B = step_4B+"<span style='font-size:16px; font-family:arial; font-weight:nomral; color:#CCCCCC; vertical-aign:top; padding-top:0px;'>";
					step_4B = step_4B+"(The <span style='font-size:120%;'><i><b>\"e\"</b></i></span> is for <span style='font-size:115%;'><b><i>enhanced</b></i></span> !!)";
					step_4B = step_4B+"</span>";
					step_4B = step_4B+"</td>";
					$('callback_voice_td_4B').innerHTML = step_4B;
					//$('callback_voice_td_4B').innerHTML = "<span style='font-size:34px; font-family:verdana,arial; font-weight:bold; color:#CCCCCC; vertical-aign:top; padding-top:0px;'><i>Assisted Virtual Terminal</i><sup>&trade;</sup></span>";

					
					//$('callback_voice_td_5').innerHTML = "<span class='notUnderline' id='step2'>Step 2.</span>&nbsp;&nbsp;<span style='color:#BBBBBB;'>You are now connected to the &nbsp;<? echo echo_bangk($font_size="16px",$reg_size="12px"); ?> . . .</span>";
					
					//$('callback_voice_td_6').innerHTML = "<span class='underline' id='step3' style=lineheight:35px;'><b>Step 3.</b></span>&nbsp;&nbsp;Now calling your customer...";
                                        
                                        $('callback_voice_td_5').innerHTML = "<span class='underline' id='step3' style=line-height:40px;'><b>Step 2.</span>&nbsp;&nbsp;<u>Now calling</u> your customer!</b><br><center><span style='color:#0000AA; font-size:16px;'>Please <u>be ready</u> to communicate when your customer answers <u>this call</u>...</span></center><br>";
					                                         
                    checkAVTPhone(uuid);    
		  			checkAnsweredStatus(uuid);                                        
		  			return;
		  		}

		  		checkCallingStatus(uuid);
			} else {
				document.getElementById('tdMain').innerHTML = statusResponse;
				clearTimeout("checkVauthSession");
			}
		}
	});
}

function changeToUnableToProcess() {
        
        var avt_receipt_url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/e-terminal/e-terminal_receipt.php'; ?>?PAYMENT_STATUS=" + window.PAYMENT_STATUS;

        var avtReceipt = new Ajax.Request(avt_receipt_url, {
                method: 'get',
                onSuccess: function(transport) {
                        $('tdMain').innerHTML = transport.responseText;
                }
        });        
}

function dropAllCall(url) {
	if(window.phoneCallRequest != null)
		window.phoneCallRequest.abort();
	if(window.statusRequest != null)
		window.statusRequest.abort();
	if(window.checkFileRequest != null)
		window.checkFileRequest.abort();
	if(window.answeredRequest != null)
		window.answeredRequest.abort();

	var killResponse = "";
	var kill_url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
	var my_uuids = "";

	for(i=0; i<window.uuid_sessions.length; i++) {
		my_uuids += window.uuid_sessions[i] + ",";
	}
	my_uuids = my_uuids.substring(0,my_uuids.length-1);

	var killRequest = new Ajax.Request(kill_url + "?command=killall&uuids=" + my_uuids, {
		method: 'get',
		onSuccess: function(transport) {
			killResponse = transport.responseText;
			if(url != "#") {
				top.window.location.replace(url);
			}			
		}
	});
}

function hangupPhoneCall(e) {    
    $(e).innerHTML = "Hanging-up...";    
    $(e).disabled = true;    
    dropCall(window.uuid);
}

function displayGuidedAVTScript(e){
    //$(e).disabled = true;  

    $('callback_voice_td_6').innerHTML = "<span class='underline' id='step4'>Step 3.</span>&nbsp;&nbsp;PCI Compliant Payment Process: <button  class='submit_button_14px' style='color:#009900' onclick='' type='button' name='call' value='Call Record' disabled>Launched!</button><br><br><div id='guidedAVTScript'></div>";

    avtCallRecord('start');

    //defind in header.js, to reset slide number
    avtScriptSlideNumberResetAJAX();
    
    var guided_avt_url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/e-terminal/e-terminal_script.php'; ?>";

    var guidedAVT = new Ajax.Request(guided_avt_url, {
            method: 'get',
            onSuccess: function(transport) {
                    $('guidedAVTScript').innerHTML = transport.responseText;
            }
    });
}

function checkAnsweredStatus(uuid) {    
    //console.log("checkAnsweredStatus");
	var answeredResponse = "";	
	var check_answered_status_url = '<? echo "https://" . $_SESSION["template"]["company"]["host_www"] . "/link_authorizations/freeswitch.auth"; ?>';

	window.answeredRequest = new Ajax.Request(check_answered_status_url + "?command=check&uuid=" + uuid, {
		method: 'get',		
		onSuccess: function(transport) {
			statusResponse = transport.responseText;
		
			if(statusResponse.indexOf("<Answer-State>") >= 0) {
				statusResponse = statusResponse.substring(statusResponse.indexOf("<Answer-State>")+14,statusResponse.indexOf("</Answer-State>"));				

				//$(document.body).insert(statusResponse);

				if(window.is_finished == false) {
			  		if(statusResponse.trim()=="answered")
			  		{
			  			checkAnsweredStatus(uuid);
			  			return;
			  		} else {
			  			if(window.hangup_count < 1){
			  				window.hangup_count++;
			  				checkAnsweredStatus(uuid);
			  				return;
			  			} else {
			  				if(window.phoneCallRequest != null)
								window.phoneCallRequest.abort();
							if(window.statusRequest != null)
								window.statusRequest.abort();
							if(window.checkFileRequest != null)
								window.checkFileRequest.abort();
							if(window.answeredRequest != null)
								window.answeredRequest.abort();
                                                        if(window.avtPhoneCallRequest != null)
								window.avtPhoneCallRequest.abort();
                                                        if(window.countingDownAVTPhoneInterval != null)
                                                            clearInterval(window.countingDownAVTPhoneInterval);
							dropCall(uuid);
							changeToUnableToProcess();
				  			window.calling_attempt=0;
				  			return;
			  			}			  			
			  		}
		  		}

			} else {
				document.getElementById('tdMain').innerHTML = statusResponse;
				clearTimeout("checkVauthSession");
			}
		}
	});
}

function sec2hms(seconds){

    if(seconds=== undefined||seconds==0||seconds === null){return ''};
    //seconds is seconds, NOT milliseconds
    var se=seconds % 60; //the remainder after div by 60
    seconds = Math.floor(seconds/60);
    var mi=seconds % 60; //the remainder after div by 60
    seconds = Math.floor(seconds/60);
    var hr = seconds % 24; //the remainder after div by 24
    var dy = Math.floor(seconds/24);
  
    hr = hr>0?(hr<10?"0"+hr:hr) + ":":"";
    mi = mi<10?"0"+mi:mi;
    se = se<10?"0"+se:se;
    dy = dy>0?dy+"d ":"";
    return dy+hr+mi+":"+se;
}

function updateCreditCardStatus(statusResponse){
    var cc_no_of_attempts = statusResponse.substring(statusResponse.indexOf("<variable_AVT_CC_NO_OF_ATTEMPT>")+31,statusResponse.indexOf("</variable_AVT_CC_NO_OF_ATTEMPT>"));
    var cc_attempt_status = statusResponse.substring(statusResponse.indexOf("<variable_AVT_CC_ATTEMPT_STATUS>")+32,statusResponse.indexOf("</variable_AVT_CC_ATTEMPT_STATUS>"));                                      
    //do not process for the same attempt
    if(cc_no_of_attempts > window.CC_INPUT_NUMBER_OF_ATTEMPT){
        window.CC_INPUT_NUMBER_OF_ATTEMPT = cc_no_of_attempts;
        if(cc_no_of_attempts == 1){            
            if(cc_attempt_status=="SUCCESS") $('cc').innerHTML = ": Successfully Registered...";
            else $('cc').innerHTML = " Attempt#" + cc_no_of_attempts + ": " + cc_attempt_status;
        }
        else if(cc_no_of_attempts>1){
            var attemptNo = '<li class="cc_attemtps_no">Credit Card Input STATUS Attempt#'+cc_no_of_attempts+': '+cc_attempt_status+'</li>';
            $('finalPaymentStatus').insert({before:attemptNo});
        }
    }
}

function checkAVTPhone(uuid) {
    stopAVTPhoneRequest();
    //console.log("checkAVTPhone is called");
    if(window.uuid_bleg != '') uuid = window.uuid_bleg;
    var statusResponse = "";
    var url = '<? echo "https://" . $_SESSION["template"]["company"]["host_www"] . "/link_authorizations/freeswitch.auth"; ?>';

	window.avtPhoneCallRequest = new Ajax.Request(url + "?avt_phone_status=yes&uuid=" + uuid, {
		method: 'get',		
		onSuccess: function(transport) {
			statusResponse = transport.responseText;		
			//console.log('checkAVTPhone=' + statusResponse);
                        //check if second phone answered and get bleg uuid 
                        if(window.uuid_bleg == ''){
                            if(statusResponse.indexOf("<variable_originate_disposition>") >= 0) {
                                    var statusResponseAVTPhone = statusResponse.substring(statusResponse.indexOf("<variable_originate_disposition>")+32,statusResponse.indexOf("</variable_originate_disposition>"));
                                    //console.log('AVT phone status=' + statusResponseAVTPhone);
                                    if(statusResponseAVTPhone == "SUCCESS"){
                                        //collect AVT Phone UUID
                                        window.uuid_bleg = statusResponse.substring(statusResponse.indexOf("<variable_bridge_uuid>")+22,statusResponse.indexOf("</variable_bridge_uuid>"));                                        
                                        window.uuid_bleg_answered_time = statusResponse.substring(statusResponse.indexOf("<Caller-Channel-Answered-Time>")+30,statusResponse.indexOf("</Caller-Channel-Answered-Time>"));
                                        //$('callback_voice_td_6').innerHTML = "<span class='notUnderline' id='step2'>Step 3.</span>&nbsp;&nbsp;Customer answered... <span id='callAVTPhoneStatus' style='font-size:120%;'></span> ago.";
                                        $('callback_voice_td_5').innerHTML = "<span class='notUnderline' id='step2'>Step 2.</span>&nbsp;&nbsp;<span style='color:#BBBBBB;'>You are now connected to your customer...</span> <span id='callAVTPhoneStatus' style='font-size:120%;'>00:01</span> <span style='color:#BBBBBB;'>ago.</span>";
                                        
                                        sessionTimer('START');
                                        //$('callback_voice_td_7').innerHTML = tableStartCallRecord;
                                        $('callback_voice_td_6').innerHTML = tableStartCallRecord;
                                        
                                    }
                                    else{
                                        //checkAVTPhone(uuid);
                                    }
                            } 
                            else{
                                //checkAVTPhone(uuid);
                            }
                        } 
                        else { 
                            var avtPhoneAnsweredState = '';
                            if(statusResponse.indexOf("<Answer-State>") >= 0) {
                                if(!window.paymentProcessCompleted){
                                    avtPhoneAnsweredState = statusResponse.substring(statusResponse.indexOf("<Answer-State>")+14,statusResponse.indexOf("</Answer-State>"));
                                    //console.log("avtPhoneAnsweredState=", avtPhoneAnsweredState);
                                    //if(statusResponse.trim()=="answered"){
                                        if(statusResponse.indexOf("<variable_AVT_PAYMENT_STATUS>") >= 0){
                                            var paymentResponse = statusResponse.substring(statusResponse.indexOf("<variable_AVT_PAYMENT_STATUS>")+29,statusResponse.indexOf("</variable_AVT_PAYMENT_STATUS>"));
                                            //console.log('AVT Payment Status=' + paymentResponse);
                                            
                                            
                                            if(paymentResponse == "INTRODUCTION_COMPLETED"){
                                                $('paymentIntroduction').innerHTML = ": Completed!";                                            
                                            }
                                            else if(paymentResponse == "CREDIT_CARD_ATTEMPT"){
                                                //if not updated already
                                                $('paymentIntroduction').innerHTML = ": Completed!";
                                                updateCreditCardStatus(statusResponse);
                                                
                                            }
                                            else if(paymentResponse == "CREDIT_CARD_ENTERED"){
                                                //$('cc').innerHTML = ": Successfully Registered...";                                            
                                            }
                                            else if(paymentResponse == "APPROVED" || paymentResponse == "DECLINED" || paymentResponse == "INSUFFICIENT" || paymentResponse == "INCOMPLETE"){
                                                    window.PAYMENT_STATUS = paymentResponse;
                                                    if(paymentResponse == "DECLINED" || paymentResponse == "INSUFFICIENT" || paymentResponse == "INCOMPLETE"){
                                                        //INCOMPLETE
                                                        window.returning_customer_check_time_max = 20; //seconds
                                                        if(paymentResponse == "INSUFFICIENT") window.returning_customer_check_time_max = 37;
                                                        else if(paymentResponse == "DECLINED") window.returning_customer_check_time_max = 32;
                                                        window.returning_customer_check_time = window.returning_customer_check_time_max;
                                                    }
                                                    window.paymentProcessCompleted = true;
                                                    //$('step5').className = "notUnderline";
                                                    
                                                    updateCreditCardStatus(statusResponse);
                                                    $('PaymentStatus').innerHTML = ": " + paymentResponse;
                                        
                                                    if(window.countingDownReturningCustomerInterval == null){
                                                        $('returning_customer').innerHTML = "Returning customer to you in <span id='returningCustomerCountDown'>"+window.returning_customer_check_time_max+" seconds</span>...";  
                                                        window.countingDownReturningCustomerInterval = setInterval("countingDownForReturningCustomer()", 1000);
                                                    }
                                            }
                                            else if(paymentResponse == "COMPLETE"){
                                                //paymentProcessCompleted = true;
                                                //$('step5').className = "notUnderline";
                                            }
                                        }
                                    //}
                                }
                            }
                            else{
                                //console.log("B-LEG hanged up("+number_of_tries_to_hangup_aleg+")");
                                number_of_tries_to_hangup_aleg--;
                                if(number_of_tries_to_hangup_aleg<=1){
                                    number_of_tries_to_hangup_aleg= 3;                                    
                                    dropCall(window.uuid);
                                }
                                else{
                                    checkAVTPhone(uuid);
                                }
                            }                            
                        }

                        if(statusResponse.indexOf("<response>") >= 0){                            
                                checkAVTPhone(uuid);                            
                        }
		}
	});
}

function avtCallRecord(action) {
	stopAVTPhoneRequest();		
        var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/goAJAX.b!'; ?>";
	
	var response = "";
	window.avtPhoneCallRequest = new Ajax.Request(url + "?avt_call_record="+action+"&uuid=" + window.uuid, {
		method: 'get',
		asynchronous: true,
		onLoading: function() {
			//$('callback_voice_td_7').innerHTML = "<span class='underline' id='step4'>Step 4.</span>&nbsp;&nbsp;<button  class='' style='' onclick='' type='button' name='call' value='Call Record' disabled>Starting Call Recording...</button>";
		},
		onLoaded: function() {			
		},
		onSuccess: function(transport) {
			response = transport.responseText;
                        //console.log(response); 
                        //ajax to freeswitch.auth
                        if(response == 'success'){
                            url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
                            response = "";
                            window.avtPhoneCallRequest = new Ajax.Request(url + "?uuid=" + window.uuid_bleg, {
                                    method: 'get',
                                    asynchronous: true,
                                    onLoading: function() {

                                    },
                                    onLoaded: function() {			
                                    },
                                    onSuccess: function(transport) {
                                            response = transport.responseText;
                                            //console.log(response); 
                                            if(response.indexOf("<response>") >= 0) {
                                                    response = response.substring(response.indexOf("<response>")+10,response.indexOf("</response>"));
                                                    //console.log(response); 
                                                    if(action == 'start'){
                                                        //document.getElementById("avtCallRecord").innerHTML = tableStopCallRecord;
                                                        //$('callback_voice_td_7').innerHTML = "<span class='notUnderline' id='step4'>Step 4.</span>&nbsp;&nbsp;<input type='button' disabled='true' name='call' value='Call Recording Started!'>";
                                    
                                                        //$('callback_voice_td_8').innerHTML = tableStartPayment;
                                                    }
                                                    else if(action == 'stop'){
                                                        //document.getElementById("avtCallRecord").innerHTML = tableStartCallRecord;
                                                    }
                                            }
                                            else{
                                                //alert('Call '+ action + ' failed.');
                                            }
                                            checkAVTPhone(uuid);
                                    },
                                    onError: function(transport) {
                                            checkAVTPhone(uuid);
                                    }
                            });
                        }
		},
		onError: function(transport) {
                        response = transport.responseText;
                        //console.log(response);
		}
	});        
}

function avtPaymentProcess(){
    //$('callback_voice_td_8').innerHTML = tableStartPayment;
    //$('guidedAVTScript').hide();
    //$('callback_voice_td_6').innerHTML = "<span class='underline' id='step4'>Step 3.</span>&nbsp;&nbsp;<span style='color:#BBBBBB;'>PCI Compliant Payment Process: </span><button class='submit_button_16px' disabled>In progress...</button>";
    
    $('callback_voice_td_6').innerHTML = "<span class='underline' id='step4'>Step 3.</span>&nbsp;&nbsp;PCI Compliant Payment Process: <button class='submit_button_16px' disabled>In progress...</button>";
    //$('step4').className = "notUnderline";
    setAvtCustomerValues();    
    
}

function setAvtCustomerValues(){
        stopAVTPhoneRequest();		
        var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
    var response = "";
    window.avtPhoneCallRequest = new Ajax.Request(url + "?set_avt_customer_values=yes&uuid=" + window.uuid_bleg, {
            method: 'get',
            asynchronous: true,
            onLoading: function() {
                    var display_to_update = "";
			//display_to_update = display_to_update + "<span class='underline' id='step5'>Step 4.</span>";
			//display_to_update = display_to_update + "&nbsp;&nbsp;";
			//display_to_update = display_to_update + "<button  class='' style='' onclick='' type='button' name='call' value='Payment Process' disabled>";
			//display_to_update = display_to_update + "PCI Compliant Payment Process...";
			//display_to_update = display_to_update + "</button>";
			display_to_update = display_to_update + "<div id='paymentProcessStatusBlock'>";
			//display_to_update = display_to_update + "<div id='inprogress'>";
			//display_to_update = display_to_update + "<br>";
			//display_to_update = display_to_update + "<span style='font-weight:normal; font-size:18px; font-family:verdana;arial;'>";
			//display_to_update = display_to_update + "In progress...";
			//display_to_update = display_to_update + "</div>";
			display_to_update = display_to_update + "<div>";
			
			display_to_update = display_to_update + "<span style='font-size:22px; color:#444444;'>";
			display_to_update = display_to_update + "<ul>";
            
                        
            display_to_update = display_to_update + "<li>";
			display_to_update = display_to_update + "<u>RECORDED</u> Card-Holder Authorization";
			display_to_update = display_to_update + "<span id='recordedCustomerDetails'><span style='color:#009900;'><i><b> : Completed!</b></i></span></span>";
			display_to_update = display_to_update + "</li>";
            display_to_update = display_to_update + "<li>";
			display_to_update = display_to_update + "Credit Card Input INSTRUCTIONS";
			display_to_update = display_to_update + " <span style='color:#009900;'><i><b><span id='paymentIntroduction'></span></b></i></span>";
			display_to_update = display_to_update + "</li>";
			display_to_update = display_to_update + "<li>";
			display_to_update = display_to_update + "Credit Card Input STATUS";
			display_to_update = display_to_update + "<span id='cc'></span>";
			display_to_update = display_to_update + "</li>";
			display_to_update = display_to_update + "<li id='finalPaymentStatus'>";
			display_to_update = display_to_update + "FINAL Payment Status";
			display_to_update = display_to_update + "<span id='PaymentStatus'></span>";
			display_to_update = display_to_update + "</li>";
			display_to_update = display_to_update + "</ul>";
			display_to_update = display_to_update + "</span>";
			
			display_to_update = display_to_update + "</div>";
			display_to_update = display_to_update + "<center><span style='font-size:18px; font-weight:bold; color:#cc0000;'><div id='returning_customer'></div></span></center>";
			display_to_update = display_to_update + "</div>";
			$('callback_voice_td_8').innerHTML = display_to_update;
            },
            onLoaded: function() {			
            },
            onSuccess: function(transport) {
                    response = transport.responseText;
                    //console.log(response); 
                    
                    startPaymentProcess();                 
            },
            onError: function(transport) {
                    
            }
    });
}

function startPaymentProcess() {
	stopAVTPhoneRequest();		
        var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/goAJAX.b!'; ?>";
	
	var response = "";
	window.avtPhoneCallRequest = new Ajax.Request(url + "?avt_start_payment_process=yes&uuid=" + window.uuid, {
		method: 'get',
		asynchronous: true,
		onLoading: function() {
			
		},
		onLoaded: function() {			
		},
		onSuccess: function(transport) {
			response = transport.responseText;
                        //console.log(response); 
                        //ajax to freeswitch.auth
                        if(response == 'success'){
                            url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
                            response = "";
                            window.avtPhoneCallRequest = new Ajax.Request(url + "?uuid=" + window.uuid, {
                                    method: 'get',
                                    asynchronous: true,
                                    onLoading: function() {

                                    },
                                    onLoaded: function() {			
                                    },
                                    onSuccess: function(transport) {
                                            response = transport.responseText;
                                            //console.log(response); 
                                            if(response.indexOf("<response>") >= 0) {
                                                //$('callback_voice_td_8').innerHTML = "<span class='underline' id='step5'>Step 4.</span>&nbsp;&nbsp;<input type='button' disabled='true' name='call' value='Payment process started!'><span id='paymentProcessingBlock'><br> (Payment is being processed by your customer, please wait while the button below is not active!)</span>";                                            
                                            }
                                            else{
                                                //alert('Payment processing ailed.');
                                            }
                                            checkAVTPhone(uuid);
                                    },
                                    onError: function(transport) {
                                            checkAVTPhone(uuid);
                                    }
                            });
                        }
		},
		onError: function(transport) {
                        response = transport.responseText;
                        //console.log(response);
		}
	});        
}


function avtCallReconnect(action) {	
        stopAVTPhoneRequest();
        var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/goAJAX.b!'; ?>";
	
	var response = "";
	window.avtPhoneCallRequest = new Ajax.Request(url + "?avt_call_park="+action+"&uuid=" + window.uuid + "&bleg_uuid=" + window.uuid_bleg, {
		method: 'get',
		asynchronous: true,
		onLoading: function() {
			$('callback_voice_td_9').innerHTML = "<span class='underline' id='step6'>STEP 4.</span>&nbsp;&nbsp;<button  class='submit_button_14px' style='color:#000088;' onclick='' type='button' name='call' value='Reconnecting' disabled>Reconnecting...</button>";
		},
		onLoaded: function() {			
		},
		onSuccess: function(transport) {
			response = transport.responseText;
                        //console.log(response); 
                        //ajax to freeswitch.auth
                        if(response == 'success'){
                            url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/freeswitch.auth'; ?>";
                            response = "";
                            window.avtPhoneCallRequest = new Ajax.Request(url + "?uuid=" + window.uuid, {
                                    method: 'get',
                                    asynchronous: true,
                                    onLoading: function() {

                                    },
                                    onLoaded: function() {			
                                    },
                                    onSuccess: function(transport) {
                                            response = transport.responseText;
                                            //console.log(response); 
                                            if(response.indexOf("<response>") >= 0) {
                                                    response = response.substring(response.indexOf("<response>")+10,response.indexOf("</response>"));
                                                    //console.log(response); 
                                                    if(action == 'start'){
                                                        
                                                    }                                                    
                                                    else if(action == 'unpark'){
                                                        //$('paymentProcessStatusBlock').innerHTML = "Completed & APPROVED";
                                                        $('callback_voice_td_9').innerHTML = "<span class='notUnderline' id='step6'>STEP 4.</span>&nbsp;&nbsp;<button class='submit_button_14px' style='color:#AAAAAA;' type='button' disabled='true' name='reconnected' value='RECONNECTED!'>RECONNECTED!</button>";
                                                        
                                                        if(window.PAYMENT_STATUS == "DECLINED" || window.PAYMENT_STATUS == "INSUFFICIENT" || window.PAYMENT_STATUS == "INCOMPLETE" ) {
	                                                        $('callback_voice_td_10').innerHTML = tableCallHangup_INSUFFICIENT;                                                                  
                                                        } else {
	                                                        $('callback_voice_td_10').innerHTML = tableCallHangup;  
                                                        }
                                                                                   
                                                        //$('callback_voice_td_10').innerHTML = tableCallHangup;                  
                                                    }
                                            }
                                            else{
                                                alert('Call Connection Failure: Please Tell Customer Supprt ERR# 57tt67g');
                                            }
                                    }
                            });
                        }
		},
		onError: function(transport) {
                        response = transport.responseText;
                        //console.log(response);
		}
	});        
}

function editPhoneNumber() {

	//alert(2);

	//document.getElementById("tdMain").innerHTML = "<div align='center'><img src='<? echo image("local","loading.gif"); ?>'></div>";

	
	//var url = "authorization_retry.auth";
	//var url = "authorization_declined.auth";
	//var url = "registration_duplicate.auth";
	//var url = "registration_approved.auth";
	var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/link_authorizations/update_phone_number.auth'; ?>";
	new Ajax.Request(url, {
		method: 'post',
		onSuccess: function(transport) {
                        //console.log(transport.responseText);
			if (transport.responseText != null) {
				//document.getElementById("tdMain").innerHTML = transport.responseText;
				//document.getElementById("wholePage").innerHTML = transport.responseText;
                                showHideEditRegisterNumberBlock('show'); 
                                $('editRegisteredNumber').innerHTML = transport.responseText;                                
			}
		}
	});


}
 
function showHideEditRegisterNumberBlock(action){
    if(action == 'show'){
        $('registeredNumber').hide();
        $('editRegisteredNumber').show();
    }
    else{
        $('registeredNumber').show();
        $('editRegisteredNumber').hide();
    }
}

function cancelEdit() {
        showHideEditRegisterNumberBlock();
	//document.getElementById("tdMain").innerHTML = tableSteps;
	//if(newPhoneNumber != undefined) document.getElementById('numberToCall').innerHTML = newPhoneNumber; // this updates the displayed phone number to dial if set
}

function tryAgainRedial() {    
	document.getElementById("tdMain").innerHTML = tableSteps; 
        setAVTNumber(); 
        resetAVT();
}

function setAVTNumber(){
    $('AVT_COUNTRY_ISO3').setValue(window.avt_country_code);
    $('AVT_COUNTRY_CALLING_CODE').innerHTML =  "+" + window.avt_calling_code;
    $('AVT_LOCAL_NUMBER').setValue(window.avt_local_number);
}

function onChangeCountryAVT(field) {
	window.avt_country_code = field.options[field.selectedIndex].value;	
	var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/goAJAX.b!'; ?>?avt_country_iso3=" + field.options[field.selectedIndex].value;		
	var response = "";
	new Ajax.Request(url, {
		method: "get",
		onSuccess: function(transport) {
			response = transport.responseText.trim();
                        //console.log("onChangeCountryAVT=", response); 
                        window.avt_calling_code = response;
                        $('AVT_COUNTRY_CALLING_CODE').innerHTML = "+" + window.avt_calling_code;
                        
		}   
	});
	
}



function onChangeCountryCode(field) {
		
	var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/goAJAX.b!'; ?>?avt_calling_code=" + field.options[field.selectedIndex].text;		
	var response = "";
	new Ajax.Request(url, {
		method: "get",
		onSuccess: function(transport) {
			response = transport.responseText.trim();
                        //console.log("changeCountryCode=", response);
                        
		}   
	});
	
}

function onChangeLocalNumber(field) {
		
	var url = "<? echo 'https://' . $_SESSION['template']['company']['host_www'] . '/goAJAX.b!'; ?>?avt_local_number=" + field.value;		
	var response = "";
	new Ajax.Request(url, {
		method: "get",
		onSuccess: function(transport) {
			response = transport.responseText.trim();
                        //console.log("changeCountryCode=", response);
                        
		}   
	});
	
}

function savePhoneNumber() {

	//alert(1);

	
	var oldNumber = document.getElementById("oldNumber").value;
	var newNumber = document.getElementById("newNumber").value;
	var newCallingCode = document.getElementById("callingCode").innerHTML;
	var newCountryCodeISO2 = document.getElementById("countryCodeISO2").value;
	
	
	//alert("oldNumber: " + oldNumber);
	//alert("newNumber: " + newNumber);
	//alert("newCallingCode: " + newCallingCode);
	//alert("newCountryCodeISO2: " + newCountryCodeISO2);
	
	//alert("newCountryCodeISO2: " + document.getElementById("countryCodeISO2").value);

	
	//var newNumber = document.getElementById('areaCode').innerHTML.trim() + document.getElementById('newNumber').value;
	
	// clean vars
	newCallingCode = newCallingCode.trim();
	newCallingCode = newCallingCode.replace(/&nbsp;/g, '');
	newCallingCode = newCallingCode.replace(/\+/g, '');	
	//clean vars
	newNumber = newNumber.replace(/&nbsp;/g, '');
	newNumber = newNumber.replace(/\n/g, '');
	newNumber = newNumber.replace(/\./g, '');
	newNumber = newNumber.replace(/\-/g, '');
	newNumber = newNumber.trim();
	
	//var newPhoneNumber = document.getElementById('callingCode').innerHTML.trim() + document.getElementById('newNumber').value;
	var newPhoneNumber = newCallingCode + " " + newNumber;
	
	//alert(newPhoneNumber);
	
	
	
	var url = "https://<? echo $_SESSION['template']['company']['host_www']; ?>/link_authorizations/save_phone_number.auth?newPhoneNumber=" + newNumber + "&newCallingCode=" + newCallingCode + "&newCountryCodeISO2=" + newCountryCodeISO2;
	
	//alert('url: ' + url);
	
	

	var updateAuthorizationSession = new Ajax.Request(url, {
		method: 'post',
		// asynchronous as we have to wait for the response to get the UUID, then make the second call...
		asynchronous: true,
		onSuccess: function(transport) {
			//alert("666");
		}
	});
	
	//alert("updateAuthorizationSession: " + updateAuthorizationSession);
	
	cancelEdit();
	document.getElementById('numberToCall').innerHTML = newPhoneNumber;
	
	
	tableSteps = document.getElementById("tdMain").innerHTML;
	cancelEdit();
}




function updateAreaCode(obj) {
	var url = '../www/get_country_code.php?country_name='+obj.options[obj.selectedIndex].text;
	new Ajax.Request( url , {
		method: 'post',
		onSuccess: function(transport) {
			document.getElementById("areaCode").innerHTML = '+' + transport.responseText + '&nbsp;';
			document.getElementById("areaCodeExample").innerHTML = '+' + transport.responseText;
		}
	});
}

window.onload = loadCallTable


function loadCallTable() {
	document.getElementById("tdMain").innerHTML = "<div align='center'><img src='https://<? echo $_SESSION['template']['company']['host_images']; ?>/loading.gif'></div>";
	document.getElementById("tdMain").innerHTML = tableSteps;        
}



function startNewCallSession() {
        var url = "https://<? echo $_SESSION['template']['company']['host_www']; ?>/e-terminal/e-terminal.b!";
	window.location.replace(url);	
	
}




</script>
