<?


###	LOGGING VARS:#############################################
$send_administrative_cc = "shea.writer@gmail.com"; # coment-out to turn off

#echo $funtion_test = "got here";

#########################################################
#########################################################
#########################################################



function logf($filename,$string) {
	//echo "$string<br><br>";
 
 	if((is_array($string)) ||	(is_object($string))) {
 		$outstring = date("Y-m-d H:i:s",time()) . ": " . print(print_r($string)) . "\n\n";
 	} else {
 		$outstring = date("Y-m-d H:i:s",time()) . ": $string\n\n";
 	}
	$fp = fopen($filename,"a");
	if($fp) {
		fwrite($fp,$outstring);
		fclose($fp);
	}
}




function flog($filename,$string) {
 
	$outstring = date("Y-m-d H:i:s",time()) . ": $string\n\n";
	$fp = fopen($filename,"a");
	if($fp) {
		fwrite($fp,$outstring);
		fclose($fp);
	}
}


function log_traffic_stats() {
	
	//$MML2_results = MML2($_SERVER['REMOTE_ADDR']);
	
	//test("ip_results",$ip_results);
	//test("geobytes_results",$geobytes_results);
	//exit;
	
	global $master_config_traffic_stats;
	//test("_SERVER['HTTP_HOST']",$_SERVER['HTTP_HOST']);
	if(empty($_SESSION['log_traffic_stats']['counter'])) {
		$_SESSION['log_traffic_stats']['counter'] = 0;
	} else {
		$_SESSION['log_traffic_stats']['counter'] = $_SESSION['log_traffic_stats']['counter'] + 1;
	}
	$tmp_counter = $_SESSION['log_traffic_stats']['counter'];
	$_SESSION['log_traffic_stats']['FULL_URL'][$tmp_counter] = $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];
	
	if(
	($master_config_traffic_stats == "ON") &&
	($already_set != true) &&
	(!stristr($_SERVER['REMOTE_ADDR'],"67.29.138")) && /*system*/
	(!array_search($_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'],$_SESSION['log_traffic_stats']['FULL_URL']))
	) {
		
		$geobytes_results = geobytes($_SERVER['REMOTE_ADDR']);
		$already_set = true;
		$tmp_sql = "INSERT INTO `traffic_stats`
					(
					`traffic_stats_id`, 
					`domain`, 
					`filename`, 
					`ip`, 
					`country_iso3`, 
					`city`, 
					`HTTP_USER_AGENT`, 
					`datetime`
					) VALUES (
					'". $traffic_stats_id ."',
					'". $_SERVER['HTTP_HOST'] ."',
					'". $_SERVER['SCRIPT_NAME'] ."',
					'". $_SERVER['REMOTE_ADDR'] ."',
					'". $geobytes_results['iso3'] ."',
					'". $geobytes_results['city'] ."',
					'". $_SERVER['HTTP_USER_AGENT'] ."',
					'". datetime() ."'
					);
		";
		//test("tmp_sql",$tmp_sql);
		$insert_results = insertTHECASHIER($tmp_sql);
		//test("tmp_sql",$tmp_sql);
	}

}

function echo_bid_bw($font_size="18px",$r_size="12px",$registered=1) {
	
	$return_value = "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#333333;'>B</span><span style='color:#777777;'>!</span><span style='color:#333333;'>D</span></span>";
	
	if($registered) $return_value .= "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#333333;'><span style='color:#AAAAAA; font-size:" . $r_size . ";'><sup>&reg;</sup></span></span></span>";
	
	return $return_value;
}


function echo_bid_blue($font_size="18px",$r_size="12px") {
	return "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#000088;'>B</span><span style='color:#0000FF;'>!</span><span style='color:#000088;'>D</span><span style='color:#AAAAAA; font-size:" . $r_size . ";'><sup>&reg;</sup></span></span>";
}

function echo_blingk_bw($font_size="18px",$r_size="12px",$registered=1) {
	
	$return_value = "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold; color:#333333;'>BLIN</span><span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold; color:#777777;'>G</span><span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold; color:#333333;'>K!</span>";
	
	if($registered) $return_value .= "<sup><span style='font-family:arial-black,verdana; font-weight:bold; color:#AAAAAA; font-size:" . $r_size . ";'>&reg;</span></sup>";
	
	return $return_value;
}

function echo_blingk_blue($font_size="18px",$r_size="12px") {
	return "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#000088;'>BLIN</span><span style='color:#0000FF;'>G</span><span style='color:#000088;'>K!</span><span style='color:#AAAAAA; font-size:" . $r_size . ";'><sup>&reg;</sup></span></span>";
}



function echo_html_service_logo() {
	
	if(stristr($_SESSION['template']['company']['text_name'],"VOCASIGN")) return echo_vocasign();
	if(stristr($_SESSION['template']['company']['text_name'],"VOCAPASS")) return echo_vocapass();
	if(stristr($_SESSION['template']['company']['text_name'],"BANGK")) return echo_bangk($font_size="18px",$reg_size="12px");
	
	if(stristr($_SESSION['template']['company']['text_name'],"VOCAONE")) return echo_vocaone();

}





### START ECHO_XXXXXX:
function echo_bangk($font_size="18px",$reg_size="12px") {

	if(stristr($_SESSION['template']['company']['text_name'],"VOCASIGN")) {
		return echo_vocasign($font_size="18px",$reg_size="12px");
	} else {
		return "<span style='font-size:" . $font_size . "; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#000088;'>BAN</span><span style='font-size:105%; color:#FFC60A; text-shadow: 0px 1px #444444;'>G</span><span style='color:#000088;'>K!</span><span style='color:#AAAAAA; font-size:" . $reg_size . "; vertical-align:30%;'><sup>&reg;</sup></span></span>";
	}
}

function echo_vocasign($font_size,$sup_size) {

	if(empty($font_size)) $font_size = "120%";
	if(empty($sup_size)) $sup_size = "60%";
	$sup_color = "";
	
	
	if(
	(stristr($_SESSION['template']['company']['name'],"BANGK"))
	) {
		
		return echo_bangk($font_size="18px",$reg_size="8px");
		
	} else {
	
		# green style:
		# return "<span 
		# style='
		# font-family:futura,verdana,arial; 
		# font-weight:bold; 
		# font-size:145%; 
		# color:#444444;
		# '><span style='color:#83AE3B;'>v</span>oca</span><span style='
		# font-family:futura,verdana,arial; 
		# font-weight:normal; 
		# font-size:145%; 
		# color:#777777; 
		# text-shadow: 0px 0px #444444;
		# '>sign</span><sup><span style='
		# font-family:verdana; 
		# font-weight:normal; 
		# font-size:". $sup_size ."; 
		# color:#". $sup_color .";
		# '> ". $sup_text ."</span></sup>";
		
		### return "<span 
		### style='
		### font-family:Helvetica Neue,Verdana; 
		### font-weight:; 
		### font-size:" . $font_size . "; 
		### color:;
		### '><span style='color:#E24A2B;'>V</span>ocaSIGN</span><sup><span style='
		### font-family:Helvetica Neue,Verdana; 
		### font-weight:normal; 
		### font-size:" . $sup_size . "; 
		### color:#" . $sup_color . ";
		### '>℠</span></sup>";
		
		//test("_SESSION['template']['company']['html_name']",$_SESSION['template']['company']['html_name']);
		return $_SESSION['template']['company']['html_name'];
		
		///return "<nobr><span style='font-size:135%; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#6E6E6E; font-family:arial-black,verdana;'>voca</span><span style='font-size:120%; color:#372a9a; text-shadow: 0px 0px #444444; font-weight:bold;'>SIGN</span><sup><span style='font-size:60%; font-weight:normal;  color:#AAAAAA;'> &#8480;</span></sup></span></nobr>";
	
	}
}



function echo_vocapass($sup_text) {

	$sup_color = "AAAAAA";
	$sup_size = "60%";
	if(!empty($sup_text)) {
		$sup_color = "CC0000"; 
		$sup_size = "16px";
	}
	
	if(empty($sup_text)) {
		$sup_text = "&#8480;";
	}
	
	// shea's// return "<span style='font-family:futura,verdana,arial; font-weight:bold; font-size:145%; color:#777777;'><span style='color:#E1492A;'>v</span>oca</span><span style='font-family:futura,verdana,arial; font-weight:bold; font-size:105%; color:#00AA00; text-shadow: 0px 0px #444444;'>PASS</span><sup><span style='font-family:verdana; font-weight:normal; font-size:". $sup_size ."; color:#". $sup_color .";'> ". $sup_text ."</span></sup>";
	
	return "<span style='font-family:futura,verdana,arial; font-weight:bold; font-size:145%; color:#444444;'><span style='color:#EDA035;'>v</span>oca</span><!-- <img src='./link_images/voice-biometric.png' style='vertical-align:middle;'>--><span style='font-family:futura,verdana,arial; font-weight:normal; font-size:145%; color:#777777; text-shadow: 0px 0px #444444;'>pass</span><sup><span style='font-family:verdana; font-weight:normal; font-size:". $sup_size ."; color:#". $sup_color .";'> ". $sup_text ."</span></sup>";
	
	
	
	
}



function echo_vocaone() {
	
	return echo_vocatrust($font_size="",$reg_size="");
	
}


function echo_vocatrust($font_size="",$reg_size="") {

	if(empty($font_size)) $font_size = "205%";
	if(empty($reg_size)) $reg_size = "20%";
	
	##return "<span style='font-family:arial-black,verdana; font-weight:bold; font-size:135%; color:#990000;'>voca</span><span style='font-family:arial-black,verdana; font-weight:bold; font-size:110%; color:#FFB500; text-shadow: 1px 1px #46028B;'>ONE</span><sup><span style='font-size:60%; font-weight:normal; color:#AAAAAA;'>&nbsp;&nbsp;&#8480;</span></sup>";
	
	return "<span style='font-family:futura,verdana,arial; font-weight:bold; font-size:145%; color:#444444;'><span style='color:#E1492A'>v</span>oca</span><span style='font-family:futura,verdana,arial; font-weight:bold; font-size:145%; color:#777777; text-shadow: 0px 0px #46028B;'>one</span><sup><span style='font-size:60%; font-weight:normal; color:#AAAAAA;'>&nbsp;&nbsp;&#8480;</span></sup>";
	
}

function echo_vocatrust_2($voca_size="125%",$reg_size="60%",$service_size="120%") {


	
	return "<span style='font-family:arial-black,verdana; font-weight:bold; color:#AA0000; font-size:$voca_size;'>voca</span><span style='font-family:arial-black,verdana; font-weight:bold; color:#DE9E00; font-size:$service_size;  text-shadow: 0px 0px #46028B;'>ONE</span><sup><span style='font-family:verdana; font-weight:normal; font-size:$reg_size; color:#AAAAAA;'>&nbsp;&nbsp;&#8480;</span></sup>";
	
}



function echo_BBL($special) {

	### if(empty($font_size)) $font_size = "205%";
	### if(empty($reg_size)) $reg_size = "20%";
	
	
	if(empty($special)) $special = "Blacklist";
	$special = ucwords(strtolower($special));
	
	return "<span style='font-size:105%; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#666666; text-shadow: 0px 0px #AAAAAA; font-family:arial-black,verdana;'>Biometric". $special ."</span><span style='font-size:80%; color:#AAAAAA; text-shadow: 0px 0px #222222;'>.org</span><sup><span style='font-size:60%; font-weight:normal; color:#AAAAAA;'>&nbsp;&#8480;</span></sup></span>";
	
}




function echo_pinpass($sup_text="") {

	$sup_color = "AAAAAA";
	$sup_size = "60%";
	if(!empty($sup_text)) {
		$sup_color = "CC0000"; 
		$sup_size = "16px";
	}
	
	if(empty($sup_text)) {
		$sup_text = "&#8480;";
	}
	
	return "<span style='font-size:105%; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#6E6E6E; font-family:arial-black,verdana;'>pin</span><span style='font-size:110%; color:#00AA00; text-shadow: 0px 0px #444444;'><i>PASS</i></span><sup><span style='font-size:". $sup_size ."; font-weight:normal; color:#". $sup_color .";'> ". $sup_text ."</span></sup></span>";
}


function echo_vocamatch($voca_size="135%",$reg_size="20%",$service_size="120%") {

	return "<span style='font-size:" . $voca_size . "; font-family:arial-black,verdana; font-weight:bold;'><span style='color:#6E6E6E; font-family:arial-black,verdana;'>voca</span><span style='font-size:$service_size; color:#BB0000; text-shadow: 0px 0px #444444; font-weight:bold;'><i>MATCH</i></span><span style='font-size:90%; font-weight:normal; color:#CCCCCC; font-family:arial-black,verdana;'>.org</span></span>";
}

function echo_vocamatch_2($voca_size="135%",$reg_size="20%",$service_size="120%") {

	return "<span style='font-family:arial-black,verdana; font-weight:bold; color:#CCCCCC; font-size:$voca_size;'>voca</span><span style='font-family:arial-black,verdana; font-weight:bold; font-size:$service_size; color:#BB0000; text-shadow: 0px 0px #444444; font-weight:bold;'>MATCH</span><span style='font-size:90%; font-weight:normal; color:#6E6E6E; font-family:arial-black;'>.org</span></span>";
}



### END ECHO_XXXXXX:



function updatePREREGISTER($status,$emailaddress,$country_calling_code,$telephone_number) {
	
	### COOKIE SESSION
	$tmp_sql = "UPDATE preregister SET status = '" . $status . "', datetime_updated = '" . datetime() . "', memberid = '" . $_SESSION['member']['memberid'] . "', accountid LIKE '" . $_SESSION['account']['accountid'] . "' WHERE cookie_session = '" . $_COOKIE['COOKIE_SESSION'] . "' AND status = 'pending';";
	logger3("tmp_sql",$tmp_sql);
	$preregisterid = updateTHECASHIER($tmp_sql);
	logger3("preregisterid",$preregisterid);
	
	### EMAIL ADDRESS
	$tmp_sql = "UPDATE preregister SET status = '" . $status . "', datetime_updated = '" . datetime() . "', memberid = '" . $_SESSION['member']['memberid'] . "', accountid LIKE '" . $_SESSION['account']['accountid'] . "' WHERE emailaddress = '" . $emailaddress . "' AND status = 'pending';";
	logger3("tmp_sql",$tmp_sql);
	$preregisterid = updateTHECASHIER($tmp_sql);
	logger3("preregisterid",$preregisterid);

	### TELEPHONE NUMBER
	$tmp_sql = "UPDATE preregister SET status = '" . $status . "', datetime_updated = '" . datetime() . "', memberid = '" . $_SESSION['member']['memberid'] . "', accountid LIKE '" . $_SESSION['account']['accountid'] . "' WHERE telephone_country_code = '" . $country_calling_code . "' AND telephone_number = '" . $telephone_number . "' AND status = 'pending';";
	logger3("tmp_sql",$tmp_sql);
	$preregisterid = updateTHECASHIER($tmp_sql);
	logger3("preregisterid",$preregisterid);
	
}






function payment_option_countries($payment_option) {

	if($payment_option == "direct debit") {
		$tmp_sql = "SELECT iso3 FROM geo_data WHERE (direct_debit != 'NULL' AND direct_debit != '') ORDER BY printable_name ASC;";
		$var = arrayTHECASHIER($tmp_sql);

		//$tmp_sql = "SELECT printable_name FROM geo_data WHERE (direct_debit != 'NULL' AND direct_debit != '') ORDER BY printable_name ASC;";
		//$var['printable_name'] = arrayTHECASHIER($tmp_sql);
	}
	
	return $var;
}

function is_my_country_supported($option,$iso3) {

	if($option == "direct debit") {
		$tmp_sql = "SELECT iso3 FROM geo_data WHERE (direct_debit != 'NULL' AND direct_debit != '') ORDER BY printable_name ASC;";
		$countries = arrayTHECASHIER($tmp_sql);
		
		//test("iso3",$iso3);
		$match = FALSE;
		foreach($countries as $key => $value) {
			//test("value",$value);
			if($iso3 == $value) $match = TRUE;
			break;
		}
		//test("match",$match);
	}
		
	
	return $match;
}

function previous_debit_card_withdrawal() {
	$tmp_sql= "SELECT transactionid FROM transactions 
				WHERE description = 'WITHDRAWAL' 
				AND method = 'DEBIT CARD' 
				AND memberid = '" . $_SESSION['member']['memberid'] . "';";
	$previous_debit_card_withdrawal = getTHECASHIER($tmp_sql);
	if($tmp_sql) {
		return TRUE;
	} else {
		return FALSE;
	}
}




function logger($log_value,$action_code) {
	global $master_config_logger; // set in /BANGK!/master_config.php (global)
	//global $SCRIPT_NAME;
	
	//test("LOGGER: log_value: " . $log_value);
	//test("PHP_SELF: " . $_SERVER["PHP_SELF"]);
	
	if(strtolower($master_config_logger) == "on") {
		$filename = explode("/",$_SERVER["PHP_SELF"]);
		if($filename[4]) {
			$write_file = $filename[4];
		} else if($filename[3]) {
			$write_file = $filename[3];
		} else if($filename[2]) {
			$write_file = $filename[2];
		} else if($filename[1]) {
			$write_file = $filename[1];	
		}
		//$filename = explode("?",$filename[1]);
		//$filename = explode(".",$filename[0]);
		
 	
 		if( (is_array($log_value)) || (is_object($log_value)) ) {
 			
 			
 			array2string($log_value,$output,$parentkey);
 			
 			
 			
 			$tmp_time = time();
 			$outstring = date("Y-m-d H:i:s",$tmp_time) . ": " . $output . "\n\n";
 		} else {
 			$outstring = date("Y-m-d H:i:s",$tmp_time) . ": " . $log_value . "\n\n";
 		}
 		
 		$log_file = "/BANGK!/logs/" . $write_file . ".logger";
		
		//test("log_file",$log_file);
		
		$fp = fopen($log_file,"a");
		if($fp) {
			if($action_code == 1) {
				$outstring .= "* * *==================================================* * *\n\n" . $outstring . "* * * ==================================================* * *\n\n";
			}
			fwrite($fp,$outstring);
			fclose($fp);
		}
	}
}


function logger_2($log_value,$file_name) {
	global $master_config_logger; // set in /BANGK!/master_config.php (global)

 	
 	if( (is_array($log_value)) || (is_object($log_value)) ) {
 		array2string($log_value,$output,$parentkey);
 		$outstring = date("Y-m-d H:i:s",time()) . ": " . $output . "\n\n";
 	} else {
 		$outstring = date("Y-m-d H:i:s",time()) . ": " . $log_value . "\n\n";
 	}
 		
 	$log_file = "/tmp/" . $file_name . ".logger_2";

	$fp = fopen($log_file,"a");
	if($fp) {
		fwrite($fp,$outstring);
		fclose($fp);
	}
}


function logger3($log_name,$log_value,$action_code=NULL) {
	global $master_config_logger; // set in /BANGK!/master_config.php (global)
	global $master_config_logger_vocaPASS_authorizations;
	global $master_config_logger_vocaSIGN_authorizations;
	//global $SCRIPT_NAME;
	
	//test("LOGGER: log_value: " . $log_value);
	//test("PHP_SELF: " . $_SERVER["PHP_SELF"]);
	
	if(
	/* general */	
	( stristr($master_config_logger,"ON") ) || 

	
	/* vocaPASS authorizations related only */
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"voice_authorization.api") ) ||
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"vocaPASS_api_listener.gate") ) ||
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"authorization_database_voicefiles.auth") ) ||
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"vocaPASS_For_Internet_biometric_account_lookup.gate") ) ||
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"database_the_voicefile.gate") ) ||
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"register_the_voice_biometric_voicefileid_array.gate") ) ||
	( ($master_config_logger_vocaPASS_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"function_check_biometrics_now.gate") ) ||
	
	
	/* vocaSIGN authorizations related only */	
	( ($master_config_logger_vocaSIGN_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"voice_authorization.api") ) ||
	( ($master_config_logger_vocaSIGN_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"vocaSIGN_api_listener.gate") ) ||
	( ($master_config_logger_vocaSIGN_authorizations == "ON") && stristr($_SERVER['SCRIPT_URL'],"authorization_database_voicefiles.auth") )
	
	
	) {
		$filename = explode("/",$_SERVER["PHP_SELF"]);
		if($filename[4]) {
			$write_file = $filename[4];
		} else if($filename[3]) {
			$write_file = $filename[3];
		} else if($filename[2]) {
			$write_file = $filename[2];
		} else if($filename[1]) {
			$write_file = $filename[1];	
		}
		//$filename = explode("?",$filename[1]);
		//$filename = explode(".",$filename[0]);
		
 	
 		if( (is_array($log_value)) || (is_object($log_value)) ) {
 			$output = var_export($log_value, true); //array2string($log_value,,$parentkey);
 			$outstring = date("Y-m-d H:i:s",time()) . " : " . strtoupper($log_name) . " : " . $output . "\n\n";
 		} else {
 			$outstring = date("Y-m-d H:i:s",time()) . " : " . strtoupper($log_name) . " : " . $log_value . "\n\n";
 		}
 		
 		$log_file = "/BANGK!/logs/" . $write_file . ".logger";
		
		//test("log_file",$log_file);
		
		$fp = fopen($log_file,"a");
		//test("fp",$fp);
		if($fp) {
			if($action_code == 1) {
				$outstring = "* * *==================================================* * *\n\n" . $outstring . "* * * ==================================================* * *\n\n";
			}
			fwrite($fp,$outstring);
			fclose($fp);
		}
	}
}


function datetime($time) {
	if($time) {
		return date("Y-m-d H:i:s",$time);
	} else {
		return date("Y-m-d H:i:s",time());
	}
		
}


function return_datetime($time) {
	if($time) {
		return date("Y-m-d H:i:s",$time);
	} else {
		return date("Y-m-d H:i:s",time());
	}
		
}

function bonus($bonusid) {

	$string_length = strlen($bonusid);
	
	if($string_length > 30) {
		$tmp_sql = "SELECT * FROM bonus WHERE hash = '" . $bonusid . "';";
	} else {
		$tmp_sql = "SELECT * FROM bonus WHERE bonusid LIKE '" . $bonusid . "';";
	}
	
	$variable = object2array(readTHECASHIER($tmp_sql));
	
	return $variable;
}




### MYSQL BASICS: ###


function readTHECASHIER($query,$dbname=NULL) {
	
	include("/BANGK!/shared/database_config.shared");

	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);
	
	$result = mysql_query($query);
	if($result) {
		$user = mysql_fetch_object($result); 
		return $user; 
	} else {
		return NULL; 
	}
}

function insertTHECASHIER($query,$dbname=NULL) {
	
	include("/BANGK!/shared/database_config.shared");

	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);

	$result = mysql_query($query);
	if($result) {
		$ID = mysql_insert_id($mysql);
		return $ID;
	} else {
		return NULL;
	}
}

function updateTHECASHIER($query,$dbname=NULL) {
	
	include("/BANGK!/shared/database_config.shared");
	
	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);

	$result = mysql_query($query);
	return $result;
}

function getTHECASHIER($query,$dbname=NULL) {
	
	include("/BANGK!/shared/database_config.shared");
	
	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);

	$result = mysql_query($query);
	
	//test("result",$result);

	if($result) {
		$row = mysql_fetch_row($result); 
	}
	if($row[0]) {
		return $row[0];
	} else {
		return NULL; 
	}
}



function arrayTHECASHIER($query,$dbname=NULL,$onecolumn=TRUE) {
	
	include("/BANGK!/shared/database_config.shared");
	
	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);
	
	$result = mysql_query($query);
	
	//
	
	$result_array = array();
	$i = 0;
	if($result) {
		
		while ($row = mysql_fetch_row ($result)) {
			
			//test("result",$result);
			
			if($onecolumn) {
				$data = trim($row[0]);
				$result_array[$i] = $data;
			} else {
				//test("row",$row);
				$result_array[$i] = $row;
			}

			$i += 1;
		}
		return $result_array;
	} else {
		return NULL;
	}
}




function readarrayTHECASHIER($query,$dbname=NULL,$onecolumn=TRUE) {
	
	include("/BANGK!/shared/database_config.shared");
	
	### dynamic db
	if($dbname != NULL) $name_of_database = $dbname;
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);
	
	$result = mysql_query($query);
	if($result) {
		$data = array();
		while($row = mysql_fetch_assoc($result)) {
			//test("row",$row);
			$data[] = $row;
    	}		
    	    
    	return $data;
		
	} else {
		return NULL;
	}
}		
		
		
		
# 	} 
# 	
# 	
# 	
# 	$i = 0;
# 	if($result) {
# 		while ($row = mysql_fetch_row ($result)) {
# 			if($onecolumn) {
# 				$data = trim($row[0]);
# 				$result_array[$i] = $data;
# 			} else {
# 				$result_array[$i] = $row;
# 			}
# 
# 			$i += 1;
# 		}
# 		return $result_array;
# 	} else {
# 		return NULL;
# 	}
# }
# 

function oddeven($number_to_test) {
	if ($number_to_test % 2 == 0)
	{
	  return "even";
	}
	else
	{
	  return "odd";
	}
}




function array2string($myarray,$output,$parentkey) {
	foreach($myarray as $key=>$value){
		if(is_array($value)) {
			$parentkey .= $key."^";
			array2string($value,$output,$parentkey);
			$parentkey = "";
		} else {
			$output .= $parentkey.$key."^".$value."\n";
			//test("output",$$output);
		}
	}
}





function array2object($array) {
	if (!is_array($array)) { #if $array is not an array, return original
		return "";
	}

	foreach($array as $key => $value) { # create obj->property pairs for all $key->value pairs
		$obj->$key = $value;
		return $obj;
	}
}



function object2array($object) {
	if ( !is_object ( $object ) )										// if $object is not an object
		return $object;															// function cannot finish

	$ret = array ();																// create return array
	$v = get_object_vars ( $object );							 // retrieve all object properties and values
	 
	while ( list ( $prop, $value ) = each ( $v ) )	// create key=>value pairs for all $prop=>value pairs
		$ret [ $prop ] = object2array ( $value );
	return $ret;
}








### EMAIL functionS:
function quick_email($to,$subject,$body) {

	### EMMMAIL N2 (CS):  ######################################################
	$to_address = $to;
	$from_address = ""; // defaults to $template
	$from_name = "";  // defaults to $template
	$subject = $subject;
	$text_message = $body;
	$html_message = $body;
	$bounce_address = "";  // defaults to $template
	$from_id = "";  // defaults to $template
	$domain_name = "";  // defaults to $template
	$ip_address = "";  // defaults to $master_config
	//EMMMAIL_CS($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $bounce_address, $from_id, $domain_name, $ip_address);
	
	global $master_config_web_server_ip_www;
	global $template;
	
	EMMMAIL_N1_1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $master_config_web_server_ip_www, $_SESSION['template']['company']['domain']);
	
	
	
	#################################################################################################################################################
}



function quick_email_original($to,$subject,$body) {

	//test("got to... quick_email()",$W);

	global $template;
	global $master_config_web_server_ip_www;
	
	$to_address = $to;
	$from_address = $_SESSION['template']['company']['emailaddress_support'];
	$from_name = $_SESSION['template']['company']['domain'];
	$subject = $subject;
	
	$text_message = str_replace("<br>","\\r",$body);
	$html_message = nl2br($body);
	
	$html_message = emailpage($html_message);
	
	$source_ip = $master_config_web_server_ip_www;
	$domain_name = $_SESSION['template']['company']['domain'];
	
	EMMMAIL_N1_1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $source_ip, $domain_name);

}

function prepareFAQ4Display($content) {
	
	if(!stristr($content, "<br>")) {
		$content = nl2br($content);
	}
	$content = stripslashes($content);
	$content = faq_personalizer($content);
	
	return $content;
}


function quick_email_php($to,$subject,$message) {

	$headers = "";
	$headers .= "From: " .$_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "Reply-To: " . $_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	global $master_config_email_development_override;
	if(!empty($master_config_email_development_override)) $to = $master_config_email_development_override;
	mail($to, $subject, $message, $headers);
}

function bmail($to,$subject,$message,$domain_prefix=null) {

	if(empty($_SESSION['template']['company']['name'])) $_SESSION['template']['company']['name'] = "BANGK!";
	if(empty($_SESSION['template']['company']['emailaddress_support'])) $_SESSION['template']['company']['emailaddress_support'] = "support@BANGK.com";
	
	if(empty($domain_prefix)) $domain_prefix = "admin";
	$headers = "";
	$headers .= "From: ".$domain_prefix."." .$_SESSION['template']['company']['name'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "Reply-To: support." . $_SESSION['template']['company']['name'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	$message = emailpage($message,$email_insert_style=NULL);

	global $master_config_email_development_override;
	if(!empty($master_config_email_development_override)) $to = $master_config_email_development_override;
	mail($to, $subject, $message, $headers);
	
}




function nsdbecp_email_alert($additional_subject="",$additional_message="") {

	// DO NOT REPORT THE FOLLOWING IP WHITELIST:
	if(
	(stristr($_SERVER['REMOTE_ADDR'],"67.29.138"))  /* CRON */
	) {
		return;
	}
	
	
	global $master_config_admin_emailaddress;
	
	$html_message = "";
	
	if(!empty($additional_message)) {
		
		$html_message = "<hr>" . $additional_message . "<hr>";
		
	}
	$html_message .= "<table style='width:100%;'><tr><td style='width:100%; font-size:18px; line-height:35px; border-color:#000088; border-style:ridge; border-width:3px; padding:20px;'>
HTTP_HOST / SERVER_ADDR: ". $_SERVER['HTTP_HOST'] . " [". $_SERVER['SERVER_ADDR'] ."]<br>
SCRIPT_FILENAME: ". $_SERVER['SCRIPT_FILENAME'] . "<br>
HTTP_REFERER: ". $_SERVER['HTTP_REFERER'] . "<br>
IP COUNTRY (ISO3): ".$_SESSION['session']['geo']['ip']. " (".$_SESSION['session']['geo']['city'].", ".$_SESSION['session']['geo']['iso3'].")<br>
HTTP_USER_AGENT: [". $_SERVER['HTTP_USER_AGENT'] ."]<br>
HTTP_COOKIE: [". $_SERVER['HTTP_COOKIE'] ."]<hr>
_SESSION['member']['memberid']: [". $_SESSION['member']['memberid'] ."]<br>
_SESSION['account']['accountid']: [". $_SESSION['account']['accountid'] ."]
</td><tr></table>
";
	
	
	$reply_to_email_address = $_SESSION['template']['company']['emailaddress_support'];
	if(empty($reply_to_email_address)) $reply_to_email_address = $master_config_admin_emailaddress;
	
	$headers = "";
	$headers .= "From: NSDB ECP ALERT <" . $reply_to_email_address . ">\r\n";
	$headers .= "Reply-To: NSDB ECP ALERT <" . $reply_to_email_address . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	//$message = emailpage($html_message,$email_insert_style=NULL);
	
	
	$subject = $_SERVER['HTTP_HOST'] ." (".$_SESSION['session']['geo']['city'].", ".$_SESSION['session']['geo']['iso3'].")";
	
	
	if(!empty($additional_subject)) {
		
		$subject = $subject . " && " . $additional_message;
		
	}	
	

	mail($to=$master_config_admin_emailaddress, $subject, $message=$html_message, $headers);
	
	
}





function bmailalert($subject,$message) {

	global $master_config_admin_emailaddress;
	
	$headers = "";
	$headers .= "From: " .$_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "Reply-To: " . $_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	$message = emailpage($message,$email_insert_style=NULL);
	
	mail($to=$master_config_admin_emailaddress, $subject, $message, $headers);
	
}


function mail_receipt_replto_business($to,$subject,$message,$alert=null) {

	$tmp_reply_to_name = $_SESSION['payme']['business']['account']['accountname'];
	$tmp_reply_to_emailaddress = $_SESSION['payme']['business']['account']['emailaddress'];

	$headers = "";
	$headers .= "From: " . $_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "Reply-To: " . $tmp_reply_to_name . " <" . $tmp_reply_to_emailaddress . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	$message = emailpage($message,$email_insert_style=NULL);

	global $master_config_email_development_override;
	if(!empty($master_config_email_development_override)) $to = $master_config_email_development_override;
	mail($to, $subject, $message, $headers);
}



function quick_mailer($to,$subject,$message,$alert=null) {


	//test("_SESSION['template']['company']['domain']",$_SESSION['template']['company']['domain']);
	

	$headers = "";
	$headers .= "From: " .$_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "Reply-To: " . $_SESSION['template']['company']['domain'] . " <" . $_SESSION['template']['company']['emailaddress_support'] . ">\r\n";
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	$message = emailpage($message,$email_insert_style=NULL);
	


	global $master_config_email_development_override;
	if(!empty($master_config_email_development_override)) $to = $master_config_email_development_override;

	//test("to",$to);
	//test("subject",$subject);
	//test("message",$message);
	
	mail($to, $subject, $message, $headers);
}


function mail_me($to='',$from_name='',$subject='',$message='',$reply_to='',$return_to='') {

	if(empty($return_to)) {
		
		if($_SESSION['template']['company']['domain'] == "NSDB.com") {
			$return_to = "bounce@NSDB.com";
		} else {
			$return_to = "bounce@BANGK.net";
		}
		
	}
	
	
	$headers = "";
	$headers .= "From: " . $from_name  . " <" . $reply_to . ">\r\n";
	$headers .= "Reply-To: " . $from_name . " <" . $reply_to . ">\r\n";
	
	$headers .= "Return-Path: " . $return_to . "\r\n";

	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	//test("mail_me(): to",$to);
	//test("mail_me(): subject",$subject);
	//test("mail_me(): message",$message);
	//test("mail_me(): headers",$headers);
	//test("mail_me(): from_name",$from_name);
	//test("mail_me(): reply_to",$reply_to);
	//test("mail_me(): return_to",$return_to);
	
	$mail_results = mail($to, $subject, $message, $headers, "-f ".$return_to);
	//test("mail_me(): mail_results",$mail_results);
	
	
	
}

# function mail_me_attachment($to_emailaddress,$from_name,$reply_to,$subject,$message,$path_to_attachment) {
# 
# 	$random_hash = md5(date('r', time()));
# 	
# 	$headers = "";
# 	$headers .= "From: " . $from_name  . " <" . $reply_to . ">";
# 	$headers .= "\r\n";
# 	$headers .= "Reply-To: " . $from_name . " <" . $reply_to . ">";
# 	$headers .= "\r\n";	
# 	$headers .= "Return-Path:" . $reply_to;
# 	$headers .= "\r\n";
# 	$headers .= "MIME-Version: 1.0";
# 	$headers .= "\r\n";
# 	$headers .= "Content-Type: multipart/mixed; boundary=\"". $random_hash ."\"";
# 	$headers .= "\r\n";
# 	$headers .= "\r\n";
# 	$header .= "This is a multi-part message in MIME format.";
# 	$headers .= "\r\n";
# 	$header .= "--". $random_hash;
# 	$headers .= "\r\n";
# 	$header .= "Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; name=\"".$path_to_attachment."\"";
# 	$headers .= "\r\n";
# 	$header .= "Content-Transfer-Encoding: base64\r\n";
# 	
# 	$attachment = chunk_split(base64_encode(file_get_contents($path_to_attachment))); 
# 	ob_start(); //Turn on output buffering 
# 	mail($to, $subject, $message, $headers);
# }


function mail_me_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
    $file = $path.$filename;
    $file_size = filesize($file);
    $handle = fopen($file, "r");
    $content = fread($handle, $file_size);
    fclose($handle);
    $content = chunk_split(base64_encode($content));
    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: ".$from_name." <".$from_mail.">\r\n";
    $header .= "Reply-To: ".$replyto."\r\n";
    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message."\r\n\r\n";
    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; name=\"".$filename."\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
    $header .= $content."\r\n\r\n";
    $header .= "--".$uid."--";
    if (mail($mailto, $subject, "", $header)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
    }
}









function mailer($email_to_emailaddress, $email_from_name, $email_subject, $email_html_message, $email_reply_to_emailaddress) {

	//$return_path = 

	$headers = "";
	$headers .= "From: " . $email_from_name . " <" . $email_reply_to_emailaddress . ">\r\n";
	
	//$headers .= "Reply-To: " . $email_from_name . " <" . $email_reply_to_emailaddress . ">\r\n";
	//$headers .= "Return-Path: " . $email_from_name . " <" . $email_reply_to_emailaddress . ">\r\n";
	
	$headers .= "Reply-To: " . $email_from_name . " <" . $email_reply_to_emailaddress . ">\r\n";
	$headers .= "Return-Path: ".$email_reply_to_emailaddress."\r\n";
	
	$headers .= "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	
	
	mail($email_to_emailaddress, $email_subject, $email_html_message, $headers, "-f" . $email_reply_to_emailaddress);
}



/*

### EMMMMAIL(7.1):
function EMMMAIL($to_address, $from_address, $from_name, $return_path, $subject, $message, $cc, $bcc, $received_from, $from_id) {

# echo "to: $to_address, from_name: $from_name, subject: $subject, message: $message<br>";



	if(!$to_address) { $to_address	= "NULL"; }
	if(!$from_address) { $from_address	= "NULL"; }
	if(!$from_name) { $from_name	= "NULL"; }
	if(!$return_path) { $return_path	= "NULL"; }
	if(!$subject) { $subject	= "NULL"; }
	if(!$message) { $message	= "NULL"; }
	if(!$cc) { $cc	= "NULL"; }
	if(!$bcc) { $bcc	= "NULL"; }
	if(!$received_from) { $received_from	= "192.168.1.1"; }
	if(!$from_id) { $from_id	= "clients.emmmail.net"; }

	$message = str_replace("\r","",$message);
	$message = str_replace("\n","\r\n",$message);
	$body = escapeshellarg($message);
	
	exec("/usr/bin/EMMMAIL.aum.php '$to_address' '$from_address' '$subject' $body '$from_name' '$cc' '$bcc' '$received_from' '$return_path' '$from_id' >/dev/null 2>&1 &");
}



### VERSION 7.4
function EMMMAIL_7_4($to_address, $from_address, $from_name, $subject, $text_message, $html_message) {
	

	### EMMMAIL SERVER CONFIG:
	$return_path	= "bounce@BANGK.com";
	$from_id = "mail.BANGK.com";
	$received_from	= "192.168.1.1";
	$ip_address = "64.132.46.3";
	
	### WEERD HTML-ONLY PATCH:
	if($html_message == "") {
		$html_message = "''";
	}
	if($text_message == "") {
		$text_message = "''";
	}

	### ENCODE THE VARS:
	$from_name = escapeshellarg($from_name);
	$subject = escapeshellarg($subject);
	$text_message = escapeshellarg($text_message);
	$html_message = escapeshellarg($html_message);
	
	
	exec("/usr/bin/EMMMAIL_7.4 '$to_address' '$from_address' $from_name $subject $text_message $html_message '$return_path' '$from_id' '$received_from' '$ip_address'>/dev/null 2>&1 &");
}
###############









########## VERSION N1.0 ##########
function EMMMAIL_N1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $source_ip) {
	

	### EMMMAIL SERVER CONFIG:
	$return_path	= "bounce@BANGK.com";
	$from_id = "mail.BANGK.com";
	$received_from	= "mail.BANGK.com";
	$source_ip = "mail.BANGK.com";
	
	
	### WEERD BLANK PATCHES:
	
	if(!$subject) {
		$subject = "''";
	}
		
	if(!$html_message) {
		$html_message = "''";
	}

	if(!$text_message) {
		$text_message = "''";
	}
	

	### ENCODE THE VARS:
	$from_name = escapeshellarg($from_name);
	$subject = escapeshellarg($subject);
	$text_message = escapeshellarg($text_message);
	$html_message = escapeshellarg($html_message);
	
	
	exec("/usr/bin/EMMMAIL_N1.0 '$to_address' '$from_address' $from_name $subject $text_message $html_message '$return_path' '$from_id' '$received_from' '$source_ip'>/dev/null 2>&1 &");
}
##############################

*/



########## VERSION N2 (CS) ##########
function EMMMAIL_CS($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $bounce_address, $from_id, $domain_name, $ip_address) {


	
	
	global $template;
	global $master_config_web_server_ip_www;
	
	### AUTO-SET EMPTY VARS
	if(!$to_address) $to_address = "shea.writer@gmail.com";
	if(!$from_address) $from_address = $_SESSION['template']['company']['emailaddress_support'];
	if(!$from_name) $from_name = $_SESSION['template']['company']['domain'];
	if(!$subject) $subject = "testies testies";
	if(!$text_message) $text_message = "testies testies";
	if(!$html_message) $html_message = "<html><body><u>testies</u> testies</body></html>";
	if(!$bounce_address) $bounce_address = "bounce@" . $_SESSION['template']['company']['domain'];
	if(!$from_id) $from_id = $_SESSION['template']['company']['domain'];
	if(!$received_from) $received_from = $master_config_web_server_ip_www;
	if(!$ip_address) $ip_address = $master_config_web_server_ip_www;
	
	### WEERD BLANK PATCHES:
	
	if(!$subject) {
		$subject = "''";
	}
		
	if(!$html_message) {
		$html_message = "''";
	}

	if(!$text_message) {
		$text_message = "''";
	}

	
	
	### ENCODE THE VARS:
	$from_name = escapeshellarg($from_name);
	$subject = escapeshellarg($subject);
	//$text_message = escapeshellarg($text_message);
	//$html_message = escapeshellarg($html_message);


	$logging = "yes";
	if($logging) logf("/tmp/emmmailer_cs.txt","F() to_address: " . $to_address);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() from_address: " . $from_address);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() from_name: " . $from_name);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() subject: " . $subject);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() text_message: " . $text_message);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() html_message: " . $html_message);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() bounce_address: " . $bounce_address);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() from_id: " . $from_id);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() received_from: " . $received_from);
	if($logging) logf("/tmp/emmmailer_cs.txt","F() ip_address: " . $ip_address);
	
	### EXECUTE:
	//exec("/usr/bin/EMMMAIL_CS '$to_address' $from_address $from_name $subject '$text_message' $html_message '$bounce_address' '$from_id' '$domain_name' '$ip_address'>/dev/null 2>&1 &");

	exec("/usr/bin/EMMMAIL_CS '$to_address' $from_address '$from_name' $subject '$text_message' $html_message '$bounce_address' '$from_id' '$received_from' '$ip_address'>/dev/null 2>&1 &");
}



function emailer_blank($to_address,$subject,$message) {

	$text_message = $html_message = $message;
	
	EMMMAIL_N1_1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $source_ip, $domain_name);
	
	//EMMMAIL_CS($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $bounce_address, $from_id, $domain_name, $ip_address);

}





########## VERSION N1.1 ##########
function EMMMAIL_N1_1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $source_ip, $domain_name) {

//test("got to... EMMMAIL_N1_1()",$W);


//1.  $to_address = $member[emailaddress],
//2.  $from_address = $_SESSION['template']['company'][emailaddress_support], 
//3.  $from_name = $_SESSION['template']['company'][simple_name], 
//4.  $subject = $subject, 
//5.  $text_message = $text_message, 
//6.  $html_message = $html_message, 
//7.  $source_ip = $master_config_web_server_ip_generic
//8.  $domain_name = $_SESSION['template']['company'][name]


	/// set vars:
	global $template;
	global $master_config_web_server_ip_www;
	
	if(!$from_address) $from_address = $_SESSION['template']['company']['emailaddress_support'];
	if(!$from_name) $from_name = $_SESSION['template']['company']['simple_name'] . " (Support)";
	if(!$source_ip) $source_ip = $master_config_web_server_ip_www;
	if(!$domain_name) $domain_name = $_SESSION['template']['company']['domain'];
	



	$logging = "yes";

	if($logging) logf("/tmp/emmmailer.txt","F() to_address: " . $to_address);
	if($logging) logf("/tmp/emmmailer.txt","F() from_address: " . $from_address);
	if($logging) logf("/tmp/emmmailer.txt","F() from_name: " . $from_name);
	if($logging) logf("/tmp/emmmailer.txt","F() subject: " . $subject);
	if($logging) logf("/tmp/emmmailer.txt","F() text_message: " . $text_message);
	if($logging) logf("/tmp/emmmailer.txt","F() html_message: " . $html_message);
	if($logging) logf("/tmp/emmmailer.txt","F() source_ip: " . $source_ip);
	if($logging) logf("/tmp/emmmailer.txt","F() domain_name: " . $domain_name);



	### EMMMAIL SERVER CONFIG:
	$return_path	= "bounce@" . $domain_name;
	$from_id = $domain_name;
	$received_from	= $domain_name;
	
	
	### WEERD BLANK PATCHES:
	
	if(!$subject) {
		$subject = "''";
	}
		
	if(!$html_message) {
		$html_message = "''";
	}

	if(!$text_message) {
		$text_message = "''";
	}
	
	
	### ENCODE THE VARS:
	$from_name = escapeshellarg($from_name);
	$subject = escapeshellarg($subject);
	$text_message = escapeshellarg($text_message);
	$html_message = escapeshellarg($html_message);
	
	//if($logging) logf("/tmp/emmmailer.txt","Got to emmailer fucntion.");
	//exec("/BANGK!/shared/EMMMAIL_N1.1 '$to_address' '$from_address' $from_name $subject $text_message $html_message '$return_path' '$from_id' '$received_from' '$source_ip' '$domain_name'>/dev/null 2>&1 &");
	
	exec("/BANGK!/shared/EMMMAIL_N1.1 '$to_address' '$from_address' $from_name $subject $text_message $html_message '$return_path' '$from_id' '$received_from' '$source_ip' '$domain_name' > /dev/null 2>&1 &");
	
	//if($logging) logf("/tmp/emmmailer.txt","tmp_results: " . $tmp_output);
	//if($logging) logf("/tmp/emmmailer.txt","tmp_results: " . $tmp_return);
	return $tmp_output;
}



function email_alert($special_message=NULL,$to_emailaddress) {

	if(!$to_emailaddress) $to_emailaddress = "shea.writer@nsdb.com";
	
	global $master_config_email_alert;
	global $skip_these_ips;
	
	if($master_config_email_alert == "on") {

		$skip_this_ip = "no";
		foreach($skip_these_ips as $key => $value) {
			$tmp_string = strstr($_SERVER['REMOTE_ADDR'],$value);
			if( isset($tmp_string) && ($tmp_string != FALSE) ) {
				$skip_this_ip = "yes";
			}
		}

		if($skip_this_ip == "no") {
	
			global $session;
			global $template;
			global $master_config_web_server_ip_www;
			global $cookie_emailaddress;

			$filename = explode("/",$_SERVER["PHP_SELF"]);
			if($filename[4]) {
				$file_name = $filename[4];
			} else if($filename[3]) {
				$file_name = $filename[3];
			} else if($filename[2]) {
				$file_name = $filename[2];
			} else if($filename[1]) {
				$file_name = $filename[1];	
			}
	
			$session_string = http_build_query($session);

			$tmp_geobytes_array = geobytes($_SERVER["REMOTE_ADDR"]);
			//test("tmp_geobytes_array",$tmp_geobytes_array);
			$tmp_geobytes_string = implode("<br>",$tmp_geobytes_array);

			$body = "<span style='font-family:arial; font-size:16px; font-weight:normal;'>
			File Name: " . $file_name . "<br>
			<br>
			IP Address: " . $_SERVER["REMOTE_ADDR"] . " ( http://www.ipchecking.com/?ip=" . $_SERVER["REMOTE_ADDR"] . "&check=Lookup )<br>
			<br>
			GEOBYTES:  " . $tmp_geobytes_string . "<br>
			<br>
			cookie_emailaddress: " . $cookie_emailaddress . "<br>
			<br>
			SESSION: " . $session_string . "
			<br>
			SPECIAL MESSAGE: " . $special_message . "
			</span>
			<p>";
			
			//$body = emailpage($body);
			
			if($special_message == NULL) $file_name = $special_message;
	
			
			$to_address = $to_emailaddress;
			$from_address = $_SESSION['template']['company']['emailaddress_support'];
			$from_name = $_SESSION['template']['company']['domain'];
			$subject = $special_message . " / COUNTRY: " . $tmp_geobytes_array['country'];
			$text_message = $body;
			$html_message = $body;
			$source_ip = $master_config_web_server_ip_www;
			$domain_name = $_SESSION['template']['company']['domain'];
			//test("subject",$subject);			//EMMMAIL_N1_1($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $source_ip, $domain_name);
			//quick_email_php($to_address,$subject,$html_message);
			
			
			//quick_mailer($to_address,$subject,$html_message,"(SYSALERT)");
			
			
			
			### EMMMAIL N2 (CS):  ######################################################
			// $to_address = "shea.writer@nsdb.com";
			// $from_address = ""; // defaults to $template
			// $from_name = "";  // defaults to $template
			// $subject = "EMAIL ALERT: " . $file_name . " / " . $_SERVER["REMOTE_ADDR"];
			// $text_message = $body;
			// $html_message = $body;
			// $bounce_address = "";  // defaults to $template
			// $from_id = "";  // defaults to $template
			// $domain_name = "";  // defaults to $template
			// $ip_address = "";  // defaults to $master_config
			// EMMMAIL_CS($to_address, $from_address, $from_name, $subject, $text_message, $html_message, $bounce_address, $from_id, $domain_name, $ip_address);
			#################################################################################################################################################
			
			
		}
	}
}


function amount012($amount,$currency_code) {

	global $account;
	
	//test("account",$account);
	
	# default to system base
	if(!$currency_code) {
		$currency_code = $account['currency_0_iso3'];
	}
	
	//test("currency_code",$currency_code);
		
	if($currency_code == $account['currency_0_iso3']) {
		
		$variable['currency_code']['0'] = $currency_code;
		$variable['currency_code']['1'] = $account['currency_code_1'];
		$variable['currency_code']['2'] = $account['currency_code_2'];
	
		$variable['amount']['0'] = currency_format($amount);
		$variable['amount']['1'] = currency_format(get_fx($variable['currency_code']['0'],$variable['currency_code']['1'],$amount));
		$variable['amount']['2'] = currency_format(get_fx($variable['currency_code']['0'],$variable['currency_code']['2'],$amount));
		
		//test("0. variable['amount']['0']",$variable['amount']['0']);
	}
		
	if($currency_code == $account['currency_code_1']) {
		$variable['currency_code']['0'] = $account['currency_0_iso3'];
		$variable['currency_code']['1'] = $currency_code;
		$variable['currency_code']['2'] = $account['currency_code_2'];
	
		$variable['amount']['0'] = currency_format(get_fx($variable['currency_code']['1'],$variable['currency_code']['0'],$amount));
		$variable['amount']['1'] = currency_format($amount);
		$variable['amount']['2'] = currency_format(get_fx($variable['currency_code']['1'],$variable['currency_code']['2'],$amount));
		
		//test("1. variable['amount']['0']",$variable['amount']['0']);
	}
		
	if($currency_code == $account['currency_code_2']) {
		$variable['currency_code']['0'] = $account['currency_0_iso3'];
		$variable['currency_code']['1'] = $account['currency_code_1'];
		$variable['currency_code']['2'] = $currency_code;
	
		$variable['amount']['0'] = currency_format(get_fx($variable['currency_code']['2'],$variable['currency_code']['0'],$amount));
		$variable['amount']['1'] = currency_format(get_fx($variable['currency_code']['2'],$variable['currency_code']['1'],$amount));
		$variable['amount']['2'] = currency_format($amount);
		
		//test("2. variable['amount']['0']",$variable['amount']['0']);
	}

	
	## If non of the abive, then set the currency to position 1
	if( ($currency_code != $account['currency_0_iso3']) && ($currency_code != $account['currency_code_1']) && ($currency_code != $account['currency_code_2']) ) {

		$variable['currency_code']['0'] = $account['currency_0_iso3'];
		$variable['currency_code']['1'] = $currency_code;
		$variable['currency_code']['2'] = $account['currency_code_2'];
	
		$variable['amount']['0'] = currency_format(get_fx($variable['currency_code']['1'],$variable['currency_code']['0'],$amount));
		$variable['amount']['1'] = currency_format($amount);
		$variable['amount']['2'] = currency_format(get_fx($variable['currency_code']['1'],$variable['currency_code']['2'],$amount));
		
		//test("1a. variable['amount']['0']",$variable['amount']['0']);
	}
	
	$variable['amount01'] = 	$variable['currency_code']['0'] . "&nbsp;" . $variable['amount']['0'];
	
	if(($account['currency_translation'] != "Off")  && ($account['currency_code_1'])) {
		$variable['amount01'] = $variable['amount01'] . "&nbsp;&nbsp;<span style='font-weight:normal; font-size:smaller;'>(" . $variable['currency_code']['1'] . "&nbsp;" . equals_symbol() . equals_symbol() . $variable['amount']['1'] . ")</span>";
	}
	
	//test("virable['value01']",$virable['value01']);
	
	//test("variable",$variable);
	
	return $variable;
}


function getTransactionNetValues($transactionid) {

	$tmp_transaction = transaction($transactionid);
	
	//test("tmp_transaction",$tmp_transaction);
		
	$variable[0] = $tmp_transaction['currency_0_iso3'] . "&nbsp;" . $tmp_transaction['currency_0_request'];
	
	//test("variable[0]",$variable[0]);
	
	if($tmp_transaction['currency_1_request']) {
		$variable[1] = "<span style='font-weight:normal; font-size:smaller;'>(" . $tmp_transaction['currency_1_iso3'] . "&nbsp;" . equals_symbol() . $tmp_transaction['currency_1_request'] . ")</span>";
	}
	
	if($tmp_transaction['currency_2_request']) {
		$variable[2] = "<span style='font-weight:normal; font-size:smaller;'>(" . $tmp_transaction['currency_2_iso3'] . "&nbsp;" . equals_symbol() . $tmp_transaction['currency_2_request'] . ")</span>";
	}
	
	return $variable;
}	



function amount012DB($transactionid) {

	//global $account;

	$tmp_sql = "SELECT * FROM transactions WHERE transactionid LIKE '" . $transactionid . "';";
	$tmp_transaction = readTHECASHIER($tmp_sql);
	
	$tmp_account = account($tmp_transaction->accountid);
	
	$variable['currency_code']['0'] = $tmp_transaction->currency_0_iso3;
	$variable['currency_code']['1'] = $tmp_transaction->currency_1_iso3;
	$variable['currency_code']['2'] = $tmp_transaction->currency_2_iso3;
	
	$variable['amount']['0'] = currency_format($tmp_transaction->currency_0_total);
	$variable['amount']['1'] = currency_format($tmp_transaction->currency_1_total);
	$variable['amount']['2'] = currency_format($tmp_transaction->currency_2_total);
		
	
	$variable['amount01'] = 	$variable['currency_code']['0'] . "&nbsp;" . $variable['amount']['0'];
	
	if(($variable['amount']['1']) && ($tmp_account['currency_translation'] != "Off") && ($variable['currency_code']['0'] != $variable['currency_code']['1']) ) {
		$variable['amount01'] = $variable['amount01'] . "<span style='font-weight:normal; font-size:smaller;'>&nbsp;&nbsp;(" . $variable['currency_code']['1'] . "&nbsp;" . equals_symbol() . $variable['amount']['1'] . ")</span>";
	}
	
	/*
	if(($account['currency_translation'] != "Off") && ($variable['amount']['2'])) {
		$variable['amount01'] = $variable['amount01'] . "<span style='font-weight:normal; font-size:smaller;'>&nbsp;&nbsp;(" . $variable['currency_code']['2'] . "&nbsp;" . equals_symbol() . $variable['amount']['2'] . ")</span>";
	}
	*/
	
	//test("virable['value01']",$virable['value01']);
	
	//test("variable",$variable);
	
	return $variable;
}


function amount012DB2($amount,$transactionid) {

# description: generate currency translation for any value based on the exxchange rates of a given transaction id

	global $account;

	$tmp_sql = "SELECT * FROM transactions WHERE transactionid LIKE '" . $transactionid . "';";
	$tmp_transaction = readTHECASHIER($tmp_sql);
	
	$variable['currency_code']['0'] = $tmp_transaction->currency_0_iso3;
	$variable['currency_code']['1'] = $tmp_transaction->currency_1_iso3;
	$variable['currency_code']['2'] = $tmp_transaction->currency_2_iso3;
	
	$variable['amount']['0'] = currency_format($amount);
	$variable['amount']['1'] = currency_format($amount * $tmp_transaction->currency_1_ratio);
	$variable['amount']['2'] = currency_format($amount * $tmp_transaction->currency_2_ratio);
		
	
	$variable['amount01'] = 	$variable['currency_code']['0'] . "&nbsp;" . $variable['amount']['0'];
	if(($account['currency_translation'] != "Off") && ($variable['amount']['1'])) {
		$variable['amount01'] = $variable['amount01'] . "<span style='font-weight:normal; font-size:smaller;'>&nbsp;&nbsp;(" . $variable['currency_code']['1'] . "&nbsp;" . equals_symbol() . $variable['amount']['1'] . ")</span>";
	}
	if(($account['currency_translation'] != "Off") && ($variable['amount']['2'])) {
		$variable['amount01'] = $variable['amount01'] . "<span style='font-weight:normal; font-size:smaller;'>&nbsp;&nbsp;(" . $variable['currency_code']['2'] . "&nbsp;" . equals_symbol() . $variable['amount']['2'] . ")</span>";
	}
	
	
	//test("virable['value01']",$virable['value01']);
	
	//test("variable",$variable);
	
	return $variable;
}





function getFAQ($questionid) {
	$tmp_sql = "SELECT * FROM faq_questions WHERE questionid = '" . $questionid . "';";
	$variable = object2array(readTHECASHIER($tmp_sql));
	$variable['question'] = prepareFAQ4Display(faq_personalizer($variable['question']));
	$variable['answer'] = prepareFAQ4Display(faq_personalizer($variable['answer']));
	return $variable;
}


function DTR($transactionid,$dynamic_DTR) {

	global $master_config_DTR;
	global $master_config_rolling_reserve_DTR;
	
	if(!$dynamic_DTR) {
		$active_DTR = $master_config_DTR;
	} else {
		$active_DTR = $dynamic_DTR;
	}

	//test("transactionid",$transactionid);

	$tmp_sql = "SELECT * FROM transactions WHERE transactionid LIKE '" . $transactionid . "';";
	$tmp_transaction_details = readTHECASHIER($tmp_sql);
	
	//logger3("tmp_sql",$tmp_sql);
	//test("transaction_details->requested_datetime",$tmp_transaction_details->requested_datetime);
	
	if(!empty($tmp_transaction_details->rebill_datetime)) {
		$requested_datetime = $tmp_transaction_details->rebill_datetime;
	} else {
		$requested_datetime = $tmp_transaction_details->requested_datetime;
	}
	
	if(
	(!empty($tmp_transaction_details->DTR)) &&
	($tmp_transaction_details->DTR != "0") &&
	($dynamic_DTR != $master_config_rolling_reserve_DTR)
	) {
		$active_DTR = $tmp_transaction_details->DTR;
	}
	
	//test("active_DTR",$active_DTR);
	
	/*$DTR_value = ceil( ($active_DTR - 1) - (strtotime(date("Y-m-d h:i:s")) - strtotime($requested_datetime)) / (60 * 60 * 24));
	if($DTR_value > $active_DTR) {
		$DTR_value = $active_DTR;
	} else if( ($DTR_value == 0) || ($DTR_value < 0) ) {
		$DTR_value = "Released";
	}*/
        

	$current_datetime = time();
	$requested_datetime = strtotime($requested_datetime);
	$time_diff = $current_datetime - $requested_datetime;    
	$ttd = $time_diff/(60*60*24);    
	$DTR_value = ceil($active_DTR - $ttd);
	//test("DTR_value",$DTR_value);      
	if($DTR_value < 1) $DTR_value = "Released";
	return $DTR_value;
}



function emailpage($message,$email_insert_style=NULL) {

	//test("message",$message);
	
	if(!stristr($message,"<BR")) {
		$message = str_replace("<br>","\\n",$message);
		$message = str_replace("<br/>","\\n",$message);
		$message = str_replace("<br />","\\n",$message);
		$message = nl2br($message);
	}
	
	if(stristr($_SESSION['template']['company']['domain'],"NSDB.com")) $set_logo_height = " height='60px;'";

	$page = "
<html>
	
	<head>
		<title>" . $_SESSION['template']['company']['domain'] . " " . $_SESSION['template']['company']['slogan1'] . "</title>
		<META NAME=\"ROBOTS\" CONTENT=\"NONE\">
		<META NAME=\"GOOGLEBOT\" CONTENT=\"NOARCHIVE\">
<style>



.v2_footer_text_table_1 {
    width:100%;
    height:auto;
    background-color:transparent;
    
    border-width:1px;
    border-spacing:0;
    border-collapse:collapse;
    border-style:solid;
    border-color:#000000;	

    padding-top:0px;
    padding-bottom:0px;
    padding-left:0px;
    padding-right:0px;
    
    margin-left:0px;
    margin-right:0px;
    margin-top:3px;
    margin-bottom:0px;

}


.v2_footer_text_td_1 {
    width:auto;
    height:auto;
    background-color:transparent;
    
    border-spacing:0;
    border-width:1px;
    border-collapse:collapse;
    border-style:solid;
    border-color:#000000;

    padding-top:0px;
    padding-bottom:5px;
    padding-left:20px;
    padding-right:5px;
    
    margin-left:0px;
    margin-right:0px;
    margin-top:0px;
    margin-bottom:0px;

    vertical-align:bottom;
    text-align:left;	
}

.v2_footer_text_td_2 {
    width:auto;
    height:auto;
    background-color:transparent;
    
    border-spacing:0;
    border-width:1px;
    border-collapse:collapse;
    border-style:solid;
    border-color:#000000;	

    padding-top:0px;
    padding-bottom:5px;
    padding-left:20px;
    padding-right:20px;
    
    margin-left:0px;
    margin-right:0px;
    margin-top:0px;
    margin-bottom:0px;
    
    vertical-align:bottom;
    text-align:right;	
}

.css_satisfaction_guaranteed {
	font-family:tahoma,arial;
	text-decoration:none;
	font-size:12px;
	font-weight:BOLD;
	color:#555555;
}

.css_satisfaction_guaranteed A {
	font-family:tahoma,arial;
	text-decoration:none;
	font-size:12px;
	font-weight:BOLD;
	color:#555555;
}

.css_satisfaction_guaranteed A:HOVER {
	font-family:tahoma,arial;
	text-decoration:underline;
	font-size:12px;
	font-weight:BOLD;
	color:#555555;
}

.email_receipt_footer_support {
	text-decoration:none;
	font-size:16px;
	font-weight:normal;
}

.email_receipt_footer_support A {
	text-decoration:none;
	font-size:16px;
	font-weight:normal;
}

.email_receipt_footer_support A:HOVER {
	text-decoration:underline;
	font-size:16px;
	font-weight:normal;
}

" . $email_insert_style . "

</style>
	</head>
	<body>
	
		<center>
	
			<!-- START TABLE I_i. ('OUTER-FRAME') -->
			<table cellpadding='1' cellspacing='0'	bgcolor='000066' width='100%' height='100%' border='2'>
				<tr>
					<td bgcolor='" . $_SESSION['template']['TABLE_I_i']['td_bgcolor'] . "' align='" . $_SESSION['template']['TABLE_I_i']['td_align'] . "'  valign='top'>
					
						<!-- START TABLE I_ii. ('INNER-FRAME') -->
						<table cellpadding='0' cellspacing='0' bgcolor='FFFFFF' width='100%' height='100%' border='0'>
							<tr>
								<td align='right' valign='top'>
								
									<table cellpadding='0' cellspacing='0' border='0' bgcolor='FFFFFF' height='94%' width='100%'>
										<tr>
											<td bgcolor='" . $_SESSION['template']['TABLE_I_ii']['td_bgcolor'] . "' align='left' valign='top' width='100%' style='padding:15px;'>
												
												<center>
									
													<!-- START TABLE III. (LOGO) -->
													<table cellpadding='" . $_SESSION['template']['TABLE_III']['cellpadding'] . "' cellspacing='" . $_SESSION['template']['TABLE_III']['cellspacing'] . "' bgcolor='" . $_SESSION['template']['TABLE_III']['bgcolor'] . "'  width='" . $_SESSION['template']['TABLE_III']['width'] . "' border='0' style='margin-bottom:auto;'>";
if(stristr($_SESSION['template']['company']['domain'],"vocamatch.org"))
{
    $page .= "<tr style='background-color:".$_SESSION['template']['company']['logo_bg'].";'>";
}
else {
    $page .= " <tr>";
}
$page .= "
			 											
			 												<td align='left' valign='top'>";
			 												

##############################################################
### START: LOGO 			 													
##############################################################

global $vocasign_email_receipt_merchant_path_to_logo;
global $vocasign_email_receipt_merchant_path_to_logo_height;
if(!empty($vocasign_email_receipt_merchant_path_to_logo)) {
	
	if(empty($vocasign_email_receipt_merchant_path_to_logo_height)) {
		$vocasign_email_receipt_merchant_path_to_logo_height = "auto";
	}
	
	$page .= "<img src='" . $vocasign_email_receipt_merchant_path_to_logo . "' style='height:" . $vocasign_email_receipt_merchant_path_to_logo_height . ";' border='0'>";
	
	
} else if(empty($_SESSION['template']['company']['logo_topleft'])) {
    //test("set_logo_height",$set_logo_height);
    $page .= "<table><tr><td ". $set_logo_height .">". $_SESSION['template']['company']['html_logo'] ."</td></tr></table>";
    
} else {
    if(stristr($_SESSION['template']['company']['domain'],"vocamatch.org"))
    {
        $page .= "<a href='https://".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
    }
    
    // this is the logo that appears in the business registration email receupts.
    //test("",$_SESSION['voice_authorization_api']['business_account_details']['vocasign']['gateway_authorization_logo']);
    
    if(is_array($_SESSION['voice_authorization_api']['business_account_details']))
    {
    	if($_SESSION['voice_authorization_api']['business_account_details']['vocasign']['gateway_authorization_logo']) {
		    $tmp_email_receipt_logo = "https://images.vocaone.com/". $_SESSION['voice_authorization_api']['business_account_details']['vocasign']['gateway_authorization_logo'];
    	} else {
		    $tmp_email_receipt_logo = image("url",$_SESSION['template']['company']['logo_topleft']);
    	}
    	$page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height .">";
    	
    	if(stristr($_SESSION['template']['company']['domain'],"vocamatch.org"))
    	{
    	    $page .= "</a>";
    	}
    }
}

 if(stristr($_SESSION['template']['company']['domain'],"video-conference.link")) {
	 $tmp_email_receipt_logo = image("url",$_SESSION['template']['company']['logo_topleft']);
	 $page .= "<a href='https://".$_SESSION['template']['company']['domain']."' target='".$_SESSION['template']['company']['domain']."' border='0'>";
	 $page .= "<img src='" . $tmp_email_receipt_logo . "' border='0'".$set_logo_height .">";
	 $page .= "</a>";
	 
 }


##############################################################
### END: LOGO 			 													
##############################################################


															
$page .= "			 												</td>
			 											
			 												<td align='middle' valign='top'>";
if(stristr($_SESSION['template']['company']['domain'],"vocamatch.org"))
{
    $page .= "<img src='" . image("url",$_SESSION['template']['company']['logo_topcenter']) . "' border='0'>";
}
$page .= "
			 												</td>
			 											
			 												<td align='right' valign='top'>";
			 												
			 													//$tmp_pormotional_logo = $_SESSION['template']['company']['logo_topright'];
			 													//if(!stristr($_COOKIE['cookie_route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
			 													//if(!stristr($_SESSION['route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
			 													
			 													
			 													
			 													/// this sets the RIGHT LOGO for vocaSIGN when the merchant has a logo set
			 													global $tmp_merchant_details;
			 													if(
			 													(!stristr($tmp_merchant_details->accountname,"vocaONE")) &&
			 													(!stristr($tmp_merchant_details->accountname,"vocaSIGN")) &&
			 													(!empty($vocasign_email_receipt_merchant_path_to_logo))
			 													) {
				 													$tmp_pormotional_logo = "powered_by_vocaSIGN.png";
			 													} else if(!stristr($_SESSION['template']['company']['domain'],"video-conference.link")){
				 													//$tmp_pormotional_logo = "biometrically_secured_network.png";
				 													$tmp_pormotional_logo = "powered_by_vocaONE.png";
			 													} else {
				 													$tmp_pormotional_logo = "one_pixel.gif";
			 													}
			 													
			 													
			 													if($_SESSION['transaction']['hash']) $add_properties = "&transactionid=".$_SESSION['transaction']['hash'];
			 													
			 										
			 													if(!stristr($_SESSION['template']['company']['domain'],"vocamatch.org")){
		$page .= "					
																<img src='" . image("url",$tmp_pormotional_logo) . "' border='0'>";
}
$page .= "
			 												</td>																																	 
													
														</tr>
													</table>
													<!-- END TABLE III. (LOGO) -->
											
												</center>
												
												<table style='width:100%; height:auto; margin-top:auto;'>
													<tr>
														<td>
															<span style='
															line-height:" . $_SESSION['template']['company']['email_line_height'] . "; 
															color:" . $_SESSION['template']['company']['email_text_color'] . "; 
															font-family:" . $_SESSION['template']['company']['email_text_face'] . "; 
															font-size:" . $_SESSION['template']['company']['email_text_size'] . ";
															font-weight:" . $_SESSION['template']['company']['email_text_weight'] . ";
															'>
															    <br>
															    " . $message . "<br>
															    <br>
															</span>
														</td>
													</tr>
												</table>
											</td>
										</tr>
									</table>";
									
									$add_to = "page";  // adds text to "page" variable
									$tight_footer_right = "<a href='https://" . $_SESSION['template']['company']['host_support'] . "'>24-Hour, Worldwide Customer Support</a>";
									include($_SESSION['template']['company']['file_path'] . "shared/footer_text.shared");
									
									$page .= "
									

								</td>
							</tr>
						</table>
						
					</td>
				</tr>
			</table>
			
		</center>

	</body>
</html>";

	return $page;
	
}


function shared_regulatory_footer() {
	return "<nobr>NSDB PTY LTD (ABN#13121500990) operates " . $_SESSION['template']['company']['domain'] . " as a \"Low-Value, Non-Cash Payment Facility\" under the regulatory authority of the Australian Securities and Investment Commisson (ASIC).</nobr><br>
<nobr>NSDB LIMITED (REG#07441969) is certified to operate " . $_SESSION['template']['company']['domain'] . " as a \"Small E-Money Issuer\" under the regulatory authority of the British Financial Services Authority (FSA UK).</nobr><br>
<nobr>NSDB LIMITED (UNITED KINGDOM) is a 100% owned, operated and guaranteed subsidiary of NSDB PTY LTD (AUSTRALIA)</nobr>";
}



function emailpage_satisfaction_guaranteed($message,$email_insert_style=NULL,$transaction_hash=null) {

	if(!stristr($message,"<BR>")) {
		$message = str_replace("<br>","",$message);
		$message = nl2br($message);
	}

	$page = "
<html>
	
	<head>
		<title>" . $_SESSION['template']['company']['domain'] . " " . $_SESSION['template']['company']['slogan1'] . "</title>
		<META NAME=\"ROBOTS\" CONTENT=\"NONE\">
		<META NAME=\"GOOGLEBOT\" CONTENT=\"NOARCHIVE\">
<style>



.v2_footer_text_table_1 {
    width:100%;
    height:auto;
    background-color:transparent;
    
    border-width:1px;
    border-spacing:0;
    border-collapse:collapse;
    border-style:solid;
    border-color:#000000;	

    padding-top:0px;
    padding-bottom:0px;
    padding-left:0px;
    padding-right:0px;
    
    margin-left:0px;
    margin-right:0px;
    margin-top:3px;
    margin-bottom:0px;

}


.v2_footer_text_td_1 {
    width:auto;
    height:auto;
    background-color:transparent;
    
    border-spacing:0;
    border-width:1px;
    border-collapse:collapse;
    border-style:solid;
    border-color:#000000;

    padding-top:0px;
    padding-bottom:5px;
    padding-left:20px;
    padding-right:5px;
    
    margin-left:0px;
    margin-right:0px;
    margin-top:0px;
    margin-bottom:0px;

    vertical-align:bottom;
    text-align:left;	
}

.v2_footer_text_td_2 {
    width:auto;
    height:auto;
    background-color:transparent;
    
    border-spacing:0;
    border-width:1px;
    border-collapse:collapse;
    border-style:solid;
    border-color:#000000;	

    padding-top:0px;
    padding-bottom:5px;
    padding-left:20px;
    padding-right:20px;
    
    margin-left:0px;
    margin-right:0px;
    margin-top:0px;
    margin-bottom:0px;
    
    vertical-align:bottom;
    text-align:right;	
}

.css_satisfaction_guaranteed {
	font-family:tahoma,arial;
	text-decoration:none;
	font-size:12px;
	font-weight:BOLD;
	color:#555555;
}

.css_satisfaction_guaranteed A {
	font-family:tahoma,arial;
	text-decoration:none;
	font-size:12px;
	font-weight:BOLD;
	color:#555555;
}

.css_satisfaction_guaranteed A:HOVER {
	font-family:tahoma,arial;
	text-decoration:underline;
	font-size:12px;
	font-weight:BOLD;
	color:#555555;
}

" . $email_insert_style . "

</style>
	</head>
	<body>
	
		<center>
	
			<!-- START TABLE I_i. ('OUTER-FRAME') -->
			<table cellpadding='1' cellspacing='0'	bgcolor='000066' width='100%' height='100%' border='2'>
				<tr>
					<td bgcolor='" . $_SESSION['template']['TABLE_I_i']['td_bgcolor'] . "' align='" . $_SESSION['template']['TABLE_I_i']['td_align'] . "'  valign='top'>
					
						<!-- START TABLE I_ii. ('INNER-FRAME') -->
						<table cellpadding='0' cellspacing='0' bgcolor='FFFFFF' width='100%' height='100%' border='0'>
							<tr>
								<td align='right' valign='top'>
								
									<table cellpadding='0' cellspacing='0' border='0' bgcolor='FFFFFF' height='94%' width='100%'>
										<tr>
											<td bgcolor='" . $_SESSION['template']['TABLE_I_ii']['td_bgcolor'] . "' align='left' valign='top' width='100%' style='padding:15px;'>
												
												<center>
									
													<!-- START TABLE III. (LOGO) -->
													<table cellpadding='" . $_SESSION['template']['TABLE_III']['cellpadding'] . "' cellspacing='" . $_SESSION['template']['TABLE_III']['cellspacing'] . "' bgcolor='" . $_SESSION['template']['TABLE_III']['bgcolor'] . "'  width='" . $_SESSION['template']['TABLE_III']['width'] . "' border='0' style='margin-bottom:auto;'>				
														<tr>
			 											
			 												<td align='left' valign='top'>
																<img src='" . image("url",$_SESSION['template']['company']['logo_topleft']) . "' border='0'>
			 												</td>
			 											
			 												<td align='middle' valign='top'>
																<img src='" . image("url",$_SESSION['template']['company']['logo_topcenter']) . "' border='0'>
			 												</td>
			 											
			 												<td align='right' valign='top'>";
			 												
			 													//$tmp_pormotional_logo = $_SESSION['template']['company']['logo_topright'];
			 													//if(!stristr($_COOKIE['cookie_route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
			 													//if(!stristr($_SESSION['route'],"SHOW SECRETS")) $tmp_pormotional_logo = "exclusive_and_patented_y.png";
			 													$tmp_pormotional_logo = "biometrically_secured_2.png";
			 													
			 													if(!empty($transaction_hash)) {
				 													$add_properties = "&transactionid=".$transaction_hash;
			 													} else if($_SESSION['transaction']['hash']) {
			 														$add_properties = "&transactionid=".$_SESSION['transaction']['hash'];
			 													}
			 										
			 													
		$page .= "					
																<img src='" . image("url",$tmp_pormotional_logo) . "' border='0'>
			 												</td>																																	 
													
														</tr>
													</table>
													<!-- END TABLE III. (LOGO) -->
											
												</center>
												
												<table style='width:100%; height:auto; margin-top:auto;'>
													<tr>
														<td>
															<span style='
															line-height:" . $_SESSION['template']['company']['email_line_height'] . "; 
															color:" . $_SESSION['template']['company']['email_text_color'] . "; 
															font-family:" . $_SESSION['template']['company']['email_text_face'] . "; 
															font-size:" . $_SESSION['template']['company']['email_text_size'] . ";
															font-weight:" . $_SESSION['template']['company']['email_text_weight'] . ";
															'>
															    <br>
															    " . $message . "<br>
															    <br>" . 
															    return_refund_footer() . "
															</span>
														</td>
													</tr>
												</table>
												
											</td>
										</tr>
									</table>";
									
									$add_to = "page";  // adds text to "page" variable
									$tight_footer_right = "<a href='https://" . $_SESSION['template']['company']['host_support'] . "'>24-Hour, Worldwide Customer Support</a>";
									include($_SESSION['template']['company']['file_path'] . "shared/footer_text.shared");
									
									$page .= "
									

								</td>
							</tr>
						</table>
						
					</td>
				</tr>
			</table>
			
		</center>

	</body>
</html>";

	return $page;
	
}





function return_refund_footer($transactionid=null) {

if(!empty($transactionid)) $add_properties = "?transactionid=".$transactionid;

$tmp_refund_footer = "<table style='width:auto; height:auto; margin-top:auto;'>
    <tr>
    	<td style='padding-top:5px;'>
    		<span style='
    		line-height:" . $_SESSION['template']['company']['email_line_height'] . "; 
    		color:" . $_SESSION['template']['company']['email_text_color'] . "; 
    		font-family:" . $_SESSION['template']['company']['email_text_face'] . "; 
    		font-size:" . $_SESSION['template']['company']['email_text_size'] . ";
    		font-weight:" . $_SESSION['template']['company']['email_text_weight'] . ";
    		'>
    		    <table>
					
					<tr>
						<td>
							<nobr>
								<span style='color:#AA0000; font-weight:bold;'>+</span> <u>REQUEST TO CANCEL / REFUND</u>:
							</nobr>
						</td>
						<td style='text-align:left; padding-left:8px;'>
							<nobr>
								<span class='css_satisfaction_guaranteed'>
									<a href='https://CANCEL-REFUND.".$_SESSION['template']['company']['domain']."/".$add_properties."'>Click here to CANCEL YOUR ORDER / REQUEST A REFUND</a>
								</span>
							</nobr>
						</td>
					</tr>
					
					<tr>
						<td>
							<nobr>
								<span style='color:#AA0000; font-weight:bold;'>+</span> REPORT FRAUD:
							</nobr>
						</td>
						<td style='text-align:left; padding-left:8px;'>
							<nobr>
								<span class='css_satisfaction_guaranteed'>
									<a href='https://REPORT-FRAUD.".$_SESSION['template']['company']['domain']."/".$add_properties."'>Click here to <span  style='font-size:13px;'>REPORT FRAUD</span></a>
								</span>
							</nobr>
						</td>
					</tr>
					
					<tr>
						<td>
							<nobr>
								<span style='color:#AA0000; font-weight:bold;'>+</span> CUSTOMER SERVICE & SUPPORT:
							</nobr>
						</td>
						<td style='text-align:left; padding-left:8px;'>
							<nobr>
								<span class='css_satisfaction_guaranteed'>
									<a href='https://SUPPORT." . $_SESSION['template']['company']['domain'] . "' target='" . $_SESSION['template']['company']['name'] . "'>Click here for CUSTOMER SERVICE & SUPPORT</a>
								</span>
							</nobr>
						</td>
					</tr>
				</table>
    		</span>
    	</td>
    </tr>
</table>";

	return str_replace("\\n", "", $tmp_refund_footer); // set to take out all new line breaks so that the email page formatter doesn't give it crazy spacing issues.

}


###	NETWORK functionS:	###


function member($tmp_memberid) {

	//echo "function MEMBER(tmp_memberid): " . $tmp_memberid;

	/// default, assume memberid
	
	logger3("member(): tmp_memberid",$tmp_memberid);
	
	
	unset($tmp_member);
	logger3("member(): 000. tmp_memberid",$tmp_memberid);
	
	// alternative: emailaddress
	if(
	(stristr($tmp_memberid,"@")) &&
	(stristr($tmp_memberid,"."))
	) {
		$tmp_sql = "SELECT * FROM members WHERE 
		emailaddress = '" . $tmp_memberid . "' AND
		emailaddress != ''
		;";
		$tmp_member = object2array(readTHECASHIER($tmp_sql));
		logger3("1. tmp_sql",$tmp_sql);
		logger3("1. tmp_member",$tmp_member);	
	}

	// alternative: hash
	if(empty($tmp_member['memberid'])) {
		
		$tmp_sql = "SELECT * FROM members WHERE
		hash = '" . $tmp_memberid . "' AND
		hash != '0' AND
		hash != ''
		;";
		$tmp_member = object2array(readTHECASHIER($tmp_sql));
		logger3("3. tmp_sql",$tmp_sql);
		logger3("3. tmp_member",$tmp_member);	
	}
	
	// memberid
	if(empty($tmp_member['memberid'])) {
	
		$tmp_sql = "SELECT * FROM members WHERE 
		memberid LIKE '" . $tmp_memberid . "' AND
		memberid != '0' AND
		memberid != ''
		;";
		logger3("2_member(): tmp_sql",$tmp_sql);
		$tmp_member = object2array(readTHECASHIER($tmp_sql));
		logger3("2_member(): tmp_member",$tmp_member);	
	}


	// alternative: authorization number (counts through all possible country+number confinations)
	if(empty($tmp_member['memberid'])) {
	
		logger("tmp_memberid: " . $tmp_memberid);
		$tmp_possible_phone_number = clean_authorization_number($tmp_memberid);
		logger("tmp_possible_phone_number: " . $tmp_possible_phone_number);
		
		$tmp_number_length = strlen($tmp_possible_phone_number);
		logger("tmp_number_length: " . $tmp_number_length);
		
		if(!$tmp_number_length_base) $tmp_number_length_base = $tmp_number_length; // sets base value for checking
		logger("tmp_number_length_base: " . $tmp_number_length_base);
		
		//sigle-digit calling code:
		$digits_in_calling_code = 1;
		$digits_in_phone_number = $tmp_number_length_base - $digits_in_calling_code;
		logger("1. digits_in_phone_number: " . $digits_in_phone_number);
		
		while( (!$tmp_phone_number['memberid']) && ($digits_in_phone_number > 0) ) {
			
			logger3("2. digits_in_phone_number",$digits_in_phone_number);
			logger3("digits_in_calling_code",$digits_in_calling_code);
			
			// set/update the vars
			$tmp_calling_code = substr($tmp_possible_phone_number, 0, -$digits_in_phone_number);
			$tmp_phone_number = substr($tmp_possible_phone_number, $digits_in_calling_code);

			logger3("tmp_calling_code",$tmp_calling_code);
			logger3("tmp_phone_number",$tmp_phone_number);
			
			/// get the record
			$tmp_sql = "SELECT * FROM phone_numbers WHERE calling_code = '" . $tmp_calling_code . "' AND number = '" . $tmp_phone_number . "';";
			$tmp_phone_number = object2array(readTHECASHIER($tmp_sql));
			logger3("tmp_phone_number",$tmp_phone_number);

			/// set to try again
			$digits_in_calling_code++;
			$digits_in_phone_number = $tmp_number_length_base - $digits_in_calling_code;
		}
		
		logger3("tmp_phone_number['memberid']",$tmp_phone_number['memberid']);
		
		if($tmp_phone_number['memberid'] > 0) {
			$tmp_phone_number = object2array(readTHECASHIER($tmp_sql));
			$tmp_member = object2array(readTHECASHIER("SELECT * FROM members WHERE memberid = '" . $tmp_phone_number['memberid'] . "'"));
		}	
	}
	
	logger3("10. tmp_member",$tmp_member);	
	logger3("10. tmp_member['memberid']",$tmp_member['memberid']);
	
	
	
	// alternative: authorization number (check whole number against number field only (dumbass left-out the country code)
	if(empty($tmp_member['memberid'])) {
	
		logger3("A11. tmp_memberid",$tmp_memberid);
		if($tmp_memberid > 0) {
		
			$tmp_possible_phone_number = clean_authorization_number($tmp_memberid);
			logger3("A11. tmp_possible_phone_number",$tmp_possible_phone_number);
			
			if($tmp_possible_phone_number) {
				$tmp_sql = "SELECT * FROM phone_numbers WHERE number = '" . $tmp_possible_phone_number . "';";
				$tmp_phone_number = object2array(readTHECASHIER($tmp_sql));
				logger3("11. tmp_sql",$tmp_sql);
				logger3("11. tmp_phone_number",$tmp_phone_number);
			}
			
			if($tmp_phone_number['memberid'] > 0) {
				
				$tmp_member = object2array(readTHECASHIER("SELECT * FROM members WHERE memberid = '" . $tmp_phone_number['memberid'] . "';"));
				logger3("11. tmp_sql",$tmp_sql);
				logger3("11. tmp_member",$tmp_member);
			}
		}
	}
	
	

	### :LEGACY: GET NUMBER OF ACCUONTS:
	//$tmp_member['accounts'] = arrayTHECASHIER("SELECT accountid FROM permissions WHERE memberid = '" . $tmp_member['memberid'] . "'");

	### :NEW: GET PERSONAL ACCOUNT:
	if(!empty($tmp_member['memberid'])) {
	
		$tmp_sql = "SELECT accountid 
					FROM accounts 
					WHERE
					creator_memberid = '" . $tmp_member['memberid'] . "' AND
					creator_memberid != '0' AND
					creator_memberid != '' AND
					accounttype = 'PERSONAL'
					;";
		//test("tmp_sql",$tmp_sql);
		
		$tmp_member['accounts']['personal'] = getTHECASHIER($tmp_sql);

		logger3("100. tmp_sql",$tmp_sql);
		logger3("100. tmp_member",$tmp_member);	
	}	
		
		
	//test("tmp_member['memberid']",$tmp_member['memberid']);
	//logger3("tmp_sql",$tmp_sql);
	//test("tmp_member['accounts']['personal']",$tmp_member['accounts']['personal']);
	
	### :NEW: GET BUSINESS ACCOUNT(S):
	if(!empty($tmp_member['memberid'])) {
	
		$tmp_sql = "SELECT accountid FROM permissions WHERE 
		memberid = '" . $tmp_member['memberid'] . "' AND 
		memberid != '0' AND
		memberid != '' AND
		accounttype = 'BUSINESS' AND 
		permissions = 'MASTER' AND 
		(admin = '' OR admin IS NULL)
		;";
		$tmp_results = arrayTHECASHIER($tmp_sql);
		if(!empty($tmp_results[0])) $tmp_member['accounts']['business'] = $tmp_results;
		unset($tmp_results);
	}
	
	//logger3("tmp_sql",$tmp_sql);
	//test("tmp_member['accounts']['business']",$tmp_member['accounts']['business']);

	### :NEW: GET SHARED ACCOUNT(S):
	if(!empty($tmp_member['memberid'])) {
	
		$tmp_sql = "SELECT accountid FROM permissions WHERE 
		memberid = '" . $tmp_member['memberid'] . "' AND 
		memberid != '0' AND 
		memberid != '' AND 
		accounttype = 'SHARED' AND 
		status != 'SELF' AND 
		status != 'DELETED'
		;";
		$tmp_results = arrayTHECASHIER($tmp_sql);	
		if($tmp_results[0]) $tmp_member['accounts']['shared'] = $tmp_results;
		unset($tmp_results);
	}
	
	### :NEW: GET ADMIN ACCOUNT(S):
	if(!empty($tmp_member['memberid'])) {
	
		$tmp_results = arrayTHECASHIER("SELECT accountid FROM permissions WHERE 
		memberid = '" . $tmp_member['memberid'] . "' AND 
		memberid != '0' AND 
		memberid != '' AND 
		admin != 'NULL' AND 
		admin != '' AND 
		admin IS NOT NULL
		;");	
		if($tmp_results[0]) $tmp_member['accounts']['admin'] = $tmp_results;
		unset($tmp_results);
	}
	
	### SET MULTIPLE ACCOUNTS
	//test("tmp_member['accounts']['admin']",$tmp_member['accounts']['admin']);
	//test("tmp_member['accounts']['shared']",$tmp_member['accounts']['shared']);
	//test("tmp_member['accounts']['business']",$tmp_member['accounts']['business']);
	
	$admin_count = count($tmp_member['accounts']['admin']);
	$shared_count = count($tmp_member['accounts']['shared']);
	$business_count = count($tmp_member['accounts']['business']);
	//test("admin_count",$admin_count);
	//test("shared_count",$shared_count);
	//test("business_count",$business_count);
	
	if( $admin_count + $shared_count + $business_count > 1) {
		$tmp_member['accounts']['multiple'] = "YES";	
	}
	
	
	if(stristr($_SESSION['template']['company']['client'],"vocaONE")) {
		$KYC_DENTITY = "OFF";
	} else {
		$KYC_DENTITY = "ON";
	}
	
	if($KYC_DENTITY == "ON") {
		################################################################################
		## CURRENT member identity
		$verified_member_identity_details = "";
		// $tmp_sql = "SELECT * FROM ids_personal 
		// 			WHERE memberid = '". $tmp_member['memberid'] ."' 
		// 			AND photo_id_filename != '' 
		// 			AND photo_id_filename IS NOT NULL 
		// 			AND status != 'CLEARED'
		// 			ORDER BY datetime_updated DESC
		// 			LIMIT 1
		// 			;";
		$tmp_sql = "SELECT * FROM ids_personal 
		    	WHERE 
		    	
		    	memberid = '". $tmp_member['memberid'] ."' AND
		    	memberid != '0' AND
		    	memberid != '' AND
		    	photo_id_filename != '' AND
		    	photo_id_filename IS NOT NULL 
		    	ORDER BY datetime_updated DESC
		    	LIMIT 1
		    	;";
		//test("tmp_sql",$tmp_sql);
		$tmp_member['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
		//test("tmp_member['current']['identity']",$tmp_member['current']['identity']);
		
		
		## CURRENT member location
		$verified_member_location_details = "";
		// $tmp_sql = "SELECT * FROM ids_personal 
		// 			WHERE memberid = '". $tmp_member['memberid'] ."' 
		// 			AND proof_of_residence_filename != '' 
		// 			AND proof_of_residence_filename IS NOT NULL
		// 			AND status != 'CLEARED'
		// 			ORDER BY datetime_updated DESC
		// 			LIMIT 1
		// 			;";
		$tmp_sql = "SELECT * FROM ids_personal 
		    		WHERE 
		    		
		    		memberid = '". $tmp_member['memberid'] ."' AND
		    		memberid = '0' AND
		    		memberid = '' AND
		    		
		    		proof_of_residence_filename != '' AND
		    		proof_of_residence_filename IS NOT NULL
		    		ORDER BY datetime_updated DESC
		    		LIMIT 1
		    		;";
		//test("tmp_sql",$tmp_sql);
		$tmp_member['current']['location'] = object2array(readTHECASHIER($tmp_sql));
		//test("tmp_member['current']['location']",$tmp_member['current']['location']);
		################################################################################
			
			
			
		####	################################################################################
		####	## VERIFIED member identity
		####	$verified_member_identity_details = "";
		####	$tmp_sql = "SELECT * FROM ids_personal 
		####				WHERE memberid = '". $tmp_member['memberid'] ."' 
		####				AND photo_id_filename != '' 
		####				AND photo_id_filename IS NOT NULL 
		####				AND status = 'VERIFIED'
		####				ORDER BY datetime_updated DESC
		####				LIMIT 1
		####				;";
		####	//test("tmp_sql",$tmp_sql);
		####	$tmp_member['verified']['identity'] = object2array(readTHECASHIER($tmp_sql));
		####	//test("tmp_member['verified']['identity']",$tmp_member['verified']['identity']);
		####	
		####	
		####	## VERIFIED member location
		####	$verified_member_location_details = "";
		####	$tmp_sql = "SELECT * FROM ids_personal 
		####				WHERE memberid = '". $tmp_member['memberid'] ."' 
		####				AND proof_of_residence_filename != '' 
		####				AND proof_of_residence_filename IS NOT NULL 
		####				AND status = 'VERIFIED'
		####				ORDER BY datetime_updated DESC
		####				LIMIT 1
		####				;";
		####	//test("tmp_sql",$tmp_sql);
		####	$tmp_member['verified']['location'] = object2array(readTHECASHIER($tmp_sql));
		####	//test("tmp_member['verified']['location']",$tmp_member['verified']['location']);
		####	################################################################################
	
	} /// END KYC IDENTITY
	
	
	
	
	## authorization_number
	$tmp_authorization_details = authorization_number($tmp_member['memberid']);
	$tmp_member['authorization_number'] = $tmp_authorization_details['clean_number'];
	$tmp_member['authorization_number_details'] = $tmp_authorization_details;
	
	
	return $tmp_member;

}


function account($tmp_accountid) {

	logger("FUNCTION: account()");
	//global $member; # note: member must be set first i guess?
	#test("accountid",$accountid);
	//global $_SESSION;
	
	logger3("tmp_accountid",$tmp_accountid);
	unset($tmp_account);
	
	// email address
	if(
	(stristr($tmp_accountid,"@")) &&
	(stristr($tmp_accountid,"."))
	) {
		$tmp_sql = "SELECT * FROM accounts WHERE emailaddress = '" . $tmp_accountid . "';";
		$tmp_account = object2array(readTHECASHIER($tmp_sql));
		logger3("tmp_sql",$tmp_sql);
		//exit;
		logger3("tmp_account",$tmp_account);
		
		### FIRST LOOKUP FAILED -- TRY SYSTEM_EMAIL_ACCOUNT
		if(empty($tmp_account['accountid'])) {
		
			$tmp_exploded_account_address = explode("@",$tmp_accountid);
			
		
			$tmp_sql = "SELECT accountid FROM email_accounts WHERE 
				username = '" . $tmp_exploded_account_address[0] . "'
				AND host = '" . $tmp_exploded_account_address[1] . "';";
			$tmp_accountid_ii = getTHECASHIER($tmp_sql);
			logger3("tmp_sql",$tmp_sql);
			logger3("tmp_accountid_ii",$tmp_accountid_ii);
			
			if(!empty($tmp_accountid_ii)) {
				$tmp_sql = "SELECT * FROM accounts WHERE accountid LIKE '" . $tmp_accountid_ii . "';";
				$tmp_account = object2array(readTHECASHIER($tmp_sql));
				logger3("tmp_sql",$tmp_sql);
				logger3("tmp_account",$tmp_account);
				
				## add system email account:
				$tmp_account['email_account'] = $tmp_account['system_email_account'] = $tmp_accountid; // was actually using the system account
			}
		
		### IT WAS AN BUSINESS ACCOUNT EMAIL ADDRESS
		} else {
			$tmp_sql = "SELECT * FROM email_accounts WHERE 
				accountid = '" . $tmp_account['accountid'] . "'
				AND status = 'ACTIVE';";
			$tmp_account_address_details = object2array(readTHECASHIER($tmp_sql));
			logger3("tmp_sql",$tmp_sql);
			logger3("tmp_account_address_details",$tmp_account_address_details);
			
			## add system email account:
			$tmp_account['email_account'] = $tmp_account['system_email_account'] = strtoupper($tmp_account_address_details['username']) . "@" . strtolower($tmp_account_address_details['host']);
		}
		
		
			
			
	}

	// hash
	if(
	(!isset($tmp_account['accountid']))
	) {
		$tmp_sql = "SELECT * FROM accounts WHERE hash = '" . $tmp_accountid . "';";
		$tmp_account = object2array(readTHECASHIER($tmp_sql));
		logger3("tmp_sql",$tmp_sql);
		logger3("tmp_account",$tmp_account);	
	}
	
	
	// accountid
	if(
	(!isset($tmp_account['accountid']))
	) {
		$tmp_sql = "SELECT * FROM accounts WHERE accountid LIKE '" . $tmp_accountid . "';";
		$tmp_account = object2array(readTHECASHIER($tmp_sql));
		logger3("tmp_sql",$tmp_sql);
		logger3("tmp_account",$tmp_account);	
	}



    if(is_array($_SESSION['member'])){            
        if($_SESSION['member']['memberid']) {

                $tmp_sql = "SELECT admin FROM permissions WHERE memberid = '" . $_SESSION['member']['memberid'] . "' AND accountid LIKE '" . $tmp_account['accountid'] . "';";
                $tmp_account['admin'] = getTHECASHIER($tmp_sql);
                logger("tmp_account['admin']..."); logger($tmp_account['admin']);
        }
    }
	
	
	//$tmp_balance = balance($tmp_account['accountid']);
	
	//$tmp_account['balance'] = $tmp_balance['balance'];
	
	
	### extract "transaction_their_fee"
	$tmp_account['transaction_fee_their'] = number_format($tmp_account['transaction_fee_total'] - $tmp_account['transaction_fee_my'],3);
	

	### ADD EMAIL ACCOUNT:
	$tmp_sql = "SELECT * FROM email_accounts WHERE accountid LIKE '".$tmp_account['accountid']."';";
	//logger3("tmp_sql",$tmp_sql);
	$tmp_account['email_account'] = object2array(readTHECASHIER($tmp_sql));
	$tmp_account['email_account_address'] = $tmp_account['email_account']['username']."@".$tmp_account['email_account']['host'];
	//test("tmp_account",$tmp_account);
	
	
	$KYC_IDENTITY = "ON";
	if(stristr($_SESSION['template']['company']['client'],"VOCAONE")) $KYC_IDENTITY == "OFF";
	if($KYC_IDENTITY == "ON"){
		
		###################################################
		### PDBA 
		###################################################
		if(
		(stristr($tmp_account['accounttype'],"PERSONAL")) ||
		(stristr($tmp_account['business_type'],"PDBA")) ||
		(stristr($tmp_account['business_type'],"GROUP"))
		) {
		
		  //$creator_member_details = member($tmp_account['creator_memberid']);
		  //test("creator_member_details",$creator_member_details);
		  //$tmp_account['verified']['location'] = $creator_member_details['verified']['location'];
		 // test("tmp_account['verified']['location']",$tmp_account['verified']['location']);
		  
		  
		  //$tmp_account['verified']['identity'] = $creator_member_details['verified']['identity'];
		  //test("tmp_account['verified']['identity']",$tmp_account['verified']['identity']);
		  
	
		  $tmp_get_ids_personal = get_ids_personal($memberid=$tmp_account['creator_memberid'],$accountid='');
		  
		  $tmp_account['current'] = $tmp_get_ids_personal['current'];
		
		
		
		
		
		
		###################################################
		### CDBA 
		###################################################
		### } else if(
		### (stristr($tmp_account['business_type'],"CDBA"))
		### ) {
		###   
		###   $parent_hash = get_cdba_parent($tmp_account['accountid']);
		###   $parent_details = account($parent_hash);
		###   $parent_accountid = $parent_details['accountid'];
		###   		
		###   $tmp_sql = "SELECT * FROM ids_business 
		###   			WHERE accountid = '". $tmp_account['accountid'] ."'
		###   			;";
		###   
	###	###   ### VERIFIED IDENTITY
	###	###   $tmp_sql = "SELECT * FROM ids_business 
	###	###   WHERE 
	###	###   accountid = '". $parent_accountid ."' 
	###	###   AND business_certificate_filename != '' 
	###	###   AND business_certificate_filename IS NOT NULL 
	###	###   AND status = 'VERIFIED'
	###	###   ORDER BY datetime_updated DESC
	###	###   ;";
	###	###   logger3("tmp_sql",$tmp_sql);
	###	###   $tmp_account['verified']['identity'] = object2array(readTHECASHIER($tmp_sql));
	###	###   logger3("tmp_account['verified']['identity']",$tmp_account['verified']['identity']);
		### 
		###   ### CURRENT IDENTITY
		###   $tmp_sql = "SELECT * FROM ids_business 
		###   WHERE 
		###   accountid = '". $parent_accountid ."' 
		###   AND 
		###   (
		###   (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL) OR
		###   (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		###   )
		###   AND business_name = '". $tmp_account['accountname'] ."'
		###   AND status != 'CLEARED'
		###   ORDER BY datetime_updated DESC
		###   ;";
		###   
		###   logger3("tmp_sql",$tmp_sql);
		###   $tmp_account['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
		###   logger3("tmp_account['current']['identity']",$tmp_account['current']['identity']);
		###   
		###   
		###   
	###	###   ### VERIFIED LOCATION
	###	###   $tmp_sql = "SELECT * FROM ids_business 
	###	###   WHERE 
	###	###   accountid = '". $parent_accountid ."' 
	###	###   AND proof_of_business_location_filename != '' 
	###	###   AND proof_of_business_location_filename IS NOT NULL 
	###	###   AND status = 'VERIFIED'
	###	###   ORDER BY datetime_updated DESC
	###	###   ;";
	###	###   logger3("tmp_sql",$tmp_sql);
	###	###   $tmp_account['verified']['location'] = object2array(readTHECASHIER($tmp_sql));
	###	###   logger3("tmp_account['verified']['location']",$tmp_account['verified']['location']);
		### 
		###   ### CURRENT LOCATION
		###   $tmp_sql = "SELECT * FROM ids_business 
		###   WHERE 
		###   accountid = '". $parent_accountid ."' 
		###   AND 
		###   ( 
		###   (AND proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL) OR
		###   (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		###   )
		###   AND business_name = '". $tmp_account['accountname'] ."'
		###   AND status != 'CLEARED'
		###   ORDER BY datetime_updated DESC
		###   ;";
		###   
		###   //test("tmp_sql",$tmp_sql);
		###   $tmp_account['current']['location'] = object2array(readTHECASHIER($tmp_sql));
		###   //test("tmp_account['current']['location']",$tmp_account['current']['location']);
		  
		  
		  
		###################################################
		### REGISTERED COMPANY 
		###################################################
		} else {
		  
		  
		  
	###	  ### VERIFIED IDENITITY
	###	  $tmp_sql = "SELECT * FROM ids_business 
	###	  WHERE 
	###	  accountid = '".$tmp_account['accountid']."' 
	###	  AND business_certificate_filename != '' 
	###	  AND business_certificate_filename IS NOT NULL 
	###	  AND status = 'VERIFIED'
	###	  ORDER BY datetime_updated DESC
	###	  ;";
	###	  //test("tmp_sql",$tmp_sql);
	###	  $tmp_account['verified']['identity'] = object2array(readTHECASHIER($tmp_sql));
	###	  //test("tmp_account['verified']['identity']",$tmp_account['verified']['identity']);
	
		  ### ### CURRENT IDENTITY
		  ### $tmp_sql = "SELECT * FROM ids_business 
		  ### WHERE 
		  ### accountid = '". $tmp_account['accountid'] ."' 
		  ### AND 
		  ### (
		  ### (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL) OR
		  ### (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		  ### )
		  ### AND business_name = '". $tmp_account['accountname'] ."'
		  ### AND status != 'CLEARED'
		  ### ORDER BY datetime_updated DESC
		  ### ;";
		  ### 
		  ### //test("tmp_sql",$tmp_sql);
		  ### $tmp_account['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
		  ### //test("tmp_account['current']['identity']",$tmp_account['current']['identity']);
		  ### 
		  ### 
		  ### 
	###	  ### ### VERIFIED LOCATION
	###	  ### $tmp_sql = "SELECT * FROM ids_business 
	###	  ### WHERE 
	###	  ### accountid = '".$tmp_account['accountid']."' 
	###	  ### AND proof_of_business_location_filename != '' 
	###	  ### AND proof_of_business_location_filename IS NOT NULL 
	###	  ### AND status = 'VERIFIED'
	###	  ### ORDER BY datetime_updated DESC
	###	  ### ;";
	###	  ### //test("555. tmp_sql",$tmp_sql);
	###	  ### $tmp_account['verified']['location'] = object2array(readTHECASHIER($tmp_sql));
	###	  ### //test("555. tmp_account['verified']['location']",$tmp_account['verified']['location']);
		  ### 
		  ### ### CURRENT LOCATION
		  ### $tmp_sql = "SELECT * FROM ids_business 
		  ### WHERE 
		  ### accountid = '". $tmp_account['accountid'] ."' 
		  ### AND proof_of_business_location_filename != '' 
		  ### AND proof_of_business_location_filename IS NOT NULL
		  ### AND status != 'CLEARED'
		  ### ORDER BY datetime_updated DESC
		  ### ;";
		  ### 
		  ### //test("tmp_sql",$tmp_sql);
		  ### $tmp_account['current']['location'] = object2array(readTHECASHIER($tmp_sql));
		  ### //test("tmp_account['current']['location']",$tmp_account['current']['location']);
		  
		  
		  $tmp_ids_business = get_ids_business($memberid='',$accountid=$tmp_account['accountid']);
		  $tmp_account['current'] = $tmp_ids_business['current'];
		  
		  
		  
		  
		  
		  
		  
		}
		
		
		## ###################################################
		## ### CDBA
		## ###################################################
		## 
		## ### IF NOT, TRY CBDA:
		## if(empty($tmp_account['verified']['identity'])) {
		## 
		## 	logger3("999. tmp_accountid",$tmp_account['accountid']);
		## 	
		## 	$parent_hash = get_cdba_parent($tmp_account['accountid']);
		## 	//if(empty($parent_hash)) $parent_hash = $tmp_account['hash']; // IS PDBA
		## 	
		## 	$parent_accountid = getTHECASHIER("SELECT accountid FROM accounts WHERE hash = '". $parent_hash ."';");
		## 		 
		## 	logger3("999. parent_accountid",$parent_accountid);
		## 	//exit;
		## 	
		## 			} else { // TRY PDBA:
		## 	
		## 
		## 	
		## 	
		## 	}
		## 	
		## } else {
		## 	logger3("888. tmp_account['verified']",$tmp_account['verified']);
		## }
		
		
		// #### VERIFIED IDENTITY:
		// if(stristr($tmp_account['accounttype'],"PERSONAL")) {
		// 
		// 	$tmp_get_personal_identity = get_personal_identity($tmp_account['accountid']);
		// 	$tmp_account['verified']['identity'] = $tmp_get_personal_identity['verified'];
		// 
		// } else { // BUSINESS:
		// 
		// 	$tmp_get_business_identity = get_business_identity($tmp_account['accountid']);
		// 	test("tmp_get_business_identity",$tmp_get_business_identity);
		// 	$tmp_account['verified']['identity'] = $tmp_get_business_identity['verified'];
		// }
		// 
		// #### VERIFIED LOCATION:
		// if(stristr($tmp_account['accounttype'],"PERSONAL")) {
		// 
		// 	$tmp_get_personal_location = get_personal_location($tmp_account['accountid']);
		// 	$tmp_account['verified']['location'] = $tmp_get_personal_location['verified'];
		// 
		// } else { // BUSINESS:
		// 
		// 	$tmp_get_business_location = get_business_location($tmp_account['accountid']);
		// 	test("tmp_get_business_location",$tmp_get_business_location);
		// 	$tmp_account['verified']['location'] = $tmp_get_business_location['verified'];
		// }
	
	} /// END KYC IDENTITY


	### FEE AND SCHEDULE PROFILE
	// $tmp_sql = "SELECT * FROM fee_and_schedule_profiles 
	// 			WHERE 
	// 			profile_name = '". $tmp_account['fee_and_schedule_profile'] ."'
	// 			;";
	// logger3("tmp_sql",$tmp_sql);
	// $tmp_account['fee_and_schedule_profile'] = object2array(readTHECASHIER($tmp_sql));
	// logger3("tmp_results",$tmp_results);

	if(stristr($_SESSION['template']['company']['client'],"VOCAONE")) {
		$table_name = 'vocasign';
                if(stristr($_SESSION['template']["company"]["text_name"],"vocaPASS")) {
                    $table_name = 'vocapass_preferences'; 
                }
		$tmp_sql = "SELECT * FROM ".$table_name." WHERE accountid = '".  $tmp_account['accountid']  ."';";
		$tmp_account['vocasign'] = object2array(readTHECASHIER($tmp_sql));
		
	} else {
			
		$tmp_account['dynamic_processing_profile'] = get_dynamic_processing_profile();
		$tmp_account['DTR'] = $tmp_account['days_to_release'] = get_dynamic_DTR($tmp_account['accountid']);
		$tmp_account['DPF'] = $tmp_account['dynamic_processing_fee'] = get_dynamic_fee_for_this_account($tmp_account['accountid']);

		
	}


	### return info
	logger3("tmp_account",$tmp_account);
	return $tmp_account;	
}


function permissions($tmp_memberid,$tmp_accountid) {
		
		#//test("memberid",$memberid);
		#//test("accountid",$accountid);
		
		# this is an important security check to be sure that the member has access to the account.
		# if the member does nt have permission, account will return NULL
		# was orginally in aaccount() but that prevented administrative fucntions from retriving account info
	
	$tmp_sql = "SELECT * FROM permissions WHERE memberid = '" . $tmp_memberid . "' AND accountid LIKE '" . $tmp_accountid . "';";
	
	//logger3("tmp_sql",$tmp_sql);
	
 	$tmp_permissions = object2array(readTHECASHIER($tmp_sql));
 	
 	//test("tmp_permissions",$tmp_permissions);
 	
 	if(
 	($tmp_permissions['accounttype'] == "Shared") ||
 	(strtoupper($tmp_permissions['permissions']) != "MASTER")
 	) {
	 	 $tmp_permissions['permissions'] = explode(",",$tmp_permissions['permissions']);
	}
	
	return $tmp_permissions;

}



function permissions_shared($tmp_memberid,$tmp_accountid) {
		
		#//test("memberid",$memberid);
		#//test("accountid",$accountid);
		
		# this is an important security check to be sure that the member has access to the account.
		# if the member does nt have permission, account will return NULL
		# was orginally in aaccount() but that prevented administrative fucntions from retriving account info
	
	$tmp_sql = "SELECT * FROM permissions WHERE memberid = '" . $tmp_memberid . "' AND accountid LIKE '" . $tmp_accountid . "' AND permissions != 'MASTER';";
	
	//logger3("tmp_sql",$tmp_sql);
	
 	$tmp_permissions = object2array(readTHECASHIER($tmp_sql));
 	
 	//test("tmp_permissions",$tmp_permissions);
 	
 	if(($tmp_permissions['permissions'] != "MASTER") && ($tmp_permissions['permissions'] != "") && ($tmp_permissions['permissions'] != " ")) {
	 	 $tmp_permissions['permissions'] = explode(",",$tmp_permissions['permissions']);
	}
	
	return $tmp_permissions;

}



### HTML/HTTPS PAGE BASICS: ###

function http($server_port) {
	if($server_port == "80") {
		return "http://";
	} else {
		return "https://";
	}
}


	
	
	
function template($domain_name,$wildcard=false) {

	global $master_config_session_logging;
	if(stristr($master_config_session_logging,"ON")) logger3("template(): domain_name",$domain_name);
	if(stristr($master_config_session_logging,"ON")) logger3("template(): wildcard",$wildcard);
	//if(stristr($master_config_session_logging,"ON")) logger3("template(): domain_name",$domain_name);
	
	//echo $_SERVER['HTTP_HOST'];
	//test("client",$client);
	//test("domain_name",$domain_name);

	global $master_config_database_company_template;
	//test("1. master_config_database_company_template",$master_config_database_company_template);
	$tmp_domain = explode(".",$_SERVER['HTTP_HOST']);
	
	if($tmp_domain[4]) {
		$tmp_host = $tmp_domain[3] . "." . $tmp_domain[4];
	} else if($tmp_domain[3]) {
		$tmp_host = $tmp_domain[2] . "." . $tmp_domain[3];
	} else if($tmp_domain[2]) {
		$tmp_host = $tmp_domain[1] . "." . $tmp_domain[2];
	} else {
		$tmp_host = $_SERVER['HTTP_HOST'];
	}
	
	$tmp_host = strtolower($tmp_host);
	//test("tmp_host",$tmp_host);
	
	if(!empty($domain_name)) $tmp_host = $domain_name;
	
	### NSDB FIX
	if($wildcard == true) {
		$tmp_sql = "SELECT templateid FROM templates_companies WHERE domain LIKE '%" . $tmp_host . "';";
	} else {
		$tmp_sql = "SELECT templateid FROM templates_companies WHERE domain = '" . $tmp_host . "';";
	}
	
	//test("tmp_sql",$tmp_sql);
	$tmp_templateid = getTHECASHIER($tmp_sql);
	//test("tmp_templateid",$tmp_templateid);	
	if(
	($tmp_templateid != NULL) &&
	($domain_name != "blingk.nsdb-demo.com") &&
	($domain_name != "blingk.nsdb-development.com")
	){
		$domain_name = $tmp_host;
	} else {
		$domain_name = strtolower($master_config_database_company_template);
	}
	
	//test("domain_name",$domain_name);
	//test("client",$client);
	

	### DEFINE VARS:
	$_SESSION['template'] = $template = NULL;
	$_SESSION['template'] = $template = array();
	
	
	### FIRST GET COMPAANY TEMPLATE:
	if($wildcard == true) {
		$_SESSION['template']['company'] = object2array(readTHECASHIER("SELECT * FROM templates_companies WHERE domain LIKE '%" . $domain_name . "';"));
	} else {
		$_SESSION['template']['company'] = object2array(readTHECASHIER("SELECT * FROM templates_companies WHERE domain = '" . $domain_name . "';"));
	}
	
	if(stristr($master_config_session_logging,"ON")) logger3("template(): _SESSION['template']['company']",$_SESSION['template']['company']);
	//test("_SESSION['template']['company']",$_SESSION['template']['company']);
	
	### NOW GET HTML TEMPLATES:
	$templateid = "";
	$templateid = array();
	$templateid = arrayTHECASHIER("SELECT templateid FROM templates_pages WHERE client = 'BANGK!'");
	
	if(stristr($master_config_session_logging,"ON")) logger3("template(): templateid",$templateid);
	
	$i = 0;
	while($templateid[$i]) {
		$template_html = "";
		$template_html = array();
		$template_html = object2array(readTHECASHIER("SELECT * FROM templates_pages where templateid LIKE '" . $templateid[$i] . "'"));
		$template_name = $template_html['template'];
		$_SESSION['template'][$template_name] = $template_html;
		$i = $i + 1;
	}
	
	if(stristr($master_config_session_logging,"ON")) logger3("template(): 999 _SESSION['template']",$_SESSION['template']);
	
	if(isset($_SESSION['template'])) {
		return $_SESSION['template'];
	} else {
		return 0;
	}
}
		
 

function readTemplate($HTTP_HOST,$template) {
	
	include("/BANGK!/shared/database_config.shared");
	
	$mysql = mysql_pconnect($mysqlhost,$mysqluser,$mysqlpass); # opens persistent connection
	mysql_select_db($name_of_database);
	
	$host = $HTTP_HOST; 
	$result = mysql_query("SELECT * FROM templates where host = '$host' AND template = '$template'");
	if($result) {
		$user = mysql_fetch_object($result); 
		return $user; 
	} else {
		return 0; 
	}
}

 

	

	
	



function image($route_to_image,$image_file_name) {
	
	//global $template;
	
	if($route_to_image == "local") {
		$final_path =  "/link_images/" . $image_file_name;
	} else {
		$final_path = "https://" . $_SESSION['template']['company']['host_images'] . "/" . $image_file_name;
	}
	
	return $final_path;
}


function imgsrc($image,$path,$height="") {
	global $template;
	if(!$path) {
		return "<img src='https://" . $_SESSION['template']['company']['host_images'] . "/" . $image . "' style='height:$height;'>";
	} else if($path == "local") {
		return "<img src='./link_images/" . $image . "' style='height:$height;'>";
	}
}


function support_popup($questionid) {
	return "<a href='javascript:openSUPPORT(" . $questionid . ");'>" . img("popup") . "</a>";
}



function display_image($image_file,$vertical_align) {
	//test("vertical_align",$vertical_align);
	global $http;
	global $template;
	if(!$vertical_align) {
		$vertical_align = "top";
	}
	//test("vertical_align",$vertical_align);
	return "<img src='" . $http . $_SESSION['template']['company']["host_images"] . "/" . $image_file . "' border='0' style='vertical-align:" . $vertical_align . ";'>";
}


function link_images($filename,$vertical_align) {
	return "<img src='./link_images/" . $image_file . "' border='0' style='vertical-align:" . $vertical_align . ";'>";
}

function start_bold($bold) {
	if($bold) { return "<b>"; }
}

function end_bold($bold) {
	if($bold) { return "</b>"; }
}

function requiredImgField($required,$variable, $imgId) {
	global $template;
	global $http;
	
	if($required == "no") {
		//return "<img name=\"$imgId\" id=\"$imgId\" src='" . image("local",$_SESSION['template']['company'][icon3]) . "' border=0>"; ## un-checked
		return "<span style='font-family:verdana; font-size:9px; color:#777777; font-weight:normal;'>(optional)<span>";
	}
	if(($required == "yes") && (!$variable)) {
		return "<img name=\"$imgId\" id=\"$imgId\" src='" . image("local",$_SESSION['template']['company']['icon2']) . "' border=0>"; ## red-checked
	}
	if(($required == "yes") && ($variable)) {
		return "<img name=\"$imgId\" id=\"$imgId\" src='" . image("local",$_SESSION['template']['company']['icon5']) . "' border=0>"; ## un-checked
	}
	if($required == "green") {
		return "<img name=\"$imgId\" id=\"$imgId\" src='" . image("local",'check_green_v4.gif') . "' border=0>"; ## green-checked
	}
	if($required == "none") {
		return "";
	}
	if($required == "open") {
		return "<img name=\"$imgId\" id=\"$imgId\" src='" . image("local",$_SESSION['template']['company']['icon3']) . "' border=0>";
	}
}


function required($required,$variable) {
	global $template;
	global $http;
	
	if($required == "no") {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon3]) . "' border=0>"; ## un-checked
	}
	if(($required == "yes") && (!$variable)) {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon2]) . "' border=0>"; ## red-checkd
	}
	if(($required == "yes") && ($variable)) {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon3]) . "' border=0>"; ## un-checkd
	}
	if(($required == "ok")) {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon5]) . "' border=0>"; ## un-checkd
	}
	
	
}

function requiredGW($required,$variable) {
	global $template;
	global $http;
	
	if($required == "no") {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon5]) . "' border=0>"; ## un-checked
	}
	if(($required == "yes") && (!$variable)) {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon13]) . "' border=0>"; ## red-checkd
	}
	if(($required == "yes") && ($variable)) {
		return "<img src='" . image("local",$_SESSION['template']['company'][icon5]) . "' border=0>"; ## un-checkd
	}
}





function numberme($page_row,$index,$index_row) {

	$page_row = ""; #none at the moment
	$index = "";
/*
	if($index == "0") {	$index = ""; }
	if($index == "1") {	$index = "i."; }
	if($index == "2") {	$index = "ii."; }
	if($index == "3") {	$index = "iii."; }
	if($index == "4") {	$index = "iv."; }
	if($index == "5") {	$index = "v."; }
	if($index == "6") {	$index = "vi."; }
	if($index == "7") {	$index = "vii."; }
	if($index == "8") {	$index = "viii."; }
	if($index == "9") {	$index = "ix."; }
	if($index == "10") {	$index = "x."; }
	if($index == "11") {	$index = "xi."; }
	if($index == "12") {	$index = "xii"; }
	if($index == "13") {	$index = "xiii."; }
	if($index == "14") {	$index = "xiv."; }
	if($index == "15") {	$index = "xv."; }
	if($index == "16") {	$index = "xvi."; }
	if($index == "17") {	$index = "xvii."; }
	if($index == "18") {	$index = "xviii."; }
	if($index == "19") {	$index = "xix."; }
	if($index == "20") {	$index = "xx."; }
	
	if($index_row == "0") {	$index_row = ""; }
	if($index_row == "1") {	$index_row = "a"; }
	if($index_row == "2") {	$index_row = "b"; }
	if($index_row == "3") {	$index_row = "c"; }
	if($index_row == "4") {	$index_row = "d"; }
	if($index_row == "5") {	$index_row = "e"; }
	if($index_row == "6") {	$index_row = "f"; }
	if($index_row == "7") {	$index_row = "g"; }
	if($index_row == "8") {	$index_row = "h"; }
	if($index_row == "9") {	$index_row = "i"; }
	if($index_row == "10") {	$index_row = "j"; }
	if($index_row == "11") {	$index_row = "k"; }
	if($index_row == "12") {	$index_row = "l"; }
	if($index_row == "13") {	$index_row = "m"; }
	if($index_row == "14") {	$index_row = "n"; }
	if($index_row == "15") {	$index_row = "o"; }
	if($index_row == "16") {	$index_row = "p"; }
	if($index_row == "17") {	$index_row = "q"; }
	if($index_row == "18") {	$index_row = "r"; }
	if($index_row == "19") {	$index_row = "s"; }
	if($index_row == "20") {	$index_row = "t"; }

*/
	if($index_row == "0") {	$index_row = ""; }
	if($index_row == "1") {	$index_row = "1)"; }
	if($index_row == "2") {	$index_row = "2)"; }
	if($index_row == "3") {	$index_row = "3)"; }
	if($index_row == "4") {	$index_row = "4)"; }
	if($index_row == "5") {	$index_row = "5)"; }
	if($index_row == "6") {	$index_row = "6)"; }
	if($index_row == "7") {	$index_row = "7)"; }
	if($index_row == "8") {	$index_row = "8)"; }
	if($index_row == "9") {	$index_row = "9)"; }
	if($index_row == "10") {	$index_row = "10)"; }
	if($index_row == "11") {	$index_row = "11)"; }
	if($index_row == "12") {	$index_row = "12)"; }
	if($index_row == "13") {	$index_row = "13)"; }
	if($index_row == "14") {	$index_row = "14)"; }
	if($index_row == "15") {	$index_row = "15)"; }
	if($index_row == "16") {	$index_row = "16)"; }
	if($index_row == "17") {	$index_row = "17)"; }
	if($index_row == "18") {	$index_row = "18)"; }
	if($index_row == "19") {	$index_row = "19)"; }
	if($index_row == "20") {	$index_row = "20)"; }

	$numberme = array();
	$numberme[0] = $page_row;
	$numberme[1] = $index;
	$numberme[2] = $index_row;
	
	return $numberme;

}


function timezone_to_unix($timezone_value) {
	//test("timezone_value",$timezone_value);
	### remove the "+" from the value:
	$tmp_timezone = str_replace("+","",$tmp_timezone);
	
	if(strstr(":",$timezone_value)) { # contains minutes
		
		$tmp_offset = explode(":",$timezone_value);
		
		$absolute_hour = abs($tmp_offset[0]);
		if($absolute_hour != $tmp_offset[0]) { # offset was negative
			if($tmp_offset[1] == "00") {
				$new_offset = $tmp_offset[0] * 60 * 60 * -1;
			} else {
				$new_offset = (($tmp_offset[0] * 60) + $tmp_offset[1]) * 60 * -1;
			}
		} else { # offset was positive
			if($tmp_offset[1] == "00") {
				$new_offset = $tmp_offset[0] * 60 * 60;
			} else {
				$new_offset = (($tmp_offset[0] * 60) + $tmp_offset[1]) * 60;
			}
		}
	} else { # does not contain minutes (and negatrive number will always be correct)
		$new_offset = $timezone_value * 60 * 60;
	}
	return $new_offset;
}


function adjust_for_timezone($time,$offset) {

	$new_offset = timezone_to_unix($offset);
	return $time + $new_offset;

}


function timezone($memberid,$time,$output) {

//test("memberid",$memberid);
//test("time",$time);
//test("output",$output);
	
	## INPUT GMT AND IT OUTPUTS CORRECT TIMEZONE
	
	$tmp_time = explode(" ",$time);
	if($tmp_time[1]) {
		$timestamp = strtotime($time);
	} else {
		$timestamp = $time;
	}
	
	
	
	$timezone = getTHECASHIER("SELECT timezone FROM members WHERE memberid = '" . $memberid . "'");
	
	//test("timezone",$timezone);
	
	if(!$timezone) $timezone = "+00:00";
	
	
	$timezone_adjustment = timezone_to_unix($timezone);
	
	//test("timezone_adjustment",$timezone_adjustment);
	
	
	
	$adjusted_timestamp = $timestamp + $timezone_adjustment;
	
	
	//test("timestamp",$timestamp);
	//test("timezone_adjustment",$timezone_adjustment);
	//test("adjusted_timestamp",$adjusted_timestamp);

	if($output == "timestamp") {
		return $adjusted_timestamp;
	}
	
	if($output == "datetime") {
		return date("Y-m-d H:i:s",$adjusted_timestamp);
	}
	
	if($output == "formatted") {
		return date("Y-m-d g:i:s A",$adjusted_timestamp);
	}

	if($output == "formatted-split") {
		return date("Y-m-d",$adjusted_timestamp) ."<br>". date("g:i:s A",$adjusted_timestamp);
	}
	

	if($output == "goodlooking") {
		if($timezone) {
			return date("F jS, Y (g:i a)",$adjusted_timestamp);
		} else {
			return date("F jS, Y (g:i a)",$time) . "&nbsp;GMT";
		}
			
	}

	if($output == "notice") {
		if($timezone) {
			return date("g:i a (F jS, Y)",$adjusted_timestamp);
		} else {
			return date("g:i a (F jS, Y)",$time) . "&nbsp;GMT";
		}
			
	}		

	if($output == "YMD") {
		return date("Y-m-d",$adjusted_timestamp);
	} 
	
	if($output == "history") {
		return date("g:i a",$adjusted_timestamp) . "<br>" . date("Y.m.d",$adjusted_timestamp);
	}

	if($output == "day") {
		return date("l",$adjusted_timestamp);
	}	
	
	if($output == "CRM") {
		
		return date("g:i a (D)",$adjusted_timestamp);
		
	}

	if($output == "HIS") {
		
		$results['h'] = date("H",$adjusted_timestamp);
		$results['i'] = date("i",$adjusted_timestamp);
		$results['s'] = date("s",$adjusted_timestamp);
		
		return $results;
		
	}
	
	
}


function timezone_manual($offset,$time,$output) {
	
	## INPUT GMT AND IT OUTPUTS CORRECT TIMEZONE
	
	$tmp_time = explode(" ",$time);
	if($tmp_time[1]) {
		$timestamp = strtotime($time);
	} else {
		$timestamp = $time;
	}
	
	
	
	$timezone = $offset;
	
	//test("timezone",$timezone);
	
	
	$timezone_adjustment = timezone_to_unix($timezone);
	
	
	
	$adjusted_timestamp = $timestamp + $timezone_adjustment;
	
	
	//test("timestamp",$timestamp);
	//test("timezone_adjustment",$timezone_adjustment);
	//test("adjusted_timestamp",$adjusted_timestamp);

	if($output == "timestamp") {
		return $adjusted_timestamp;
	}
	
	if($output == "datetime") {
		return date("Y-m-d H:i:s",$adjusted_timestamp);
	}
	
	if($output == "formatted") {
		return date("Y-m-d g:i:s A",$adjusted_timestamp);
	}
	
	if($output == "goodlooking") {
		if($timezone) {
			return date("F jS, Y (g:i a)",$adjusted_timestamp);
		} else {
			return date("F jS, Y (g:i a)",$time) . "&nbsp;GMT";
		}
			
	}	

	if($output == "YMD") {
		return date("Y-m-d",$adjusted_timestamp);
	} 
	
	if($output == "history") {
		return date("g:i a",$adjusted_timestamp) . "<br>" . date("Y.m.d",$adjusted_timestamp);
	}
	
	if($output == "simple time") {
		return date("g:i a",$adjusted_timestamp);
	}
	
}






function timezoneREVERSE($memberid,$time,$output) { #converts timezone back to GMT
	
	$tmp_time = explode(" ",$time);
	if($tmp_time[1]) {
		$timestamp = strtotime($time);
	} else {
		$timestamp = $time;
	}
	
	$timezone = getTHECASHIER("SELECT timezone from members where memberid = '$memberid'");
	
	#$timezone = "";
	
	$timezone_adjustment = $timezone * 3600;
	
	$adjusted_timestamp = $timestamp - $timezone_adjustment;
	
	if($output == "timestamp") {
		return $adjusted_timestamp;
	}
	
	if($output == "datetime") {
		return date("Y-m-d H:i:s",$adjusted_timestamp);
	}
	
	if($output == "formatted") {
		return date("Y-m-d g:i:s A",$adjusted_timestamp);
	}

	if($output == "goodlooking") {
		return date("F jS, Y (g:i a)",$adjusted_timestamp);
	}
	
	
	if($output == "formatted<br>") { # 2:00:00�PM<br>1969-12-31
	
		$adjusted_timestamp = date("Y-m-d H:i:s",$adjusted_timestamp);
		$adjusted_timestamp = explode(" ",$adjusted_timestamp);
		$adjusted_timestamp = $adjusted_timestamp[1] . "&nbsp;" . $adjusted_timestamp[2] . "<br>" . $adjusted_timestamp[0];
		return $adjusted_timestamp;
	}
		
	if($output == "YMD") {
		return date("Y-m-d",$adjusted_timestamp);
	}	
		
} 
	
	
	
	
########################################
#### CURRENCIES v RATIOS v BALANCES ####
########################################


### THE BASICS:
function currency1($value,$ratio) {
	
	global $template;
	
	if(!$ratio) {
		return $_SESSION['template']['company'][currency1] . "&nbsp;" . number_format($value,2,".","");
	
	} else if($ratio) {
		return $_SESSION['template']['company'][currency1] . "&nbsp;" . number_format($value/$ratio,2,".","");
	}
}

function currency1_nospace($value,$ratio) {
	
	global $template;
	
	if(!$ratio) {
		return $_SESSION['template']['company'][currency1] . number_format($value,2,".","");
	
	} else if($ratio) {
		return $_SESSION['template']['company'][currency1] . number_format($value/$ratio,2,".","");
	}
}


function value2balance($value,$ratio) {
	global $template;
	if(!$ratio) {
		return "<nobr>" . $_SESSION['template']['company'][currency1] . "&nbsp;" . number_format($value,2,".","") . "</nobr>";
	
	} else if($ratio) {
		return "<nobr>" . $_SESSION['template']['company'][currency1] . "&nbsp;" . number_format($value/$ratio,2,".","") . "</nobr>";
	}
}


function currency2($value,$ratio) {
	global $template;
	if(!$ratio) {
		return $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($value,2,".","");
	
	} else if($ratio) {
		return $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($value*$ratio,2,".","");
	}
}

function balance2value($value,$ratio) {
	global $template;
	if(!$ratio) {
		return "<nobr>" . $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($value,2,".","") . "</nobr>";
	
	} else if($ratio) {
		return "<nobr>" . $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($value*$ratio,2,".","") . "</nobr>";
	}
}

###



function currencyRATIO() {
	//global $template;
	### NOTE: ratio MUST be set - uncomment convertions if you don't want to display 2nd currency
	# return "10.613";
	//return $_SESSION['template']['company'][exchange_rate];
	
	logger3("_SESSION['account']['currency_translation']",$_SESSION['account']['currency_translation']);
	if(stristr($_SESSION['account']['currency_translation'],"ON")) {
		
		return get_fx($_SESSION['account']['currency_0_iso3'],$_SESSION['template']['company']['currency1'],"1.00");
		logger3("_SESSION['account']['currency_0_iso3']",$_SESSION['account']['currency_0_iso3']);	
		logger3("_SESSION['template']['company']['currency1']",$_SESSION['template']['company']['currency1']);
		
	} else {
		return "1.00";
	}
}


function displayCURRENCY1($value) {
	global $template;
	$display = "<nobr>" . $_SESSION['template']['company'][currency1] . "&nbsp;" . number_format($value,2,".","") . "</nobr>";
	return $display;
}
		 
	
	


function displayCURRENCY2($spacer,$tmp_balance) {
	global $template;
	if($_SESSION['template']['company'][currency2]) { 
		$display = $spacer . "<font color='888888' face='verdana,arial,helvetica,sans-serif' size='1'>(" . $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($tmp_balance,2,".","") . ")</font>";
	}
	return $display;
}



function formatCURRENCY2($spacer,$ratio,$value) {

	# converts value (US$) to balance (g)
	
	global $template;
	$tmp_balance = $ratio * $value;
	$display = $spacer . "<font color='888888' face='verdana,arial,helvetica,sans-serif' size='1'>(". $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($tmp_balance,2,".","") . ")</font>";

	return $display;
}


function convertCURRENCY2($spacer,$ratio,$value) {
	
	# return ""; #uncomment for no convertions
	
	global $template;
	if($_SESSION['template']['company'][currency2]) { 
		$tmp_balance = $ratio * $value;
		$display = $spacer . "<font color='888888' face='verdana,arial,helvetica,sans-serif' size='1'>(x&nbsp;" . $_SESSION['template']['company'][currency2] . "&nbsp;" . $ratio . "&nbsp;=&nbsp;<u>". $_SESSION['template']['company'][currency2] . "&nbsp;" . number_format($tmp_balance,2,".","") . "</u>)</font>";
	}

	return $display;
}


function multicurrency_display($account_currency) {
	
	global $template;
	
	if( 
	($_SESSION['template']['company']['currency1'] == $account_currency) || 
	($account_currency == "") || 
	($account_currency == NULL) || 
	($account_currency == " ") 
	) {
		return FALSE;
	} else {
		return TRUE;
	}
}



		
function balance($accountid) {
	//global $master_config_platform_emulation;
	global $master_config_platform_base_currency;
	$tmp_balance = array();
	
	
	//$tmp_account_details = account($accountid);
	//test("tmp_account_details",$tmp_account_details);
	
        //default value from session
        //$force_platform_balance = $_SESSION['template']['company']['domain'];

        //if(stristr($_SESSION['template']['company']['domain'] ,"nsdb")){
        //    $force_platform_balance = $master_config_platform_emulation;
        //}

	$tmp_sql = "SELECT * FROM balances 
												WHERE 
												accountid = '" . $accountid . "' 

												AND platform = '". echo_platform() ."'

												AND currency_iso3 = '". $master_config_platform_base_currency ."';";
	logger3("tmp_sql",$tmp_sql);
	
	$tmp_balance = object2array(readTHECASHIER($tmp_sql));
	//test("tmp_balance",$tmp_balance);
										
	### if the balance field does not exist, create one (a bit of a multi-currency balance fix		
	if(empty($tmp_balance['balanceid'])) {
		
		####################################################################
		### NOW SET AN ACCOUNT BALANCE:
		
		
		$tmp_datetime = datetime();
		$tmp_balanceid = NULL;
		$tmp_platform = $force_platform_balance;
		$tmp_currency_iso3 = $master_config_platform_base_currency;
		$tmp_accountid = $accountid;
		$tmp_account_balance = "0.00";
		$tmp_sponsor_balance = "0.00";
		$tmp_approved = "0.00";
		$tmp_available = "0.00";
		$tmp_blingk_credit = $master_config_blingk_free_credit;
		$tmp_vocasign_gateway = "0.00";
		$tmp_created = $tmp_datetime;
		$tmp_updated = $tmp_datetime;
		
		$tmp_sql = "INSERT into balances (
			`balanceid`,
			`platform`,
			`currency_iso3`,
			`accountid`,
			`account_balance`,
			`sponsor_balance`,
			`approved`,
			`available`,
			`blingk_credit`,
			`created`,
			`updated`
		) VALUES (
			'" . $tmp_balanceid . "',
			'" . echo_platform() . "',
			'" . $tmp_currency_iso3 . "',
			'" . $tmp_accountid . "',
			'" . $tmp_account_balance . "',
			'" . $tmp_sponsor_balance . "',
			'" . $tmp_approved . "',
			'" . $tmp_available . "',
			'" . $tmp_blingk_credit . "',
			'" . $tmp_vocasign_gateway . "',
			'" . $tmp_created . "',
			'" . $tmp_updated . "');";
			logger("tmp_sql: " . $tmp_sql);
		$new_balanceid = insertTHECASHIER($tmp_sql);
		####################################################################
		####################################################################	

		/// NOW, get the balance values again (now that they exist):
		$tmp_balance = object2array(readTHECASHIER("SELECT * FROM balances 
													WHERE 
													accountid = '" . $accountid . "' 

													AND platform = '". echo_platform() ."'

													AND currency_iso3 = '". $master_config_platform_base_currency ."';"));
		
												
												
	}
	
	### ### START ???
	### //$account_dynamic_schedule = get_dynamic_DTR($accountid);
	### $datetime_rolling_schedule = datetime(strtotime("-30 days"));
	### 
	### 
	### $tmp_sql = "SELECT SUM(transaction_net_value) FROM transactions 
	###   		WHERE 
	###   		accountid = '" . $accountid . "' 
	### 
	###   		AND platform = '". echo_platform() ."' 
	### 
	###   		AND currency_0_iso3 = '". $master_config_platform_base_currency ."' 
	###   		AND description = 'INCOMING' 
	###   		AND updated_datetime > '" . $datetime_rolling_schedule . "';";
	### $tmp_approved = getTHECASHIER($tmp_sql);
	### //logger3("tmp_sql",$tmp_sql);
	### //test("tmp_approved",$tmp_approved);
	### 
	### $tmp_sql = "SELECT SUM(fee_recipient_value) FROM transactions WHERE accountid LIKE '" . $accountid . "' 
	###   		AND description = 'Incoming' 
	###   		AND updated_datetime > '" . $datetime_rolling_schedule . "';";
	### $tmp_fees = getTHECASHIER($tmp_sql);
	### 
	### 
	### $tmp_balance['approved'] = $tmp_balance['balance']['approved'] = currency_format($tmp_approved - $tmp_fees);
	### END ???
	
	
	$tmp_balance['balance']['sponsor_balance'] = $tmp_balance['sponsor'] = $tmp_balance['balance']['sponsor'] = currency_format($tmp_balance['sponsor_balance']);
	
	//test("tmp_balance['account_balance']",$tmp_balance['account_balance']);
	
	$tmp_balance['balance']['account_balance'] = $tmp_balance['account'] = $tmp_balance['balance']['account'] = currency_format($tmp_balance['account_balance']);
	
	//test("tmp_balance['balance']['account_balance']",$tmp_balance['balance']['account_balance']);
		
	//test("_SESSION['template']['company']['name']",$_SESSION['template']['company']['name']);
	//test("_SESSION['account']['business_category']",$_SESSION['account']['business_category']);
	### MAKE IT SHOW VOCASIGN GATEWAY BALANCE AS DEFAULT
	
	if(empty($_SESSION['account']['business_subcategory'])) {
		$tmp_sql = "SELECT business_subcategory FROM accounts WHERE accountid = '". $accountid ."';";
		$business_subcategory = getTHECASHIER($tmp_sql);
	} else {
		$business_subcategory = $_SESSION['account']['business_subcategory'];
	}
	
	// if(
	// (stristr($_SESSION['template']['company']['name'],"vocaSIGN")) &&
	// (stristr($business_subcategory,"GATEWAY"))
	// ) {
	// 	
	// 	
	// 	$tmp_balance['account_balance'] = $tmp_balance['balance']['account_balance'] = $tmp_balance['account'] = $tmp_balance['balance']['account'] = currency_format($tmp_balance['vocasign_gateway']);
	// 	
	// 	
	// }
	
	//test("tmp_balance",$tmp_balance);
	//test("tmp_balance",$tmp_balance);
	
	$tmp_balance['balance']['available'] = currency_format($tmp_balance['available']);
	
	$tmp_balance['balance']['balanceid'] = $tmp_balance['balanceid'];
	
	return $tmp_balance;
}


function simple_balance($accountid) {
	$tmp_sql = "SELECT account_balance FROM balances 
				WHERE 
				platform = '".echo_platform()."' 
				AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."' 
				AND accountid LIKE '" . $accountid . "';";
	$tmp_results = getTHECASHIER($tmp_sql);
	logger3("simple_balance(): tmp_sql",$tmp_sql);
	logger3("simple_balance(): tmp_results",$tmp_results);
	
	if((!$tmp_results) || ($tmp_results == 0) || ($tmp_results == "0") || ($tmp_results == NULL) || ($tmp_results == "NULL")) {
		$tmp_results = "0.00";
	}
	
	return currency_format($tmp_results);
}

function simple_blingk_credit($accountid) {
	$tmp_sql = "SELECT blingk_credit FROM balances WHERE 
				platform = '".echo_platform()."' 
				AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."' 
				AND accountid LIKE '" . $accountid . "';";
	$tmp_results = getTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("tmp_results",$tmp_results);
	
	if((!$tmp_results) || ($tmp_results == 0) || ($tmp_results == "0") || ($tmp_results == NULL) || ($tmp_results == "NULL")) {
		$tmp_results = "0.00";
	}
	return currency_format($tmp_results);
}


function img($filename) {
	global $template;
	if($filename == "popup") $filename = "popup.png";
	//return "<img src='https://" . $_SESSION['template']['company']['host_images'] . "/" . $filename . "' border='0'>";
	return "<img src='./link_images/" . $filename . "' border='0'>";
}



function currency1_px($px) {
	
	return "<span style='color:#666666; font-size:" . $px . ";'>" . $_SESSION['template']['company']['currency1'] . "</span>";
}


#######



function currency_code_1($px) {
	
	return "<span style='color:#666666; font-size:" . $px . ";'>" . $_SESSION['account']['currency_code_1'] . "</span>";
}




########################################
#### CURRENCIES ^ RATIOS ^ BALANCES ####
########################################

function jump($method,$location_page,$artificial_delay=NULL,$processing_message=null) {
	///echo 333;
	
	//logger3("function: jump(): start.",$X);
	logger3("function: jump(): method",$method);
	logger3("function: jump(): location_page",$location_page);
	
	//global $http;
	//global $template;

	
	
	///test("FUNC: location_page",$location_page);
	
	if(strtolower($method) == "javascript") {
		//test("method == javascript == TRUE",NULL,NULL);
		if(!empty($artificial_delay)) {

			if(!empty($processing_message)) {
				//echo 7777;
				display_processing($processing_message,$full_html_headers);
			}
			
			echo "
			<SCRIPT LANGUAGE=\"JAVASCRIPT\" TYPE=\"TEXT/JAVASCRIPT\">
				setTimeout('location.href = \"" . $location_page . "\"','" . $artificial_delay . "');
			</SCRIPT>";
		
		} else {
			
			echo "<SCRIPT LANGUAGE=\"JAVASCRIPT\" TYPE=\"TEXT/JAVASCRIPT\">
				location.href = \"" . $location_page . "\";
			</SCRIPT>";
		
		}

		#location.href = \"" . $http . $_SESSION['template']['company']['host_www'] . "/" . $location_page . "\"; old
	} else if($method == "meta") {
		echo "<META HTTP-EQUIV=\"refresh\" content=\"0;URL=" . $location_page . "\">";
		
	} else if($method == "processing") {
		echo "<META HTTP-EQUIV=\"refresh\" content=\"6;URL=https://" . $_SESSION['template']['company']['host_www'] . "/" . $location_page . "\">";
		
	} else if($method == "gateway processing") {
		echo "<META HTTP-EQUIV=\"refresh\" content=\"6;URL=https://" . $_SESSION['template']['company']['host_gateway'] . "/" . $location_page . "\">";
		
	} else if($method == "url") {
		echo "<SCRIPT LANGUAGE=\"JAVASCRIPT\" TYPE=\"TEXT/JAVASCRIPT\">
		  window.open(\"" . $location_page . ",\"_self\");
		</SCRIPT>";
	
	} else if(
	($method == "visual_processing") ||
	($method == "visual")
	)  {
		if(!$processing_message) $processing_message = "Processing Secured Request...";
		if(!$artificial_delay) $artificial_delay = 2;
		display_processing($processing_message,$full_html_headers);
		echo "<META HTTP-EQUIV=\"refresh\" content=\"".$artificial_delay.";URL=" . $location_page . "\">";
		
		
	} else if(
	($method == "javascript_top") || 
	($method == "top")
	) {

		echo "<SCRIPT LANGUAGE=\"JAVASCRIPT\" TYPE=\"TEXT/JAVASCRIPT\">
		top.window.location.replace(\"" . $location_page . "\");
		</SCRIPT>";
	}
	
	unset($location_page);
	logger("function: jump(): end.");
}



function display_currency_translation($currency_code_0=null,$currency_code_1=null,$accountid) {


		
	## DEFINE ACCOUNT	
	if($accountid) {
		$tmp_account = account($accountid);
	} else {
		$tmp_account = $_SESSION['account'];
	}
	
	### TRANSLATION OT OFF:
	if(!stristr($tmp_account['currency_transaction'],"OFF")) {

		## DEFINE CURRENCY_1
		if($currency_code_1) {
			$tmp_currency_code_1 = $currency_code_1;

		} else if($tmp_account['currency_code_1']) {
			$tmp_currency_code_1 = $tmp_account['currency_code_1'];

		} else {
			$tmp_currency_code_1 = geo_data($_SESSION['geodata']['iso3'],"iso3","currency_code");
		}
		
		//test("tmp_currency_code_1",$tmp_currency_code_1);
		
		
		## DEFINE CURRENCY_0
		if(isset($currency_code_0)) {
		    $tmp_currency_code_0 = $currency_code_0;
		
		} else if($tmp_account['currency_0_iso3']) {
			$tmp_currency_code_0 = $tmp_account['currency_0_iso3'];

		} else {
		    $tmp_currency_code_0 = $_SESSION['template']['currency1'];
		}
			
		//test("tmp_currency_code_0",$tmp_currency_code_0);
		


		if(
		(isset($tmp_currency_code_0)) &&
		(isset($tmp_currency_code_1)) &&
		($tmp_currency_code_0 != $tmp_currency_code_1)
		) {
			return TRUE;
		} else {
			return FALSE;
		}
		
	### TRANSLATION SET TO OFF
	} else {
		return FALSE;
	}
}
	
	


function transactionTABS($total_tabs,$total_transactions,$max_display,$active_tab) {
	$display_tabs = "<font face=verdana color=aaaaaa size=1><b>|&nbsp;</b></font>";
	
	
	
	
	$tab_start = 1;
	$tab_counter = 1;
	if(!$active_tab) { $active_tab = 1; }
	while($tab_start) {

		$test_max = ($max_display - 1);
		while($test_max) {
			if(($tab_start + $test_max) <= $total_transactions) {
				$tab_end = $tab_start + $test_max;
				break;
			} else {
				$test_max = $test_max - 1;
			}
		}
		
		if($active_tab == $tab_start) {
			$display_tabs = $display_tabs . "<a href='history.aum?tab=$tab_start'><font face=verdana color=aa0000 size=1><b>$tab_start&nbsp;-&nbsp;$tab_end</b></font></a><font face=verdana color=aaaaaa size=1><b>&nbsp;|&nbsp;</b></font>";
		} else {
			$display_tabs = $display_tabs . "<a href='history.aum?tab=$tab_start'><font face=verdana color=aaaaaa size=1><b>$tab_start&nbsp;-&nbsp;$tab_end</b></font></a><font face=verdana color=aaaaaa size=1><b>&nbsp;|&nbsp;</b></font>";
		}
		
		if(($tab_end + 1) > $total_transactions) {
			break;
		}
		
		if($tab_counter == $total_tabs) {
			break;
		}
		
		$tab_start = $tab_start + $max_display;
		$tab_counter = $tab_counter + 1;
	}
	
	$display_tabs = $display_tabs . "<a href='history.aum?history=search'><font face=verdana color=aaaaaa size=1><b>Search Dates</b></font></a><font face=verdana color=aaaaaa size=1><b>&nbsp;|&nbsp;</b></font>";

	return $display_tabs;
}



function transactionFEE($method,$description,$value) {
	$transactionFEE = array();
	
	if(($description == "Deposit") && ($method == "web")) {
		if($value >= "10") {
			$fee = $value * .1;
		} else {
			$fee = 1;
		}
	}


	if($description == "Incoming" && $method == "transfer") {
		if($value >= "1") {
			$fee = $value * .08;
		} else {
			$fee = "0.00";
		}
	}
	
	
	
	
	return $fee;
}





/* function bonuses($source,$sender_memberid,$description,$value) {
	
	$fee = "";
	$fee = array();

	if($source == "gateway" && $description == "outgoing") {
	
		if(!$previous_transfer = readTHECASHIER("SELECT * from transactions where memberid = '$sender_memberid' AND description = 'Outgoing' AND status = 'Completed'")) { ### FIRST TIME TRANSFER:
			
			$bonus = 
			
			
			$fee[total] = $value * ".20";
			############################
			$fee[bonus] = "0.00";
			$fee[affiliate] = "0.00";
			$fee[network] = $fee[gross] * ".10";
		
		} else { ### NOT "FIRST TIME":
		
			$fee[total] = $value * ".20";
			############################
			$fee[bonus] = "0.00";
			$fee[affiliate] = $fee[gross] * ".02";
			$fee[network] = $fee[gross] * ".16";
		}
	}
}
*/




function fees($source,$sender_memberid,$description,$value) {
	
	$fee = NULL;
	$fee = array();

	if($description == "transfer" && ($source == "www" || $source == "gateway")) {
	
		$fee[total_value] = $value * ".08";
		############################
		$fee[bonus_value] =	$value * ".01";
		$fee[bonus_percentage] = "1%";
		$fee[sponsor_value] = "0.00";
		$fee[network_value] = $value * ".07";
	
	}
	
	/*
		if(!$previous_transfer = readTHECASHIER("SELECT * from transactions where memberid = '$sender_memberid' AND description = 'Outgoing' AND status = 'Completed'")) { ### FIRST TIME TRANSFER:
			
			$fee[total_value] = $value * ".08";
			############################
			$fee[bonus_value] =	$value * ".01";
			$fee[bonus_percentage] = "1%";
			$fee[sponsor_value] = "0.00";
			$fee[network_value] = $value * ".07";
		
		} else { ### NOT "FIRST TIME":
		
			$fee[total_value] = $value * ".08";
			############################
			$fee[bonus_value] =	$value * ".01";
			$fee[bonus_percentage] = "1%";
			$fee[sponsor_value] = $value * "0.00";
			$fee[network_value] = $value * ".07";
		}
		*/
		
	
	return $fee;
}


function new_fees($description,$value,$sender_accountid,$recipient_accountid) {
	
	$fee = NULL;
	$fee = array();
	
	global $template;
	global $account;
	
	
	/*

	if($description == "transfer") {
	
		### GET BASIC FEES: ###
		$tmp_sql = "SELECT * FROM preferences WHERE 
	
	
		### GET SPONSOR FEE: ###
		
		# get recipient member
		$tmp_sql = "SELECT creator_memberid FROM accounts WHERE accountid LIKE '" . $recipient_accountid . "';";
		$tmp_creatorid = getTHECASHIER($tmp_sql);
		
		# get sponsor
		$tmp_sql = "SELECT sponsor_accountid FROM members WHERE memberid = '" . $tmp_creatorid . "';";
		$tmp_sponsorid = getTHECASHIER($tmp_sql);
		
		
		if($tmp_sponsorid) {
	
			# get sponsor fee
			$tmp_sql = "SELECT sponsor_fee FROM preferences WHERE accountid LIKE '" . $tmp_sponsorid . "';";
			$tmp_sponsor_fee = getTHECASHIER($tmp_sql);
			
			if(!$tmp_sponsor_fee) {
				$fee[sponsor_value] = $_SESSION['template']["company"]["sponsor_fee"];
			}
		
		} else {
			#no sponsor
			$fee[sponsor_value] = "0.00";
		}
	
	} else {
		# not a transfer
		$fee[sponsor_value] = "0.00";
	}
		
		
		
			
		
		
		
		
		
		
		
		$fee[total_value] = $value * ".08";
		############################
		$fee[bonus_value] =	$value * ".01";
		$fee[bonus_percentage] = "1%";
		$fee[sponsor_value] = "0.00";
		$fee[network_value] = $value * ".07";
	
	}
	*/

	
	return $fee;
}








function discountFEE($display,$method) {
	if(($display == "") && ($method == "creditcard")) {
		return "0.035";
	}
	
	if(($display == "%") && ($method == "creditcard")) {
		return "3.5%";
	}
	
	if(($display == "") && ($method == "paypal")) {
		return "0.035";
	}
	
	if(($display == "%") && ($method == "paypal")) {
		return "3.5%";
	}

	if(($display == "") && ($method == "echeck")) {
		return "0.035";
	}
	

	if(($display == "%") && ($method == "echeck")) {
		return "3.5%";
	}
	
	
	if(($display == "") && ($method == "bankwire")) {
		return "3.5%";
	}

	if(($display == "%") && ($method == "bankwire")) {
		return "3.5%";
	}
}






function MOD10($card_number) {
	
	# Get rid of any non-digits:
	$card_number = ereg_replace("[^[:digit:]]", "", $card_number);
	$card_number = trim($card_number);
	
	# The Luhn formula works right to left, so reverse the number.
	$card_number = strrev($card_number);

	$Total = 0;

	for ($x=0; $x<strlen($card_number); $x++) {
		$digit = substr($card_number,$x,1);

		# If it's an odd digit, double it
		if ($x/2 != floor($x/2)) {
			$digit *= 2;

			# If the result is two digits, add them
			if (strlen($digit) == 2) {
				$digit = substr($digit,0,1) + substr($digit,1,1);
			}
		}

		# Add the current digit, doubled and added if applicable, to the Total
		$Total += $digit;
	}

	# If it passed (or bypassed) the card-specific check and the Total is
	# evenly divisible by 10, it's cool!
	if ($Total % 10 == 0) {
		return TRUE; 
	} else {
		return FALSE;
	}
}


function mod10cc( $ccnum ) {
    $double = array( 0,2,4,6,8,1,3,5,7,9 );
    $ccnum = strrev( $ccnum );
    for( $i=0; $i<strlen( $ccnum ); $i++ )
        $values[] = ( $i&1 ) ? $double[$ccnum[$i]] : $ccnum[$i];
    return ( array_sum( $values ) % 10 ) ? 0 : 1;
}


function disguise_string($string,$number_of_digits_to_show,$display_side) {
	
	if($display_side == "right") {
	
		$tmp_account_number = $string; 
		$tmp_length = strlen($tmp_account_number); 
		$tmp_characters = $number_of_digits_to_show; 
		$tmp_start = $tmp_length - $tmp_characters; 
		$tmp_3_digit_account_number = substr($tmp_account_number , $tmp_start ,$tmp_characters); 
		$tmp_bullets = substr($tmp_account_number, 0, $number_of_digits_to_show*-1);
		$tmp_bullets = preg_replace("/[a-zA-Z0-9.-\/#]/","&bull;",$tmp_bullets);
		return $tmp_bullets . $tmp_3_digit_account_number;
	}
}



function card_details($card_number) {

	$card_number = ereg_replace("[^[:digit:]]", "", $card_number);
	
	$clean_card_number = trim($card_number);
	$card_number = str_split($clean_card_number);
	
	$card = "";
	$card = array();
	


		
	### AMEX
	if(
	($card_number[0] == "3") &&
	(count($card_number) == 15) 
	) {
		$card['brand'] = $card['type'] = "AMEX";
		$card['number'] = $card['card_number'] = $clean_card_number;
		# $card['display'] = $card_number[0] . "xxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] .$card_number[14];
		$card['display'] = "xxxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] .$card_number[14];
		$card['last'] = $card['last_4'] = $card_number[12] . $card_number[13] .$card_number[14];
		$card['last_four_digits'] = $card_number[12]." ".$card_number[13]." ".$card_number[14];

	}

	### DINER's
	if(
	($card_number[0] == "3") &&
	(count($card_number) == 14) 
	) {
		$card['brand'] = $card['type'] = "Diner's Club";
		$card['number'] = $card['card_number'] = $clean_card_number;
		# $card['display'] = $card_number[0] . "x&minus;xxxx&minus;xxxx&minus;" . $card_number[11] . $card_number[12] . $card_number[13] .$card_number[14];
		$card['display'] = "xx&minus;xxxx&minus;xxxx&minus;" . $card_number[10] . $card_number[11] . $card_number[12] .$card_number[13];
		$card['last'] = $card['last_4'] = $card_number[10] . $card_number[11] . $card_number[12] .$card_number[13];
		$card['last_four_digits'] = $card_number[10]." ".$card_number[11]." ".$card_number[12]." ".$card_number[13];
	}
	

	### JCB
	if(
	($card_number[0] == "3") &&
	(count($card_number) == 16) 
	) {
		$card['brand'] = $card['type'] = "JCB";
		$card['number'] = $card['card_number'] = $clean_card_number;
		# $card['display'] = $card_number[0] . "xxx&minus;xxxx&minus;xxxx&minus;" . $card_number[11] . $card_number[12] . $card_number[13] .$card_number[14];
		$card['display'] = "xxxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last'] = $card['last_4'] = $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last_four_digits'] = $card_number[12]." ".$card_number[13]." ".$card_number[14]." ".$card_number[15];
	}
	
	
	
	if($card_number[0] == "4") {
		$card['brand'] = $card['type'] = "VISA";
		$card['number'] = $card['card_number'] = $clean_card_number;
		# $card['display'] = $card_number[0] . "xxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['display'] = "xxxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last'] = $card['last_4'] = $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last_four_digits'] = $card_number[12]." ".$card_number[13]." ".$card_number[14]." ".$card_number[15];
	}
	
	
	
	if($card_number[0] == "5") {
		$card['brand'] = $card['type'] = "MasterCard";
		$card['number'] = $card['card_number'] = $clean_card_number;
		# $card['display'] = $card_number[0] . "xxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['display'] = "xxxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last'] = $card['last_4'] = $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last_four_digits'] = $card_number[12]." ".$card_number[13]." ".$card_number[14]." ".$card_number[15];
	}



	if($card_number[0] == "6") {
		$card['brand'] = $card['type'] = "Discover";
		$card['number'] = $card['card_number'] = $clean_card_number;
		# $card['display'] = $card_number[0] . "xxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['display'] = "xxxx&minus;xxxx&minus;xxxx&minus;" . $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last'] = $card['last_4'] = $card_number[12] . $card_number[13] . $card_number[14] .$card_number[15];
		$card['last_four_digits'] = $card_number[12]." ".$card_number[13]." ".$card_number[14]." ".$card_number[15];
	}
	
	
	
	
	
	### add BIN:
	$card['bin'] = $card_number[0] . $card_number[1] . $card_number[2] . $card_number[3] . $card_number[4] . $card_number[5];
	
	### legacy fix:
	$card['last4'] = $card['LAST4'] = $card['last_4'];
	
	### LAST 6:
	$card['last_six_digits'] = $card['last6'] = $card['LAST6'] = substr($clean_card_number,6);
	
	if($card) {
		return $card;
	} else {
		return NULL;
	}
}






function unsuspend($adminid,$memberid,$note) {

	$datetime = date("Y-m-d H:i:s");

	
	
	### UN-SUSPEND THE MEMBER:
	updateTHECASHIER("DELETE FROM banned WHERE memberid = '$memberid' AND status != ''");
	
	# UN-suspend wallets:
	updateTHECASHIER("UPDATE wallets SET authorization_status = 'Approved' WHERE authorization_status = 'Suspended' AND memberid = '$memberid'");



	### TAG MEMBER WITH NOTE:
	$member_note = "Member UN-Suspended: $note";
	$noteid = insertTHECASHIER("INSERT INTO notes 
	(`noteid`,
	`adminid`,
	`memberid`,
	`accountid`,
	`note`,
	`datetime`)
		
	VALUES
		
	('$blank_noteid',
	'$adminid',
	'$memberid',
	'$blank_accountid',
	'$member_note',
	'" . date("Y-m-d H:i:s",time()) . "')");



	### ALWAYS GET LATEST ACCOUNTS:
	$tmp_accounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$memberid' ORDER BY created ASC");

		
	### UN-SUSPEND ACCOUNTS:
	$i = 0;
	while($tmp_accounts[$i]) {
		
		updateTHECASHIER("DELETE FROM banned WHERE accountid LIKE '$tmp_accounts[$i]' AND status != ''");
		
		### TAG ACCOUNTS WITH NOTE:
		$account_note = "Account UN-Suspended: $note";
		$noteid = insertTHECASHIER("INSERT INTO notes 
		(`noteid`,
		`adminid`,
		`memberid`,
		`accountid`,
		`note`,
		`datetime`)
		
		VALUES
		
		('$blank_noteid',
		'$adminid',
		'$blank_memberid',
		'$tmp_accounts[$i]',
		'$member_note',
		'" . date("Y-m-d H:i:s",time()) . "')");
		$account_note = ""; # clear for next loop

		$i = $i + 1;									
	}
	

	### UPDATE 'SUSPENDED' TRANSACTIONS TO 'PENDING':
	$i = 0;
	while($tmp_accounts[$i]) {
		
		### NOTE!!! not sure why i am searching "results" - i think it is ok but MIGHT be a probelm?!
		
		# updated_datetime
		updateTHECASHIER("UPDATE transactions SET updated_datetime = '$datetime' WHERE (account_details LIKE '%ACCOUNTID][$tmp_accounts[$i]]%' OR results LIKE '%ACCOUNTID][$tmp_accounts[$i]]%') AND status = 'Suspended'");
		
		# adminid
		updateTHECASHIER("UPDATE transactions SET adminid = '$adminid' WHERE (account_details LIKE '%ACCOUNTID][$tmp_accounts[$i]]%' OR results LIKE '%ACCOUNTID][$tmp_accounts[$i]]%') AND status = 'Suspended'");

		# status
		updateTHECASHIER("UPDATE transactions SET status = 'Pending' WHERE (account_details LIKE '%ACCOUNTID][$tmp_accounts[$i]]%' OR results LIKE '%ACCOUNTID][$tmp_accounts[$i]]%') AND status = 'Suspended'");




		$i = $i + 1;									
	}
}




function check_banned($IP,$memberid,$accountid) {

	logger3("function check_banned()",0);
	logger3("IP",$IP);
	logger3("memberid",$memberid);
	logger3("accountid",$accountid);

	### SET SOME VARS:
	global $template;
	global $cookie_special;
	$current_datetime = datetime();
	#test("check_banned()...",$blank);
	
	
	

	## first check if the IP is "Bannned" - specifcially and only "Banned" IPs:
		# note: this should only effect the gateway and/or login.
		# basically if the IP is banned the system shouldn't let the user on at all. ever.
	
	

	### CHECK/MANAGE "BANNED" IP: ########################################################
	# (has nothing to do with suspended... just banned)

	
	# get banned ip:
	if($IP) {
		$banned_ip = readTHECASHIER("SELECT * FROM banned WHERE status = 'Banned' AND IP LIKE '%[$IP]%'");
		#test("banned_ip: ",$banned_ip);
		
		
		# check to see if ban is NOT expired:

		if(($banned_ip) && ($current_datetime < date("Y-m-d H:i:s",strtotime("$banned_ip->datetime +1 day")))) {
			
			$_SESSION['banned']['try_again'] = "0";
			$_SESSION['banned']['status'] = "Banned";
			$_SESSION['banned']['description'] = $banned_info->description;
			$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For your protection, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily placed on-hold for security review...<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime("$banned_ip->datetime +1 day"),"goodlooking") . ". <br>
<br>
Please try logging back into your account at this time, or you may contact customer support for further assistance.</font color>";

			return $_SESSION['banned'];
			
		} else { # delete outdated entry:
			updateTHECASHIER("DELETE FROM banned WHERE  bannedid LIKE '" . $banned_ip->bannedid . "';");
		}
	} # end IP/Banned check
	
	###################################################################################
	
	
		

	
	### CHECK IF MEMBER/ACCOUNT IS LIMITED/SUSPENDED: #################################
	
	if($memberid || $accountid) {
		$banned_info = "";
	
		if($memberid) {
			$banned_member = readTHECASHIER("SELECT * FROM banned WHERE status != '' AND memberid = '" . $memberid . "'");
			#test("banned_member: ",$banned_member);
			
			if($banned_member) {
			
				#### UPDATE IPs: #################################################
				# compile row IPs and add new IPs as necessary:
				$tmp_ip = $banned_info->IP;
				if(($IP) && (!strstr($tmp_ip,$IP))) {
					$tmp_ip = $tmp_ip . "[$IP]";
				}
				if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
					$tmp_ip = $tmp_ip . "[$cookie_special]";
				}
				#
				##################################################################
			
				updateTHECASHIER("UPDATE banned SET IP = '" . $tmp_ip . "' WHERE  bannedid LIKE '" . $banned_member->bannedid . "';");
				$banned_info = readTHECASHIER("SELECT * FROM banned WHERE  bannedid LIKE '" . $banned_member->bannedid . "'");
				logger3("banned_info",$banned_info);
			}
			
		
		} else if($accountid) {
			$banned_info = readTHECASHIER("SELECT * FROM banned WHERE status != '' AND accountid LIKE '$accountid'");
			#test("banned_account: ",$banned_account);
			# no ned to updat IPs as IPs are only for member insertions.
		}
		
		
		## check if suspended:
		if(strtoupper($banned_info->status) == 'SUSPENDED') {
			#test("banned_info->status: ",$banned_info->status);
			
			# note: no time limit. if member/account is suspdned then so be it.
			
			#  in " . countdown($event,"03","21","2013") . " days
			
			$_SESSION['banned']['message'] = "<span style='line-height:35px;'>
			<b>ALERT!</b><br>
			This account has been suspended.<br>
			<font color=000099>As a result, services are limited to viewing transaction history.<br>
			Please contact customer support should you require further assistance.</font color><br>
			</span>";

			$_SESSION['banned']['try_again'] = "0";
			$_SESSION['banned']['description'] = $banned_info->description;
			$_SESSION['banned']['status'] = "Suspended";
			return $_SESSION['banned'];
		}
		
		
		## now check to see if member/account account is limited:
		if(strtoupper($banned_info->status) == 'LIMITED') {
		
			# make sure the time is NOT expired:
			if($current_datetime < date("Y-m-d H:i:s",strtotime("$banned_info->datetime +1 day"))) {
			
				
				
				$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily limited..<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime($banned_info->datetime . " +1 day"),"goodlooking") . ".<br>
<br>
You may also contact customer support for further assistance.</font color>";

				$_SESSION['banned']['try_again'] = "0";
				$_SESSION['banned']['description'] = $banned_info->description;
				$_SESSION['banned']['status'] = $banned_info->status;
				
				
				logger("check_banned(): _SESSION['banned']",$_SESSION['banned']);
				
				return $_SESSION['banned'];
			
			} else { # delete outdated entry:
				
				# get memberid:
				if(!$banned_info->memberid) {
					$tmp_account = readTHECASHIER("SELECT * FROM accounts WHERE accountid LIKE '$banned_info->accountid'");
					$tmp_member = readTHECASHIER("SELECT * FROM members WHERE memberid = '$tmp_account->creator'");
					$tmp_memberid = $tmp_member->memberid;
					$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$tmp_memberid'");
				 
				} else {
					$tmp_memberid = $banned_info->memberid;
					$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$tmp_memberid'");
				}
					
				# unsuspend member
				updateTHECASHIER("DELETE FROM banned WHERE memberid = '$tmp_memberid'");
				
				# unsuspend accounts:
				$a = 0;
				while($tmp_acccounts[$a]) {
					updateTHECASHIER("DELETE FROM banned WHERE accountid LIKE '$tmp_acccounts[$a]'");
					$a = $a + 1;
				}
				
				# do not return; keep going through rest of script.
				
			} # end expired check
			
		} # end check based on memberid/accuntid
		
	} # end make sure memberid/accountid is set
	
	###################################################################################
 
 
 
	# ok so now... they passed member/account check ... so and they have to be logged in. so i gess we have to be sure that member sessin is set. and if member session is set then then we can check to see if the ip hat the user logged in fom is banned or if the ip tat the cookie is set is banned. if so then ban the new member session plus all accounts and if cookie is different that ip then tag both. UNLESS!!! unbind is set on the banned ip so as too allow for ths new member id. maybe?! ;) hehehe

	
	
	### CHECK IF MEMBER/ACCOUNT IS LIMITED/SUSPENDED BY WAY OF ASSOCIATED IP: ########
	
	if($memberid) {
		$banned_info = "";
		#test("got to mmebr",$blank);
		
		if($IP) {
			$banned_ip = readTHECASHIER("SELECT * FROM banned WHERE status != '' AND IP LIKE '%[$IP]%'");
		 #test("banned_ip: ",$banned_ip);
			if(!strstr($banned_ip->unassociated,"[$memberid]")) {
				$banned_info = $banned_ip;
			}
		} if($banned_cookie) {
			$banned_cookie = readTHECASHIER("SELECT * FROM banned WHERE status != '' AND IP LIKE '%[$cookie_special]%'");
		 #test("banned_cookie: ",$banned_cookie);
			if(!strstr($banned_ip->unassociated,"[$memberid]")) {
				$banned_info = $banned_cookie;
			}
		}

		
		if($banned_info->status == "Limited") {
			
			# check to see if ban is NOT expired:
			if($current_datetime < date("Y-m-d H:i:s",strtotime("$banned_info->datetime +1 day"))) {
				
				# delet all old/pending references to member:
				updateTHECASHIER("DELETE FROM banned WHERE memberid = '$memberid'");
				
				
				#### UPDATE IPs: #################################################
				# compile row IPs and add new IPs as necessary:
				$tmp_ip = $banned_info->IP;
				if(($IP) && (!strstr($tmp_ip,$IP))) {
					$tmp_ip = $tmp_ip . "[$IP]";
				}
				if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
					$tmp_ip = $tmp_ip . "[$cookie_special]";
				}
				#
				##################################################################
				
				
				# insert new member ban based on date from ASOCIATED IP:
				$tmp_bannedid = insertTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$tmp_ip','$memberid','$blank_accountid','$banned_info->status','ASSOCIATED BANNEDID:$banned_info->bannedid','$blank_attempts','$blank_adminid','$banned_info->datetime')");
				
				# insert member note:
				$member_note = "Member Limited (24 Hours): ASSOCIATED:$banned_info->memberid";
				$noteid = insertTHECASHIER("INSERT INTO notes 
				(`noteid`,
				`adminid`,
				`memberid`,
				`accountid`,
				`note`,
				`datetime`)
		
				VALUES
		
				('$blank_noteid',
				'$adminid',
				'$memberid',
				'$blank_accountid',
				'$member_note',
				'" . date("Y-m-d H:i:s",time()) . "')");
				
				
				# insert new account bans based on ASOCIATED IP:
				$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$memberid'");
			
				$a = 0;
				while($tmp_acccounts[$a]) {
					updateTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$blank_ip','$blank_member','$tmp_acccounts[$a]','$banned_info->status','$tmp_bannedid','$blank_attempts','$blank_adminid','$current_datetime')");

					# insert member note:
					$acccount_note = "Account Limited (24 Hours): ASSOCIATED MEMBERID:$banned_info->memberid";
					$noteid = insertTHECASHIER("INSERT INTO notes 
					(`noteid`,
					`adminid`,
					`memberid`,
					`accountid`,
					`note`,
					`datetime`)
	 
					VALUES
		
					('$blank_noteid',
					'$adminid',
					'$blank_memberid',
					'$tmp_acccounts[$a]',
					'$account_note',
					'" . date("Y-m-d H:i:s",time()) . "')");
				
					$a	= $a + 1;
				}
				
				# return updated msg:
				$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily limited..<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime("$banned_info->datetime +1 day"),"goodlooking") . ".<br>
<br>
You may also contact customer support for further assistance.</font color>";

				$_SESSION['banned']['try_again'] = "0";
				$_SESSION['banned']['description'] = $banned_info->description;
				$_SESSION['banned']['status'] = $banned_info->status;
				return $_SESSION['banned'];
				
				
			} else {
				# time has expired, do nothing. 
				# old entry will be deleted next time actua accunt hlder logs in
			}
			
		} # end limited
		
		
		if($banned_info->status == "Suspended") {	
				
			# delet all old/pending references to member:
			updateTHECASHIER("DELETE FROM banned WHERE memberid = '$memberid'");
				
				
				
							
			#### UPDATE IPs: #################################################
			# compile row IPs and add new IPs as necessary:
			$tmp_ip = $banned_info->IP;
			if(($IP) && (!strstr($tmp_ip,$IP))) {
				$tmp_ip = $tmp_ip . "[$IP]";
			}
			if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
				$tmp_ip = $tmp_ip . "[$cookie_special]";
			}
			#
			##################################################################
			

				
			
			# insert new member ban based on date from ASOCIATED IP:
			$tmp_bannedid = insertTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$tmp_ip','$memberid','$blank_accountid','$banned_info->status','ASSOCIATED BANNEDID:$banned_info->bannedid','$blank_attempts','$blank_adminid','$current_datetime')");
				
			# insert member note:
			$member_note = "Member Suspended: ASSOCIATED:$banned_info->memberid";
			$noteid = insertTHECASHIER("INSERT INTO notes 
			(`noteid`,
			`adminid`,
			`memberid`,
			`accountid`,
			`note`,
			`datetime`)
		
			VALUES
		
			('$blank_noteid',
			'$adminid',
			'$memberid',
			'$blank_accountid',
			'$member_note',
			'" . date("Y-m-d H:i:s",time()) . "')");
	
	

			# suspend wallets:
			updateTHECASHIER("UPDATE wallets SET authorization_status = 'Suspended' WHERE authorization_status = 'Approved' AND memberid = '$memberid'");	
	
	
				

			# insert new account bans based on ASOCIATED IP:
			$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$memberid'");
			
			$a = 0;
			while($tmp_acccounts[$a]) {
				updateTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$blank_ip','$blank_member','$tmp_acccounts[$a]','$banned_info->status','BANNEDID:$tmp_bannedid','$blank_attempts','$blank_adminid','$current_datetime')");

				# insert member note:
				$acccount_note = "Account Suspended: ASSOCIATED:$banned_info->memberid";
				$noteid = insertTHECASHIER("INSERT INTO notes 
				(`noteid`,
				`adminid`,
				`memberid`,
				`accountid`,
				`note`,
				`datetime`)
	 
				VALUES
		
				('$blank_noteid',
				'$adminid',
				'$blank_memberid',
				'$tmp_acccounts[$a]',
				'$account_note',
				'" . date("Y-m-d H:i:s",time()) . "')");
				
				$a	= $a + 1;
			}
		
			$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been suspended..<br>
<br>
<font color=000099>Please contact customer support for further assistance.</font color>";

			$_SESSION['banned']['try_again'] = "0";
			$_SESSION['banned']['description'] = $banned_info->description;
			$_SESSION['banned']['status'] = "Suspended";
			return $_SESSION['banned'];

		
		} # end banned by association.
	
	} # end ($memberid)
	
	###################################################################################
	
	return NULL;
	
} # end check_banned()
	

function update_authorized_ip_address($memberid) {

	global $authorization;
	
	$tmp_sql = "SELECT * FROM ips WHERE memberid = '" . $memberid . "' AND ip = '" . $_SERVER['REMOTE_ADDR'] . "';";
	$existing_ip = object2array(readTHECASHIER($tmp_sql));
	
	// update existing
	if($existing_ip['ipid']) {
		$tmp_sql = "UPDATE ips SET status = 'Authorized', updated = '" . $authorization['datetime'] . "'  WHERE ipid LIKE '" . $existing_ip['ipid'] . "';";
		updateTHECASHIER($tmp_sql);
		
	// add new record
	} else {
		$tmp_sql = "INSERT INTO ips 
					(`ipid`,
					`memberid`,
					`ip`,
					`status`,
					`created`,
					`updated`)
		
					VALUES
		
					('" . $blank_noteid . "',
					'" . $memberid . "',
					'" . $_SERVER['REMOTE_ADDR'] . "',
					'Authorized',
					'" . $authorization['datetime'] . "',
					'" . $authorization['datetime'] . "');";
		$existing_ip['ipid'] = insertTHECASHIER($tmp_sql);
	}
	
	return $existing_ip['ipid'];
}



function update_banned($adminid,$memberid,$IP,$banned_status,$banned_description,$banned_attempts) {

	### $banned_status
	//	Limited (24 Hours)
	//	Suspended 
	//	Banned
	

	### SET SOME VARS:
	global $template;
	global $cookie_special;
	$current_datetime = date("Y-m-d H:i:s",time());
 #test("update_banned()...",$blank);
	
	$tmp_member = member($memberid);
	if(!$adminid) {
		$tmp_admin['emailaddress'] = $_SESSION['template']['company']['emailaddress_support'];
	} else {
		$tmp_admin = member($adminid);
	}
	
	
	
 
	### INSTANT BAN MEMBER/ACCOUNT: #########################################
	if($banned_attempts == "0") {
			
		# delet all old/pending references to member:
		updateTHECASHIER("DELETE FROM banned WHERE memberid = '$memberid'");
		#
		# 2004.02.07 - looks ok until this point.	

		
		# basicalkly, if adminid is set then donlt include hr/his IP in the ban ;)
		# set IP value:
		if((!$adminid) || ($adminid == "0")) {
			if(($cookie_special) && ($IP != $cookie_special)) {
				$tmp_ip = "[$IP]" . "[$cookie_special]"; 
			} else {
				$tmp_ip = "[$IP]";
			}
		}
		#
		# 2004.02.07 - looks ok until this point.
	

			

		# insert new member ban based on date from associated IP:
		$tmp_bannedid = insertTHECASHIER("INSERT INTO banned 
		(`bannedid`,
		`IP`,
		`memberid`,
		`accountid`,
		`status`,
		`description`,
		`attempts`,
		`adminid`,
		`datetime`) 
		
		VALUES 

		('$blank_bannedid',
		'$tmp_ip',
		'$memberid',
		'$blank_accountid',
		'$banned_status',
		'$banned_description',
		'$banned_attempts',
		'$adminid',
		'$current_datetime')");
		#
		# 2004.02.07 - looks ok until this point.
	

	
		# SUSPEND WALLETS / SET NOTES:
		if($banned_status == "Suspended") {
		
			updateTHECASHIER("UPDATE wallets SET authorization_status = 'Suspended' WHERE authorization_status = 'Approved' AND memberid = '$memberid'");

			$member_note = "Member Suspended:
WHO: $tmp_member[emailaddress] (MID:$tmp_member[memberid])
WHY: $banned_description";
			
			$account_note = "Account Suspended:
WHO: $tmp_member[emailaddress] (MID:$tmp_member[memberid])
WHY: $banned_description";

		} else {
			$member_note = "Account $banned_status (24 Hours):
WHO: $tmp_member[emailaddress] (MID:$tmp_member[memberid])
WHY: $banned_description";

			$account_note = "Account $banned_status (24 Hours): 
WHO: $tmp_member[emailaddress] (MID:$tmp_member[memberid])
WHY: $banned_description";

		}
		#
		# 2004.02.07 - looks ok until this point.
	

				
				
		# insert member note:
		if($memberid) {
			$noteid = insertTHECASHIER("INSERT INTO notes 
			(`noteid`,
			`adminid`,
			`memberid`,
			`accountid`,
			`note`,
			`datetime`)
		
			VALUES
		
			('$blank_noteid',
			'$adminid',
			'$memberid',
			'$blank_accountid',
			'$member_note',
			'$current_datetime')");
		}
		#
		# 2004.02.07 - looks ok until this point.
	


		# insert new account:
		$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$memberid'");
			
		$a = 0;
		while($tmp_acccounts[$a]) {
			updateTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$blank_ip','$blank_member','$tmp_acccounts[$a]','$banned_status','BANNEDID:$tmp_bannedid','$blank_attempts','$adminid','$current_datetime')");

			# insert account note:
			# $acccount_note = "Account Suspended: MEMBERID:$memberid";
			$noteid = insertTHECASHIER("INSERT INTO notes 
			(`noteid`,
			`adminid`,
			`memberid`,
			`accountid`,
			`note`,
			`datetime`)
	 
			VALUES
	
			('$blank_noteid',
			'$adminid',
			'$blank_memberid',
			'$tmp_acccounts[$a]',
			'$account_note',
			'$current_datetime')");
			$a = $a + 1;
		}
		#
		# 2004.02.07 - looks ok until this point.
	

	 
		if($banned_status == "Suspended") {
			
			
			
			$_SESSION['banned']['try_again'] = "0";
			$_SESSION['banned']['status'] = "Suspended";
			$_SESSION['banned']['description'] = $banned_description;
			$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been suspended..<br>
<br>
<font color=000099>Please contact customer support for further assistance.</font color>";
		
		} else if(strtoupper($banned_status) == "LIMITED") {
		
				//$_SESSION['member'] = $member = "";
				//$_SESSION['account'] = $member = "";
				$_SESSION['banned']['try_again'] = "0";
				$_SESSION['banned']['status'] = "Limited";
				$_SESSION['banned']['description'] = $banned_description;
				$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily limited...<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime("$current_datetime +1 day"),"goodlooking") . ".<br>
<br>
You may also contact customer support for further assistance.</font color>";

		} else if($banned_status == "Banned") {
			
		 #test("banned_status...",$banned_status);
			
			$_SESSION['banned']['try_again'] = "0";
			$_SESSION['banned']['status'] = "Banned";
			$_SESSION['banned']['description'] = $banned_description;
			$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For your protection, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily placed on-hold for security review...<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime("$current_datetime +1 day"),"goodlooking") . ". <br>
<br>
Please try logging back into your account at this time, or you may contact customer support for further assistance.</font color>";
		}
		#
		# 2004.02.07 - looks ok until this point.
	

		
		return $_SESSION['banned'];
	
	}
	##########################################################################
	
	#
	# 2004.02.07 - looks ok until this point.

	

	# check to see if member has a pending banned try:
	if($IP) {
		$banned_info = readTHECASHIER("SELECT * FROM banned WHERE IP LIKE '%[$IP]%' AND description = '$banned_description'");
	} else if($memberid) {
		$banned_info = readTHECASHIER("SELECT * FROM banned WHERE memberid = '$memberid' AND description = '$banned_description'");
	}

	if(!$banned_info) { # YES PREVIOUS LOG:
		
		$tmp_ip = $banned_info->IP;
		
		if(($IP) && (!strstr($tmp_ip,$IP))) {
			$tmp_ip = $tmp_ip . "[$IP]";
		}
		
		if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
			$tmp_ip = $tmp_ip . "[$cookie_special]";
		}


		# was not found, add new entry:
		updateTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$tmp_ip','$memberid','$blank_account','$blank_status','$banned_description','1','$blank_adminid','$current_datetime')");

		# retrun info...
		$_SESSION['banned']['message'] = "";
		$_SESSION['banned']['try_again'] = $banned_attempts - 1;
		$_SESSION['banned']['description'] = "";
		$_SESSION['banned']['status'] = "";
		return $_SESSION['banned'];
	
	} else { ## previous entry was found:
		
		# check to be sure that previous entry has NOT expired:
		if(date("Y-m-d H:i:s",strtotime("$banned_info->datetime +1 day")) > $current_datetime) {
		
			# entry has not expired, update attempts:
			$updated_attempts = $banned_info->attempts + 1;
				
			# maybe set banned:
			if($updated_attempts >= $banned_attempts) {
								
				# delet all old/pending references to member:
				updateTHECASHIER("DELETE FROM banned WHERE memberid = '$memberid'");
				

				#### UPDATE IPs: #################################################
				# compile row IPs and add new IPs as necessary:
				$tmp_ip = $banned_info->IP;
				if(($IP) && (!strstr($tmp_ip,$IP))) {
					$tmp_ip = $tmp_ip . "[$IP]";
				}
				if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
					$tmp_ip = $tmp_ip . "[$cookie_special]";
				}
				#
				##################################################################
				

				

				# insert new member ban based on date from associated IP:
				$tmp_bannedid = insertTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$tmp_ip','$memberid','$blank_accountid','$banned_status','$banned_description','$banned_attempts','$adminid','$current_datetime')");

				# suspend wallets:
				if($banned_status == "Suspended") {
					updateTHECASHIER("UPDATE wallets SET authorization_status = 'Suspended' WHERE authorization_status = 'Approved' AND memberid = '$memberid'");

					$member_note = "Member Suspended: $banned_description";
					$account_note = "Account Suspended: $banned_description";

				} else {
					$member_note = "Account $banned_status (24 Hours): MEMBERID:$memberid";
					$account_note = "Account $banned_status (24 Hours): MEMBERID:$memberid";
				}
				
				
				
				# insert member note:
				# $member_note = "Member $banned_status: $banned_description";
				if($memberid) {
					$noteid = insertTHECASHIER("INSERT INTO notes 
					(`noteid`,
					`adminid`,
					`memberid`,
					`accountid`,
					`note`,
					`datetime`)
		
					VALUES
		
					('$blank_noteid',
					'$adminid',
					'$memberid',
					'$blank_accountid',
					'$member_note',
					'$current_datetime')");
				}
	
				# insert new account:
				$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator_memberid = '$memberid'");
			
				$a = 0;
				while($tmp_acccounts[$a]) {
				 updateTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$blank_ip','$blank_member','$tmp_acccounts[$a]','$banned_status','BANNEDID:$tmp_bannedid','$banned_attempts','$adminid','$current_datetime')");

					# insert account note:
					# $acccount_note = "Account Suspended: MEMBERID:$memberid";
					$noteid = insertTHECASHIER("INSERT INTO notes 
					(`noteid`,
					`adminid`,
					`memberid`,
					`accountid`,
					`note`,
					`datetime`)
	 
					VALUES
	
					('$blank_noteid',
					'$adminid',
					'$blank_memberid',
					'$tmp_acccounts[$a]',
					'$account_note',
					'$current_datetime')");
					$a	= $a + 1;
				}
		
				# return 
				if($banned_status == "Suspended") {
			
					$_SESSION['banned']['try_again'] = "0";
					$_SESSION['banned']['status'] = "Suspended";
					$_SESSION['banned']['description'] = $banned_description;
					$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been suspended..<br>
<br>
<font color=000099>Please contact customer support for further assistance.</font color>";
		
				} else if($banned_status == "Limited") {
		
						$_SESSION['banned']['try_again'] = "0";
						$_SESSION['banned']['status'] = "Limited";
						$_SESSION['banned']['description'] = $banned_description;
						$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For security purposes, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily limited..<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime("$current_datetime +1 day"),"goodlooking") . ".<br>
<br>
You may also contact customer support for further assistance.</font color>";

				} else if($banned_status == "Banned") {
		
				 #test("2banned_status...",$banned_status);
					$_SESSION['banned']['try_again'] = "0";
					$_SESSION['banned']['status'] = "Banned";
					$_SESSION['banned']['description'] = $banned_description;
					$_SESSION['banned']['message'] = "<u>ALERT</u>!&nbsp;&nbsp;For your protection, this " . $_SESSION['template']['company']['name'] . " Account has been temporarily placed on-hold for security review...<br>
<br>
<font color=5555aa>For your convenience, the account will be <u>automatcally re-activated</u> no later than " . timezone($memberid,strtotime("$current_datetime +1 day"),"goodlooking") . ". <br>
<br>
Please try logging back into your account at this time, or you may contact customer support for further assistance.</font color>";
				}
		
				return $_SESSION['banned'];
				
			} else { # update current entry only:
			
			
				## UPDATE ENTRY:
					 
				#### UPDATE IPs: #################################################
				# compile row IPs and add new IPs as necessary:
				$tmp_ip = $banned_info->IP;
				if(($IP) && (!strstr($tmp_ip,$IP))) {
					$tmp_ip = $tmp_ip . "[$IP]";
				}
				if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
					$tmp_ip = $tmp_ip . "[$cookie_special]";
				}
				#
				##################################################################
		
		

				
				updateTHECASHIER("UPDATE banned SET IP = '$tmp_ip' WHERE  bannedid LIKE '$banned_info->bannedid'");
					
				updateTHECASHIER("UPDATE banned SET attempts = '$updated_attempts' WHERE  bannedid LIKE '$banned_info->bannedid'");
					
				# return - info will be updated in next page refresh:
				$_SESSION['banned']['message'] = "";
				$_SESSION['banned']['try_again'] = $banned_attempts - $updated_attempts;
				$_SESSION['banned']['description'] = "";
				$_SESSION['banned']['status'] = "";
				return $_SESSION['banned'];
			}
		
		} else { # previously matching entry has EXPIRED... erase old and start a new one:
		 
			updateTHECASHIER("DELETE FROM banned WHERE  bannedid LIKE '$banned_info->bannedid'");
			
			
			
			
			#### UPDATE IPs: #################################################
			# compile row IPs and add new IPs as necessary:
			$tmp_ip = $banned_info->IP;
			if(($IP) && (!strstr($tmp_ip,$IP))) {
				$tmp_ip = $tmp_ip . "[$IP]";
			}
			if(($cookie_special) && (!strstr($tmp_ip,$cookie_special))) {
				$tmp_ip = $tmp_ip . "[$cookie_special]";
			}
			#
			##################################################################
				
		 
			# add new entry:
			updateTHECASHIER("INSERT INTO banned (`bannedid`,`IP`,`memberid`,`accountid`,`status`,`description`,`attempts`,`adminid`,`datetime`) VALUES ('$blank_bannedid','$tmp_ip','$memberid','$blank_account','$blank_status','$banned_description','1','$blank_adminid','$current_datetime')");

			# retrun info...
			$_SESSION['banned']['message'] = "";
			$_SESSION['banned']['try_again'] = $banned_attempts - 1;
			$_SESSION['banned']['description'] = "";
			$_SESSION['banned']['status'] = "";
			return $_SESSION['banned'];
		
		} # end expiration check
	
	} # end previous/update/add banned	 

} # end update_banned();



function update_account_status($accountid,$status,$note) {
	
	//test("(): accountid",$accountid);
	$account_details = account($accountid);
	//test("account_details['creator_memberid']",$account_details['creator_memberid']);
	
	//test("(): _SESSION['account']['accountid']",$_SESSION['account']['accountid']);
	
	$tmp_sql = "DELETE FROM banned WHERE accountid LIKE '".$account_details['accountid']."' OR memberid = '".$account_details['creator_memberid']."';";
	$sql_results = updateTHECASHIER($tmp_sql);
	
	//test("tmp_sql",$tmp_sql);
	//test("sql_results",$sql_results);
	
	
	if(!stristr($status,"ACTIVE")) {
	
		### INSERT UPDATE	
		$tmp_sql = "INSERT INTO banned 
			(`bannedid`
			,`IP`
			,`memberid`
			,`accountid`
			,`status`
			,`description`
			,`attempts`
			,`adminid`
			,`datetime`
			) VALUES (
			'".$blank_bannedid."'
			,null
			,'".$account_details['creator_memberid']."'
			,'". $accountid ."'
			,'".$status."'
			,'".$note."'
			,'0'
			,'".$_SESSION['account']['accountid']."'
			,'".datetime()."'
			)";
		$sql_results = updateTHECASHIER($tmp_sql);
		//test("tmp_sql",$tmp_sql);
		//test("update_results",$update_results);
	}
	
	return $sql_results;
}

function get_account_status($accountid) {

	$tmp_sql = "SELECT * FROM banned WHERE accountid LIKE '". $accountid ."'";
	$banned_account = object2array(readTHECASHIER($tmp_sql));
	if($banned_account['status']) {
		return $banned_account;
	} else {
		$banned_account['status'] =  "ACTIVE";
		return $banned_account;
	}
}

function get_member_status($memberid) {

	$tmp_sql = "SELECT * FROM banned WHERE memberid = '".$memberid."'";
	$banned_member = object2array(readTHECASHIER($tmp_sql));
	if($banned_member['status']) {
		return $banned_member;
	} else {
		$banned_member['status'] =  "ACTIVE";
		return $banned_member;
	}
}






function transaction_totals($account_number) {

	### NOTE: [ACCOUNT] VAR REPRESENTS INDIVIDUAL CARD OR PAYPAL ACCOUNT AND *NOT* CENTROGOLD ACCOUNT.
	### the idea is to limit each card or paypal account on deposits and not transfers
	### also, we want to limit cards and not account else they just register new accounts and use card again.
	### cards will be limited to use of unique card per member. cannot add same card to another member account.
	
	
	global $account;
	global $member;
	$totals = "";
	$totals = array();
	
	### GET USER TIMEZONE:
	if(!$timezone = getTHECASHIER("SELECT timezone from members where memberid = '$member[memberid]'")) {
		$timezone = "0";
	}
	
	$timezone = "";
 #test("timezone",$timezone);
	
	

	### FIGURE OUT DAYS TOTALS:
	# NOTE: use revrse tchnolgy to lookup time according to GMT... it think that should work...
	# ALSO: limits are form midnight to midnight per timezone.
	#
	# ok new drink:	transaction totals are for the last 24 hours and the last 7 dys and last 30 days
	
	
	
	$this_morning = timezoneREVERSE($member[memberid],date("Y-m-d 23:59:59",strtotime("-1 day")),"datetime");
	$tomorrow_morning = timezoneREVERSE($member[memberid],date("Y-m-d 23:59:59",strtotime("+0 day")),"datetime");
	$last_24_hours = date("Y-m-d H:i:s",strtotime("-24 hours"));
	
 #test("last_24_hours",$last_24_hours);
	

	# oldlookup based on midnight to midnight
	#$tmp_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND method_details = 'CARD_NUMBER][$account_number][' AND status = 'Completed' AND requested_datetime > '$this_morning' AND requested_datetime < '$tomorrow_morning'";

	# new lookup of transactions in the lst 24 hours
	$tmp_account_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND method_details = 'CARD_NUMBER][$account_number][' AND status = 'Completed' AND requested_datetime > '$last_24_hours'";

	$tmp_account_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND status = 'Completed' AND requested_datetime > '$last_24_hours'";
	
	
	$totals[account][day] = number_format(getTHECASHIER("$tmp_account_query"),2,".","");
	$totals[member][day] = number_format(getTHECASHIER("$tmp_member_query"),2,".","");



 #test("totals[account][day]",$totals[account][day]);
 #test("totals[member][day]",$totals[member][day]);
	


	### FIGURE OUT WEEKS TOTALS:
	### WEEK STARTS FRIDAY AND ENDS THURSADY
	
	$today = date("l",strtotime("$timezone hours")); # Ex: Sunday, Monday
	
 #test("today",$today);
	
	if($today == "Friday") { $thisweek_adustment = "-0"; }
	if($today == "Saturday") { $thisweek_adustment = "-1"; }
	if($today == "Sunday") { $thisweek_adustment = "-2"; }
	if($today == "Monday") { $thisweek_adustment = "-3"; }
	if($today == "Tuesday") { $thisweek_adustment = "-4"; }
	if($today == "Wednesday") { $thisweek_adustment = "-5"; }
	if($today == "Thursday") { $thisweek_adustment = "-6"; }
	
	$this_week = timezone($member[memberid],date("Y-m-d 00:00:01",strtotime("$thisweek_adustment days")),"datetime");
	$next_week = timezone($member[memberid],date("Y-m-d 00:00:01",strtotime("$thisweek_adustment days +1 week")),"datetime");
	$last_7_days = date("Y-m-d H:i:s",strtotime("-7 days"));
	
 #test("last_7_days",$last_7_days);
	

	/* old method based on thursday to firday
	$totals[account][week] = number_format(getTHECASHIER("SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND method_details = 'CARD_NUMBER][$account_number][' AND status = 'Completed' AND requested_datetime > '$this_week' AND requested_datetime < '$next_week'"),2,".","");

	$totals[member][week] = number_format(getTHECASHIER("SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND status = 'Completed' AND requested_datetime > '$this_week' AND requested_datetime < '$next_week'"),2,".",""); */





	# new methd based on last 7 days
	$tmp_account_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND method_details = 'CARD_NUMBER][$account_number][' AND status = 'Completed' AND requested_datetime > '$last_7_days'";

	$tmp_member_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND status = 'Completed' AND requested_datetime > '$last_7_days'";

	$totals[account][week] = number_format(getTHECASHIER($tmp_account_query),2,".","");
	$totals[member][week] = number_format(getTHECASHIER($tmp_member_query),2,".","");


 #test("totals[account][week]",$totals[account][week]);
 #test("totals[member][week]",$totals[member][week]);


	### FIGURE OUT MONTHS TOTALS:
	
	$this_month = timezone($member[memberid],date("Y-m-01 00:00:01",strtotime("+0 month")),"datetime");
	$next_month = timezone($member[memberid],date("Y-m-01 00:00:01",strtotime("+1 month")),"datetime");
	$last_30_days = date("Y-m-d H:i:s",strtotime("-30 days"));
	
 #test("last_30_days",$last_30_days);
	
	# old method 1st of mnth to 30th of month
	#$tmp_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND method_details = 'CARD_NUMBER][$account_number][' AND status = 'Completed' AND requested_datetime > '$this_month' AND requested_datetime < '$next_month'";



	# new method of last 30 days
	$tmp_account_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND method_details = 'CARD_NUMBER][$account_number][' AND status = 'Completed' AND requested_datetime > '$last_30_days'";

	$tmp_member_query = "SELECT SUM(transaction_net_value) FROM transactions where memberid = '$member[memberid]' AND description = 'Deposit' AND status = 'Completed' AND requested_datetime > '$last_30_days'";
	
	
	$totals[account][month] = number_format(getTHECASHIER($tmp_account_query),2,".","");
	$totals[member][month] = number_format(getTHECASHIER($tmp_member_query),2,".","");
	
	
	

 #test("totals[account][month]",$totals[account][month]);
 #test("totals[member][month]",$totals[member][month]);
	
 #test("totals",$totals);

	return $totals;

}



function extract_method_details($transactionid) {
	$tmp_sql = "SELECT * FROM transactions WHERE transactionid LIKE '" . $transactionid . "';";
	$tmp_transaction_details = readTHECASHIER($tmp_sql);
	
	$tmp_method_details = explode("[",$tmp_transaction_details->method_details);
	//test("tmp_method_details",$tmp_method_details);
	// foreach($tmp_method_details as $key => $val) {
	// 	$tmp_details = explode("^",$val);
	// 	$tmp_details_exploded = explode("]",$tmp_details[1]);
	// 	$tmp_return[$tmp_details] = $tmp_details_exploded[0];
	// }
	
	
	 $tmp_country = explode("COUNTRY-",$tmp_method_details[1]);
	 $tmp_return['COUNTRY'] = substr($tmp_country[1], 0, -1);

	 $tmp_holder = explode("HOLDER-",$tmp_method_details[2]);
	 $tmp_return['HOLDER'] = substr($tmp_holder[1], 0, -1);

	 $tmp_etc = explode("^",$tmp_method_details[3]);
	 $tmp_return['BANK_NAME'] = substr($tmp_etc[1], 0, -1);

	 $tmp_etc = explode("^",$tmp_method_details[4]);
	 $tmp_return['ACCOUNT_NUMBER'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[5]);
	 $tmp_return['ROUTING_NUMBER'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[6]);
	 $tmp_return['IBAN'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[7]);
	 $tmp_return['BIC'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("CITY-",$tmp_method_details[8]);
	 $tmp_return['CITY'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("FIRST_NAME-",$tmp_method_details[9]);
	 $tmp_return['FIRST_NAME'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("LAST_NAME-",$tmp_method_details[10]);
	 $tmp_return['LAST_NAME'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("STREET-",$tmp_method_details[11]);
	 $tmp_return['STREET'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("ZIP-",$tmp_method_details[12]);
	 $tmp_return['ZIP'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("CITY_ADDRESS-",$tmp_method_details[13]);
	 $tmp_return['CITY_ADDRESS'] = substr($tmp_etc[1], 0, -1); 
	
	//test("tmp_return",$tmp_return);
	return $tmp_return;
}


function extract_method_details_2($transactionid) {
	$tmp_sql = "SELECT * FROM transactions WHERE transactionid LIKE '" . $transactionid . "';";
	$tmp_transaction_details = readTHECASHIER($tmp_sql);
	
	$tmp_method_details = explode("[",$tmp_transaction_details->method_details);
	//test("tmp_method_details",$tmp_method_details);
	// foreach($tmp_method_details as $key => $val) {
	// 	$tmp_details = explode("^",$val);
	// 	$tmp_details_exploded = explode("]",$tmp_details[1]);
	// 	$tmp_return[$tmp_details] = $tmp_details_exploded[0];
	// }
	
	
	 $tmp_country = explode("^",$tmp_method_details[1]);
	 $tmp_return['COUNTRY'] = substr($tmp_country[1], 0, -1);

	 $tmp_holder = explode("^",$tmp_method_details[2]);
	 $tmp_return['HOLDER'] = substr($tmp_holder[1], 0, -1);

	 $tmp_etc = explode("^",$tmp_method_details[3]);
	 $tmp_return['BANK_NAME'] = substr($tmp_etc[1], 0, -1);

	 $tmp_etc = explode("^",$tmp_method_details[4]);
	 $tmp_return['ACCOUNT_NUMBER'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[5]);
	 $tmp_return['ROUTING_NUMBER'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[6]);
	 $tmp_return['IBAN'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[7]);
	 $tmp_return['BIC'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[8]);
	 $tmp_return['CITY'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[9]);
	 $tmp_return['FIRST_NAME'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[10]);
	 $tmp_return['LAST_NAME'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[11]);
	 $tmp_return['STREET'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[12]);
	 $tmp_return['ZIP'] = substr($tmp_etc[1], 0, -1);
	 
	 $tmp_etc = explode("^",$tmp_method_details[13]);
	 $tmp_return['CITY_ADDRESS'] = substr($tmp_etc[1], 0, -1); 
	
	//test("tmp_return",$tmp_return);
	return $tmp_return;
}


function limits($deposit_value,$wallet_number) {

	# echo "got here<br>";
	### SET SOME VARS:
	global $member;
	global $account;
	global $template;
	$totals = ""; $totals = array();
	$limits = ""; $limits = array();
	
	### GET TOTALS:
#test("wallet_number",$wallet_number);
	$totals = transaction_totals($wallet_number);
#test("totals",$totals);

	### MAKE CARD LOOK PRETTY:
	$card = card_details($wallet_number);
#test("card ",$card );
	
	### GET WALLET_NUMBER LIMITS:
	$tmp_wallet = readTHECASHIER("SELECT * FROM wallets where number = '$card[number]' AND memberid = '$member[memberid]'"); 
	
#test("tmp_wallet",$tmp_wallet);
	

	### IF WALLET IS NOT SET THEN SKIP:
	if($tmp_wallet || !$tmp_wallet) { # LAME FIX - prevents new cards from accepting more than limits.
	
		if($tmp_wallet) {
			$limits[day_max] = $tmp_wallet->daily_limit;
			$limits[week_max] = $tmp_wallet->weekly_limit;
			$limits[month_max] = $tmp_wallet->monthly_limit;
		} else {
			$limits[day_max] =	$_SESSION['template']['company'][cclimit_day];
			$limits[week_max] = $_SESSION['template']['company'][cclimit_week];
			$limits[month_max] = $_SESSION['template']['company'][cclimit_month];
		}
			
	#test("limits ",$limits );
	#test("totals",$totals);
		

		if(($totals[account][day] + $deposit_value) > $limits[day_max]) {
	
			$limits[available] = $limits[day_max] - $totals[account][day];
			$limits['message'] = "<u>ALERT!</u>&nbsp;&nbsp;Suggested \"Daily\" Purchase Limit Reached:<br>
<br>
<font color=5555aa>Authorized Credit Card Account:</font color> <font color=55aa55>$card[type]: $card[display]</font color><br>
<font color=5555aa>Suggested Daily Limit (Per Authorized Credit Card):</font color> <font color=aa5555>" . currency1($limits[day_max],$blank) . "</font color><br>
<font color=5555aa>Today's (Last 24 Hours) Total Purchased Value:</font color> <font color=55aa55>" . currency1($totals[account][day],$blank) . "</font color><br>
<font color=5555aa>Available For Purchase:</font color> <font color=55aa55>" . currency1($limits[available],$blank) . "</font color><br>
<br>
<font color=000077>Please try again using this card (up to " . currency1($limits[available],$blank) . ") or use a \"different\" Credit Card to complete your " . currency1($deposit_value,$blank) . " purchase request.</font color><br>
<br>
<font color=888888>(For more information about account limits,</font color> <a href='javascript:openSUPPORT(\"26\")'><font color=888888>'Click Here'</font color></a><font color=888888>.)</font color>";





		} else if(($totals[account][week] + $deposit_value) > $limits[week_max]) {
			$limits[available] = $limits[week_max] - $totals[account][week];
			$limits['message'] = "<u>ALERT!</u>&nbsp;Suggested \"Weekly\" Limit Reached:<br>
<br>
<font color=5555aa>Authorized Credit Card Account:</font color> <font color=55aa55>$card[type]: $card[display]</font color><br>
<font color=5555aa>Suggested Weekly Limit (Per Authorized Credit Card):</font color> <font color=aa5555>" . currency1($limits[week_max],$blank) . "</font color><br>
<font color=5555aa>This Week's (Last 7 Days) Total Purchased Value:</font color> <font color=55aa55>" . currency1($totals[account][week],$blank) . "</font color><br>
<font color=5555aa>Available For Purchase:</font color> <font color=55aa55>" . currency1($limits[available],$blank) . "</font color><br>
<br>
<font color=000077>Please try again using this card (up to " . currency1($limits[available],$blank) . ") or use a \"different\" Credit Card to complete your " . currency1($deposit_value,$blank) . " purchase request.</font color><br>
<br>
<font color=888888>(For more information about account limits,</font color> <a href='javascript:openSUPPORT(\"26\")'><font color=888888>'Click Here'</font color></a><font color=888888>.)</font color>";




		} else if(($totals[account][month] + $deposit_value) > $limits[month_max]) {
			$limits[available] = $limits[month_max] - $totals[account][month];
			$limits['message'] = "<u>ALERT!</u>&nbsp;Suggested \"Monthly\" Limit Reached:<br>
<br>
<font color=5555aa>Authorized Credit Card Account:</font color> <font color=55aa55>$card[type]: $card[display]</font color><br>
<font color=5555aa>Suggested Monthly Limit (Per Authorized Credit Card):</font color> <font color=aa5555>" . currency1($limits[month_max],$blank) . "</font color><br>
<font color=5555aa>This Month's (Last 30 Days) Total Purchased Value:</font color> <font color=55aa55>" . currency1($totals[account][month],$blank) . "</font color><br>
<font color=5555aa>Available For Purchase:</font color> <font color=55aa55>" . currency1($limits[available],$blank) . "</font color><br>
<br>
<font color=000077>Please try again using this card (up to " . currency1($limits[available],$blank) . ") or use a \"different\" Credit Card to complete your " . currency1($deposit_value,$blank) . " purchase request.</font color><br>
<br>
<font color=888888>(For more information about account limits,</font color> <a href='javascript:openSUPPORT(\"26\")'><font color=888888>'Click Here'</font color></a><font color=888888>.)</font color>";

		} else { ### ALL GOOD: SEND BACK 'AVAILABLE' ASSUMING REQUESTED TRANSACTION IS APPROVED:
			
			# echo "got here<br>";
			
			$limits['message'] = "";
			$limits[day_available] = $limits[day_max] -	($totals[account][day] + $deposit_value);
			$limits[week_available] = $limits[week_max] -	($totals[account][week] + $deposit_value);
			$limits[month_available] = $limits[month_max] -	($totals[account][month] + $deposit_value);
			$limits[summary] = "<font color=888888><u>Transaction Summary</u>:</font color><br>
			
<font color=5555aa>Authorized Credit Card Account:</font color> <font color=888888>$card[type]: $card[display]</font color><br>

<font color=5555aa>Daily (Last 24 Hours) Total:</font color> <font color=55aa55>" . currency1($totals[account][day],$blank) . "</font color> <font color=888888>(Limit: " . currency1($limits[day_max],$blank) . ")</font color><br>

<font color=5555aa>Weekly (Last 7 Days) Total:</font color> <font color=55aa55>" . currency1($totals[account][week],$blank) . "</font color> <font color=888888>(Limit: " . currency1($limits[week_max],$blank) . ")</font color><br> 
	
<font color=5555aa>Monthly (Last 30 Days) Total:</font color> <font color=55aa55>" . currency1($totals[account][month],$blank) . "</font color> <font color=888888>(Limit: " . currency1($limits[month_max],$blank) . ")</font color>";
		}
		
		return $limits;
		# echo "limits<br>";
	
	} ### wallet was not set:
	return NULL;
}




/*
### VERSION 7.4
function EMMMAIL74_CG($to_address, $from_address, $from_name, $subject, $text_message, $html_message) {

	global $template;
	
	
	if($from_address) {
		$from_address = $from_address;
	} else {
		$from_address = $_SESSION['template']['company'][emailaddress_support];
	}
	
	if($from_name) {
		$from_name = $_SESSION['template']['company'][name] . " ($from_name)";
	} else {
		$from_name = $_SESSION['template']['company'][name];
	}


	### EMMMAIL SERVER CONFIG:
	$return_path	= "support@BANGK.com";
	$from_id = "mail.BANGK.com";
	$received_from	= "192.168.1.1";
	$ip_address = "67.29.138.9";
	
	### WEERD HTML-ONLY PATCH:
	if($html_message == "") {
		$html_message = "''";
	}
	

	### ENCODE THE VARS:
	$from_name = escapeshellarg($from_name);
	$subject = escapeshellarg($subject);
	$text_message = escapeshellarg($text_message);
	$html_message = escapeshellarg($html_message);
	
	
	exec("/usr/bin/EMMMAIL7.4_CG '$to_address' '$from_address' $from_name $subject $text_message $html_message '$return_path' '$from_id' '$received_from' '$ip_address'>/dev/null 2>&1 &");
}
###############
*/




function duplicate_card($cardnumber) {
	global $template;
	global $member;

	### FIRST CHECK TO SEE IF CARD IS REGISTERED BY ANOTHER EMEMBER:
	$tmp_anothermember = getTHECASHIER("SELECT authorization_status FROM wallets WHERE number = '$cardnumber' AND memberid != '$member[memberid]' AND authorization_status = 'Approved')");

	$tmp_membercard = getTHECASHIER("SELECT walletid FROM wallets WHERE number = '$cardnumber' AND memberid = '$member[memberid]'");

	if($tmp_anothermember == "Approved") {
		
		banned("Suspended","Card Used By Another Member",3);
				
		$SYSMSG = "ALERT: The card you have selected has already been registered by another {$_SESSION['template'][copany][name]} Member.<br>
		<br>
		<font color=000099>Please use a new card OR contact {$_SESSION['template'][copany][name]} Customer Support for further assistance.</font color>";
		$transaction = "";
		jump("javascript","deposit_cards.aum?source=newcard");
		return;

	} else if($tmp_anothermember == "Suspended") {

		banned("Suspended","Card Was Previous Suspended",1);
		$SYSMSG = "ALERT: For security purposes, your account has been temporarily suspended.<br>
		<br>
		<font color=000099>Please contact {$_SESSION['template'][copany][name]} Customer Support for further assistance.</font color>";
		$transaction = "";
		jump("javascript","history.aum");
		return;

	} else if($tmp_membercard) {
		$transaction[source] = "wallet";
	}
}



function processorCURLER($url,$parameters,$referrer) {

	$cookie_file = tempnam("/tmp", "CURLCOOKIE");

	$ch = curl_init();

	curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie_file); 

	curl_setopt ($ch, CURLOPT_URL, $url );

	curl_setopt ($ch, CURLOPT_POST, 1);
	
	curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters); 

	curl_setopt ($ch, CURLOPT_HEADER, 1);

	curl_setopt ($ch, CURLOPT_ENCODING, 0);

	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

	if($referer) {
		//test("referer",$referer);
		curl_setopt ($ch, CURLOPT_REFERER, $referer);
	} else {
		curl_setopt ($ch, CURLOPT_AUTOREFERER, 1);
	}
	
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	
	curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");

	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 

	curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); 

	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	
	$result = curl_exec ($ch) or die ("Couldn't connect to $url.");

	$tmp_header_info = curl_getinfo($ch);
	
	//test("tmp_header_info",$tmp_header_info);
	
	curl_close ($ch);
	
	return $result;

}

function simpleCURLER($url,$parameters) {
	$ch = curl_init(); 
	curl_setopt($ch, CURLOPT_URL, $url . $parameters);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

	$result = curl_exec($ch) or die ("Couldn't connect to URL[" . $url . "] PARAMETERS[" . $parameters . "].");
	
	if(!$result) {
		$result = curl_error($ch);
	}
	
	curl_close ($ch);	
	return $result;
}


function postDATA($send_url,$send_data,$asynchronous = false) {
	
	$send_session = curl_init($send_url);
	# echo "send_session: $send_session<br>";
	
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_NOPROGRESS,1);
	curl_setopt($send_session, CURLOPT_COOKIESESSION,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	#curl_setopt($send_session, CURLOPT_REFERRER,$HTTP_HOST);
	curl_setopt($send_session, CURLOPT_POSTFIELDS,$send_data);
	curl_setopt($send_session, CURLOPT_SSL_VERIFYPEER, FALSE);
        
        if($asynchronous){
            curl_setopt($send_session, CURLOPT_FRESH_CONNECT, true);
            curl_setopt($send_session, CURLOPT_TIMEOUT,1);
            curl_setopt($send_session, CURLOPT_NOBODY, true); 
        }
        
	$send_results = curl_exec($send_session);
	//echo "<pre>send_results: $send_results</pre>";
	
	if(!$send_results) {
		$send_results = curl_error($send_session);
	}
	
	curl_close($send_session);
	
	return $send_results;
}


function active_currency() {
	if(
	(!$_SESSION['account']['currency_0_iso3']) ||
	($_SESSION['account']['currency_0_iso3'] == NULL) ||
	($_SESSION['account']['currency_0_iso3'] == "")
	) {
		return $_SESSION['account']['currency_0_iso3'] = $_SESSION['template']['company']['currency1'];
	} else {
		return $_SESSION['account']['currency_0_iso3'];
	}
}

function xml2array($xmlstring) {
	$xml = simplexml_load_string($xmlstring);
	$json = json_encode($xml);
	$array = json_decode($json,TRUE);
	return $array;
	//$array = json_decode(json_encode((array)simplexml_load_string($xml)),1);
}


function postBIOMETRIC($action,$memberid,$voiceid) {
	global $master_config_ibmsiv_host;
	
	
	
// $action: enroll, delete, score, query.
// if action = enroll, it will always create a bound session since we are always going to have 5 prints per baseprint
// everything else is a simple, unbound session that simply requires a printid and a path to audio


## START:

	# set timestmp
	$timestamp = date("Y-m-d H:i:s");
	
	# get name of audio file
	$new_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid LIKE '" . $voiceid . "'");
	//test("new_filename",$new_filename);
	
## DOES THIS MEMBER HAVE A BASE PRINT?
	$current_base_prints = object2array(readTHECASHIER("SELECT * FROM base_prints WHERE memberid = '" . $memberid . "'"));
	//test("current_base_prints",$current_base_prints);

## COUNT NUMBER OF PRINTS:
	$count_prints = 0;
	if(($current_base_prints[voiceid1]) && ($current_base_prints[voiceid1] != 0)) $count_prints++;
	if(($current_base_prints[voiceid2]) && ($current_base_prints[voiceid2] != 0)) $count_prints++;
	if(($current_base_prints[voiceid3]) && ($current_base_prints[voiceid3] != 0)) $count_prints++;
	if(($current_base_prints[voiceid4]) && ($current_base_prints[voiceid4] != 0)) $count_prints++;
	if(($current_base_prints[voiceid5]) && ($current_base_prints[voiceid5] != 0)) $count_prints++;
	//test("count_prints0",$count_prints);
	
## IF NO BASE PRINT, THEN REGISTER USER:
	
	if($action == "enroll") {	
		
		//test("action",$action);
		

		# build array
		if($count_prints == "0") { # ON REGISTRTAION:
		
			//test("count_prints1",$count_prints);
		
			#SET CURL VARS:
			$path_to_audio = NULL;
			$path_to_audio = array();
			$path_to_audio[0] = NULL; # keept $i value consistant with session results + voiceids
			$path_to_audio[1] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul";
			$path_to_audio[2] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul";
			$path_to_audio[3] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul";
			$path_to_audio[4] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul";
			$path_to_audio[5] = NULL; # set to null for first timers
			
			# update db:
			$test_sql = "INSERT into base_prints (
				`baseid`,
				`memberid`,
				`voiceid1`,
				`voiceid2`,
				`voiceid3`,
				`voiceid4`,
				`voiceid5`,
				`created`,
				`updated`
			) VALUES (
				'" . $baseid . "',
				'" . $memberid . "',
				'" . $voiceid . "',
				'" . $voiceid . "',
				'" . $voiceid . "',
				'" . $voiceid . "',
				'NULL',
				'" . $timestamp . "',
				'" . $timestamp . "')";
			$baseid = insertTHECASHIER($test_sql); # gets base print id to send/set in sv reprository
	
			//test("baseid",$baseid);
		
		} else if($count_prints == "4") { # 2ND TIME
			
			//test("count_prints2",$count_prints);
			
			# get baseid to send/set in sv reprository
			$baseid = $current_base_prints[baseid];
		
			# get filenames based on voiceid's from existing baseprint (only once here since all voiceid are the same)
			$voiceid1_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid LIKE '{$current_base_prints[voiceid1]}'");

			# create array for curl session to make/update exsiting base print
			$path_to_audio = NULL;
			$path_to_audio = array();
			$path_to_audio[0] = NULL; # keept $i value consistant with session results + voiceids
			$path_to_audio[1] = "/root/audio/incoming_voice_authorizations/" . $voiceid1_filename . ".ul";
			$path_to_audio[2] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul"; # makes for better prints and cycling off
			$path_to_audio[3] = "/root/audio/incoming_voice_authorizations/" . $voiceid1_filename . ".ul"; # "
			$path_to_audio[4] = "/root/audio/incoming_voice_authorizations/" . $voiceid1_filename . ".ul"; # "
			$path_to_audio[5] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul"; # makes for better prints and cycling off
			
			# update db:
			updateTHECASHIER("UPDATE base_prints SET voiceid2 = '" . $voiceid . "' WHERE memberid = '$memberid'");
			updateTHECASHIER("UPDATE base_prints SET voiceid5 = '" . $voiceid . "' WHERE memberid = '$memberid'");
		

		} else { # ALL OTHER TIMES
			
			//test("count_prints",$count_prints);
			
			# get baseid to send/set in sv reprository
			$baseid = $current_base_prints[baseid];

			# get filenames based on voiceid's from existing baseprint
			$voiceid2_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid LIKE '" . $current_base_prints[voiceid2] . "'");
			$voiceid3_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid LIKE '" . $current_base_prints[voiceid3] . "'");
			$voiceid4_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid LIKE '" . $current_base_prints[voiceid4] . "'");
			$voiceid5_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid LIKE '" . $current_base_prints[voiceid5] . "'");
			
			$path_to_audio = NULL;
			$path_to_audio = array();
			$path_to_audio[0] = NULL; # keept $i value consistant with session results + voiceids
			$path_to_audio[1] = "/root/audio/incoming_voice_authorizations/" . $voiceid2_filename . ".ul";
			$path_to_audio[2] = "/root/audio/incoming_voice_authorizations/" . $voiceid3_filename . ".ul";
			$path_to_audio[3] = "/root/audio/incoming_voice_authorizations/" . $voiceid4_filename . ".ul";
			$path_to_audio[4] = "/root/audio/incoming_voice_authorizations/" . $voiceid5_filename . ".ul";
			$path_to_audio[5] = "/root/audio/incoming_voice_authorizations/" . $new_filename . ".ul";

			# update db:
			updateTHECASHIER("UPDATE base_prints SET voiceid1 = '" . $current_base_prints[voiceid2] . "' WHERE memberid = '$memberid'");
			updateTHECASHIER("UPDATE base_prints SET voiceid2 = '" . $current_base_prints[voiceid3] . "' WHERE memberid = '$memberid'");
			updateTHECASHIER("UPDATE base_prints SET voiceid3 = '" . $current_base_prints[voiceid4] . "' WHERE memberid = '$memberid'");
			updateTHECASHIER("UPDATE base_prints SET voiceid4 = '" . $current_base_prints[voiceid5] . "' WHERE memberid = '$memberid'");
			updateTHECASHIER("UPDATE base_prints SET voiceid5 = '" . $voiceid . "' WHERE memberid = '$memberid'");
		
		}
		
	} #end if(enroll)
		
		
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	### IF "BOUND":
	
	if(is_array($path_to_audio)) {
	
		#create tmp file for cookie
		$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
		curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
		//test("URI","http://203.215.152.190:9080/ibmsiv/startsession?voiceprint=" . $baseid . "&mode=" . $action);
		curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
		curl_setopt($send_session, CURLOPT_POSTFIELDS,"voiceprint=" . $baseid . "&mode=" . $action);
		
		$send_results = NULL;
		$send_results = array();
		$send_results[0] = curl_exec($send_session);

		# prep for next curl stage:
		curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify");
		
		$i = 1;
		while($path_to_audio[$i]) {
		
			//test("URI","http://203.215.152.190:9080/ibmsiv/verify?input-wave-uri=" . $path_to_audio[$i]);
			// curl_setopt($send_session, CURLOPT_POSTFIELDS,"voiceprint=" . $voiceprint_id . "&input-wave-uri=" . $path_to_audio[$i]);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,"input-wave-uri=" . $path_to_audio[$i]);
			$send_results[$i] = curl_exec($send_session);
			
			if(!$send_results[$i]) {
				$send_results[$i] = curl_error($send_session);
			}
		
			$i++;
		}
		
		//test("URI","http://203.215.152.190:9080/ibmsiv/endsession");
		curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
		curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession");
		$send_results[$i] = curl_exec($send_session);
	
	
	### UNBOUND:
	
	} else {
	
		curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/" . $action);
		curl_setopt($send_session, CURLOPT_POSTFIELDS,"voiceprint=" . $baseid . "&input-wave-uri=" . $path_to_audio);
		$send_results =  curl_exec($send_session);

		if(!$send_session) {
			$send_session = curl_error($send_session);
		}
	
	}
	
	curl_close($send_session);
	
	return $send_results;
}
	
	
	
	
	
	

function minimizeState($state) {
	
	$state2 = trim($state);
	$state3 = str_replace(".","",$state2);
	$state4 = str_replace("-","",$state3);
	$full_state = ucwords(strtolower($state4));
	if(($full_state == "Alabama") || ($full_state == "Al")) {
		$minimized_state = "AL";
	} else if(($full_state == "Alaska") || ($full_state == "Ak")) {
		$minimized_state = "AK";
	} else if(($full_state == "Arizona") || ($full_state == "Az")) {
		$minimized_state = "AZ";
	} else if(($full_state == "Arkansas") || ($full_state == "Ar")) {
		$minimized_state = "AR";
	} else if(($full_state == "California") || ($full_state == "Ca")) {
		$minimized_state = "CA";
	} else if(($full_state == "Colorado") || ($full_state == "Co")) {
		$minimized_state = "CO";
	} else if(($full_state == "Connecticut") || ($full_state == "Ct")) {
		$minimized_state = "CT";
	} else if(($full_state == "Delaware") || ($full_state == "De")) {
		$minimized_state = "DE";
	} else if(($full_state == "District Of Columbia") || ($full_state ==
"Dc")) {
		$minimized_state = "DC";
	} else if(($full_state == "Dist Of Columbia") || ($full_state == "Dc")) {
		$minimized_state = "DC";
	} else if(($full_state == "Florida") || ($full_state == "Fl")) {
		$minimized_state = "FL";
	} else if(($full_state == "Georgia") || ($full_state == "Ga")) {
		$minimized_state = "GA";
	} else if(($full_state == "Hawaii") || ($full_state == "Hi")) {
		$minimized_state = "HI";
	} else if(($full_state == "Idaho") || ($full_state == "Id")) {
		$minimized_state = "ID";
	} else if(($full_state == "Illinois") || ($full_state == "Il")) {
		$minimized_state = "IL";
	} else if(($full_state == "Indiana") || ($full_state == "In")) {
		$minimized_state = "IN";
	} else if(($full_state == "Iowa") || ($full_state == "Ia")) {
		$minimized_state = "IA";
	} else if(($full_state == "Kansas") || ($full_state == "Ks")) {
		$minimized_state = "KS";
	} else if(($full_state == "Kentucky") || ($full_state == "Ky")) {
		$minimized_state = "KY";
	} else if(($full_state == "Louisiana") || ($full_state == "La")) {
		$minimized_state = "LA";
	} else if(($full_state == "Maine") || ($full_state == "Me")) {
		$minimized_state = "ME";
	} else if(($full_state == "Maryland") || ($full_state == "Md")) {
		$minimized_state = "MD";
	} else if(($full_state == "Massachusetts") || ($full_state == "Ma")) {
		$minimized_state = "MA";
	} else if(($full_state == "Michigan") || ($full_state == "Mi")) {
		$minimized_state = "MI";
	} else if(($full_state == "Minnesota") || ($full_state == "Mn")) {
		$minimized_state = "MN";
	} else if(($full_state == "Mississippi") || ($full_state == "Ms")) {
		$minimized_state = "MS";
	} else if(($full_state == "Missouri") || ($full_state == "Mo")) {
		$minimized_state = "MO";
	} else if(($full_state == "Montana") || ($full_state == "Mt")) {
		$minimized_state = "MT";
	} else if(($full_state == "Nebraska") || ($full_state == "Ne")) {
		$minimized_state = "NE";
	} else if(($full_state == "Nevada") || ($full_state == "Nv")) {
		$minimized_state = "NV";
	} else if(($full_state == "New Hampshire") || ($full_state == "Nh")) {
		$minimized_state = "NH";
	} else if(($full_state == "New Jersey") || ($full_state == "Nj")) {
		$minimized_state = "NJ";
	} else if(($full_state == "New Mexico") || ($full_state == "Nm")) {
		$minimized_state = "NM";
	} else if(($full_state == "New York") || ($full_state == "Ny")) {
		$minimized_state = "NY";
	} else if(($full_state == "North Carolina") || ($full_state == "Nc")) {
		$minimized_state = "NC";
	} else if(($full_state == "North Dakota") || ($full_state == "Nd")) {
		$minimized_state = "ND";
	} else if(($full_state == "Ohio") || ($full_state == "Oh")) {
		$minimized_state = "OH";
	} else if(($full_state == "Oklahoma") || ($full_state == "Ok")) {
		$minimized_state = "OK";
	} else if(($full_state == "Oregon") || ($full_state == "Or")) {
		$minimized_state = "OR";
	} else if(($full_state == "Pennsylvania") || ($full_state == "Pa")) {
		$minimized_state = "PA";
	} else if(($full_state == "Rhode Island") || ($full_state == "Ri")) {
		$minimized_state = "RI";
	} else if(($full_state == "South Carolina") || ($full_state == "Sc")) {
		$minimized_state = "SC";
	} else if(($full_state == "South Dakota") || ($full_state == "Sd")) {
		$minimized_state = "SD";
	} else if(($full_state == "Tennessee") || ($full_state == "Tn")) {
		$minimized_state = "TN";
	} else if(($full_state == "Texas") || ($full_state == "Tx")) {
		$minimized_state = "TX";
	} else if(($full_state == "Utah") || ($full_state == "Ut")) {
		$minimized_state = "UT";
	} else if(($full_state == "Vermont") || ($full_state == "Vt")) {
		$minimized_state = "VT";
	} else if(($full_state == "Virginia") || ($full_state == "Va")) {
		$minimized_state = "VA";
	} else if(($full_state == "Washington") || ($full_state == "Wa")) {
		$minimized_state = "WA";
	} else if(($full_state == "Washington DC") || ($full_state == "Dc")) {
		$minimized_state = "DC";
	} else if(($full_state == "Washington Dc") || ($full_state == "Dc")) {
		$minimized_state = "DC";
	} else if(($full_state == "Wash Dc") || ($full_state == "Dc")) {
		$minimized_state = "DC";
	} else if(($full_state == "West Virginia") || ($full_state == "Wv")) {
		$minimized_state = "WV";
	} else if(($full_state == "Wisconsin") || ($full_state == "Wi")) {
		$minimized_state = "WI";
	} else if(($full_state == "Wyoming") || ($full_state == "Wy")) {
		$minimized_state = "WY";
	
	### CANADA:
	} else if($full_state == "Alberta") {
		$minimized_state = "AB";	
	} else if($full_state == "British Columbia") {
		$minimized_state = "BC";	
	} else if($full_state == "Manitoba") {
		$minimized_state = "MB"; 
	} else if($full_state == "New Brunswick") {
		$minimized_state = "NB";	
	} else if($full_state == "New Foundland") {
		$minimized_state = "NF";	
	} else if($full_state == "Northwest Territories") {
		$minimized_state = "NT"; 
	} else if($full_state == "Nova Scotia") {
		$minimized_state = "NS";
	} else if($full_state == "Nunavut") {
		$minimized_state = "NT";
	} else if($full_state == "Ontario") {
		$minimized_state = "ON";
	} else if($full_state == "Prince Edward Island") {
		$minimized_state = "PE";
	} else if($full_state == "Quebec") {
		$minimized_state = "QC"; 
	} else if($full_state == "Saskatchewan") {
		$minimized_state = "SK";
	} else if($full_state == "Yukon") {
		$minimized_state = "YT";
	
	} else {
		
		### NON-US/CANADA
		$minimized_state = "OO";
	}
	return $minimized_state;
}



function minimizeCOUNTRY($incoming_country) {

	$country = strtoupper(trim($incoming_country));
	
	if($country == "USA") { return "US"; }
	if($country == "U.S.") { return "US"; }
	if($country == "U.S.A.") { return "US"; }
	
	$country = ucwords(strtolower(trim($country)));
	
	if($country == "Afghanistan") { return "AF"; }
	if($country == "Albania") { return "AL"; }
	if($country == "Algeria") { return "DZ"; }
	if($country == "American Samoa") { return "AS"; }
	if($country == "Andorra") { return "AD"; }
	if($country == "Angola") { return "AO"; }
	if($country == "Anguilla") { return "AI"; }
	if($country == "Antarctica") { return "AQ"; }
	if($country == "Antigua And Barbuda") { return "AG"; }
	if($country == "Argentina") { return "AR"; }
	if($country == "Armenia") { return "AM"; }
	if($country == "Aruba") { return "AW"; }
	if($country == "Australia") { return "AU"; }
	if($country == "Austria") { return "AT"; }
	if($country == "Azerbaijan") { return "AZ"; }
	if($country == "Bahamas") { return "BS"; }
	if($country == "Bahrain") { return "BH"; }
	if($country == "Bangladesh") { return "BD"; }
	if($country == "Barbados") { return "BB"; }
	if($country == "Belarus") { return "BY"; }
	if($country == "Belgium") { return "BE"; }
	if($country == "Belize") { return "BZ"; }
	if($country == "Benin") { return "BJ"; }
	if($country == "Bermuda") { return "BM"; }
	if($country == "Bhutan") { return "BT"; }
	if($country == "Bolivia") { return "BO"; }
	if($country == "Bosnia And Herzegowina") { return "BA"; }
	if($country == "Botswana") { return "BW"; }
	if($country == "Bouvet Island") { return "BV"; }
	if($country == "Brazil") { return "BR"; }
	if($country == "British Indian Ocean Terr.") { return "IO"; }
	if($country == "Brunei Darussalam") { return "BN"; }
	if($country == "Bulgaria") { return "BG"; }
	if($country == "Burkina Faso") { return "BF"; }
	if($country == "Burundi") { return "BI"; }
	if($country == "Cambodia") { return "KH"; }
	if($country == "Cameroon") { return "CM"; }
	if($country == "Canada") { return "CA"; }
	if($country == "Cape Verde") { return "CV"; }
	if($country == "Cayman Islands") { return "KY"; }
	if($country == "Central African Republic") { return "CF"; }
	if($country == "Chad") { return "TD"; }
	if($country == "Chile") { return "CL"; }
	if($country == "China") { return "CN"; }
	if($country == "Christmas Island") { return "CX"; }
	if($country == "Cocos (Keeling) Islands") { return "CC"; }
	if($country == "Colombia") { return "CO"; }
	if($country == "Comoros") { return "KM"; }
	if($country == "Congo") { return "CG"; }
	if($country == "Cook Islands") { return "CK"; }
	if($country == "Costa Rica") { return "CR"; }
	if($country == "Cote D'Ivoire") { return "CI"; }
	if($country == "Croatia") { return "HR"; }
	if($country == "Cuba") { return "CU"; }
	if($country == "Cyprus") { return "CY"; }
	if($country == "Czech Republic") { return "CZ"; }
	if($country == "Denmark") { return "DK"; }
	if($country == "Djibouti") { return "DJ"; }
	if($country == "Dominica") { return "DM"; }
	if($country == "Dominican Republic") { return "DO"; }
	if($country == "East Timor") { return "TP"; }
	if($country == "Ecuador") { return "EC"; }
	if($country == "Egypt") { return "EG"; }
	if($country == "El Salvador") { return "SV"; }
	if($country == "Equatorial Guinea") { return "GQ"; }
	if($country == "Eritrea") { return "ER"; }
	if($country == "Estonia") { return "EE"; }
	if($country == "Ethiopia") { return "ET"; }
	if($country == "Falkland Islands") { return "FK"; }
	if($country == "Faroe Islands") { return "FO"; }
	if($country == "Fiji") { return "FJ"; }
	if($country == "Finland") { return "FI"; }
	if($country == "France") { return "FR"; }
	if($country == "France, Metropolitan") { return "FX"; }
	if($country == "French Guiana") { return "GF"; }
	if($country == "French Polynesia") { return "PF"; }
	if($country == "French Southern Territories") { return "TF"; }
	if($country == "Gabon") { return "GA"; }
	if($country == "Gambia") { return "GM"; }
	if($country == "Georgia") { return "GE"; }
	if($country == "Germany") { return "DE"; }
	if($country == "Ghana") { return "GH"; }
	if($country == "Gibraltar") { return "GI"; }
	if($country == "Greece") { return "GR"; }
	if($country == "Greenland") { return "GL"; }
	if($country == "Grenada") { return "GD"; }
	if($country == "Guadeloupe") { return "GP"; }
	if($country == "Guam") { return "GU"; }
	if($country == "Guatemala") { return "GT"; }
	if($country == "Guinea") { return "GN"; }
	if($country == "Guinea-Bissau") { return "GW"; }
	if($country == "Guyana") { return "GY"; }
	if($country == "Haiti") { return "HT"; }
	if($country == "Heard And McDonald Islands") { return "HM"; }
	if($country == "Honduras") { return "HN"; }
	if($country == "Hong Kong") { return "HK"; }
	if($country == "Hungary") { return "HU"; }
	if($country == "Iceland") { return "IS"; }
	if($country == "India") { return "IN"; }
	if($country == "Indonesia") { return "ID"; }
	if($country == "Iran") { return "IR"; }
	if($country == "Iraq") { return "IQ"; }
	if($country == "Ireland") { return "IE"; }
	if($country == "Israel") { return "IL"; }
	if($country == "Italy") { return "IT"; }
	if($country == "Jamaica") { return "JM"; }
	if($country == "Japan") { return "JP"; }
	if($country == "Jordan") { return "JO"; }
	if($country == "Kazakhstan") { return "KZ"; }
	if($country == "Kenya") { return "KE"; }
	if($country == "Kiribati") { return "KI"; }
	if($country == "North Korea") { return "KP"; }
	if($country == "South Korea") { return "KR"; }
	if($country == "Kuwait") { return "KW"; }
	if($country == "Kyrgyzstan") { return "KG"; }
	if($country == "Lao People's Republic") { return "LA"; }
	if($country == "Latvia") { return "LV"; }
	if($country == "Lebanon") { return "LB"; }
	if($country == "Lesotho") { return "LS"; }
	if($country == "Liberia") { return "LR"; }
	if($country == "Libyan Arab Jamahiriya") { return "LY"; }
	if($country == "Liechtenstein") { return "LI"; }
	if($country == "Lithuania") { return "LT"; }
	if($country == "Luxembourg") { return "LU"; }
	if($country == "Macau") { return "MO"; }
	if($country == "Macedonia") { return "MK"; }
	if($country == "Madagascar") { return "MG"; }
	if($country == "Malawi") { return "MW"; }
	if($country == "Malaysia") { return "MY"; }
	if($country == "Maldives") { return "MV"; }
	if($country == "Mali") { return "ML"; }
	if($country == "Malta") { return "MT"; }
	if($country == "Marshall Islands") { return "MH"; }
	if($country == "Martinique") { return "MQ"; }
	if($country == "Mauritania") { return "MR"; }
	if($country == "Mauritius") { return "MU"; }
	if($country == "Mayotte") { return "YT"; }
	if($country == "Mexico") { return "MX"; }
	if($country == "Micronesia") { return "FM"; }
	if($country == "Moldova") { return "MD"; }
	if($country == "Monaco") { return "MC"; }
	if($country == "Mongolia") { return "MN"; }
	if($country == "Montserrat") { return "MS"; }
	if($country == "Morocco") { return "MA"; }
	if($country == "Mozambique") { return "MZ"; }
	if($country == "Myanmar") { return "MM"; }
	if($country == "Namibia") { return "NA"; }
	if($country == "Nauru") { return "NR"; }
	if($country == "Nepal") { return "NP"; }
	if($country == "Netherlands") { return "NL"; }
	if($country == "Netherlands Antilles") { return "AN"; }
	if($country == "New Caledonia") { return "NC"; }
	if($country == "New Zealand") { return "NZ"; }
	if($country == "Nicaragua") { return "NI"; }
	if($country == "Niger") { return "NE"; }
	if($country == "Nigeria") { return "NG"; }
	if($country == "Niue") { return "NU"; }
	if($country == "Norfolk Island") { return "NF"; }
	if($country == "Northern Mariana Islands") { return "MP"; }
	if($country == "Norway") { return "NO"; }
	if($country == "Oman") { return "OM"; }
	if($country == "Pakistan") { return "PK"; }
	if($country == "Palau") { return "PW"; }
	if($country == "Panama") { return "PA"; }
	if($country == "Papua NewGuinea") { return "PG"; }
	if($country == "Paraguay") { return "PY"; }
	if($country == "Peru") { return "PE"; }
	if($country == "Philippines") { return "PH"; }
	if($country == "Pitcairn") { return "PN"; }
	if($country == "Poland") { return "PL"; }
	if($country == "Portugal") { return "PT"; }
	if($country == "Puerto Rico") { return "PR"; }
	if($country == "Qatar") { return "QA"; }
	if($country == "Reunion") { return "RE"; }
	if($country == "Romania") { return "RO"; }
	if($country == "Russian Federation") { return "RU"; }
	if($country == "Rwanda") { return "RW"; }
	if($country == "Saint Kitts And Nevis") { return "KN"; }
	if($country == "Saint Lucia") { return "LC"; }
	if($country == "St Vincent/The Grenadines") { return "VC"; }
	if($country == "Samoa") { return "WS"; }
	if($country == "San Marino") { return "SM"; }
	if($country == "Sao Tome And Principe") { return "ST"; }
	if($country == "Saudi Arabia") { return "SA"; }
	if($country == "Senegal") { return "SN"; }
	if($country == "Seychelles") { return "SC"; }
	if($country == "Sierra Leone") { return "SL"; }
	if($country == "Singapore") { return "SG"; }
	if($country == "Slovakia") { return "SK"; }
	if($country == "Slovenia") { return "SI"; }
	if($country == "Solomon Islands") { return "SB"; }
	if($country == "Somalia") { return "SO"; }
	if($country == "South Africa") { return "ZA"; }
	if($country == "South Georgia/S.Sandwich Isl.") { return "GS"; }
	if($country == "Spain") { return "ES"; }
	if($country == "Sri Lanka") { return "LK"; }
	if($country == "St Helena") { return "SH"; }
	if($country == "St Pierre and Miquelon") { return "PM"; }
	if($country == "Sudan") { return "SD"; }
	if($country == "Suriname") { return "SR"; }
	if($country == "Svalbard And Jan Mayen Isl.") { return "SJ"; }
	if($country == "Swaziland") { return "SZ"; }
	if($country == "Sweden") { return "SE"; }
	if($country == "Switzerland") { return "CH"; }
	if($country == "Syrian Arab Republic") { return "SY"; }
	if($country == "Taiwan") { return "TW"; }
	if($country == "Tajikistan") { return "TJ"; }
	if($country == "Tanzania") { return "TZ"; }
	if($country == "Thailand") { return "TH"; }
	if($country == "Togo") { return "TG"; }
	if($country == "Tokelau") { return "TK"; }
	if($country == "Tonga") { return "TO"; }
	if($country == "Trinidad And Tobago") { return "TT"; }
	if($country == "Tunisia") { return "TN"; }
	if($country == "Turkey") { return "TR"; }
	if($country == "Turkmenistan") { return "TM"; }
	if($country == "Turks And Caicos Islands") { return "TC"; }
	if($country == "Tuvalu") { return "TV"; }
	if($country == "Uganda") { return "UG"; }
	if($country == "Ukraine") { return "UA"; }
	if($country == "United Arab Emirates") { return "AE"; }
	if($country == "United Kingdom") { return "GB"; }
	if($country == "United States") { return "US"; }
	if($country == "United States Minor Outlying Isl.") { return "UM"; }
	if($country == "Uruguay") { return "UY"; }
	if($country == "Uzbekistan") { return "UZ"; }
	if($country == "Vanuatu") { return "VU"; }
	if($country == "Vatican City State") { return "VA"; }
	if($country == "Venezuela") { return "VE"; }
	if($country == "Viet Nam") { return "VN"; }
	if($country == "Virgin Islands (British)") { return "VG"; }
	if($country == "Virgin Islands (U.S.)") { return "VI"; }
	if($country == "Wallis And Futuna Islands") { return "WF"; }
	if($country == "Western Sahara") { return "EH"; }
	if($country == "Yemen") { return "YE"; }
	if($country == "Zaire") { return "ZR"; }
	if($country == "Zambia") { return "ZM"; }
	if($country == "Zimbabwe") { return "ZW"; }
	return $incoming_country;
}



function prettySTATE($incoming_state) {
	
	$state = strtoupper(trim(str_replace(".","",$incoming_state)));

	if($state == "OO") { return "Not US/Canada"; }
	if($state == "AL") { return "Alabama"; }
	if($state == "AK") { return "Alaska"; }
	if($state == "AZ") { return "Arizona"; }
	if($state == "AR") { return "Arkansas"; }
	if($state == "CA") { return "California"; }
	if($state == "CO") { return "Colorado"; }
	if($state == "CT") { return "Connecticut"; }
	if($state == "DC") { return "District of Columbia"; }
	if($state == "DE") { return "Delaware"; }
	if($state == "FL") { return "Florida"; }
	if($state == "GA") { return "Georgia"; }
	if($state == "HI") { return "Hawaii"; }
	if($state == "ID") { return "Idaho"; }
	if($state == "IL") { return "Illinois"; }
	if($state == "IN") { return "Indiana"; }
	if($state == "IA") { return "Iowa"; }
	if($state == "KS") { return "Kansas"; }
	if($state == "KY") { return "Kentucky"; }
	if($state == "LA") { return "Louisiana"; }
	if($state == "ME") { return "Maine"; }
	if($state == "MD") { return "Maryland"; }
	if($state == "MA") { return "Massachusetts"; }
	if($state == "MI") { return "Michigan"; }
	if($state == "MN") { return "Minnesota"; }
	if($state == "MS") { return "Mississippi"; }
	if($state == "MO") { return "Missouri"; }
	if($state == "MT") { return "Montana"; }
	if($state == "NE") { return "Nebraska"; }
	if($state == "NV") { return "Nevada"; }
	if($state == "NH") { return "New Hampshire"; }
	if($state == "NJ") { return "New Jersey"; }
	if($state == "NM") { return "New Mexico"; }
	if($state == "NY") { return "New York"; }
	if($state == "NC") { return "North Carolina"; }
	if($state == "ND") { return "North Dakota"; }
	if($state == "OH") { return "Ohio"; }
	if($state == "OK") { return "Oklahoma"; }
	if($state == "OR") { return "Oregon"; }
	if($state == "PA") { return "Pennsylvania"; }
	if($state == "PR") { return "Puerto Rico"; }
	if($state == "RI") { return "Rhode Island"; }
	if($state == "SC") { return "South Carolina"; }
	if($state == "SD") { return "South Dakota"; }
	if($state == "TN") { return "Tennessee"; }
	if($state == "TX") { return "Texas"; }
	if($state == "UT") { return "Utah"; }
	if($state == "VT") { return "Vermont"; }
	if($state == "VA") { return "Virginia"; }
	if($state == "WA") { return "Washington"; }
	if($state == "WV") { return "West Virginia"; }
	if($state == "WI") { return "Wisconsin"; }
	if($state == "WY") { return "Wyoming"; }

	## CANADA: 
	if($state == "AB") { return "Alberta"; }
	if($state == "BC") { return "British Columbia"; }
	if($state == "MB") { return "Manitoba"; }
	if($state == "NB") { return "New Brunswick"; }
	if($state == "NF") { return "New Foundland"; }
	if($state == "NT") { return "Northwest Territories"; }
	if($state == "NS") { return "Nova Scotia"; }
	if($state == "NT") { return "Nunavut"; }
	if($state == "ON") { return "Ontario"; }
	if($state == "PE") { return "Prince Edward Island"; }
	if($state == "QC") { return "Quebec"; }
	if($state == "SK") { return "Saskatchewan"; }
	if($state == "YT") { return "Yukon"; }
}


function prettyCOUNTRY($incoming_country) {
	
	$country = strtoupper(trim(str_replace(".","",$incoming_country)));
	
	if($country == "AF") { return "Afghanistan"; }
	if($country == "AL") { return "Albania"; }
	if($country == "DZ") { return "Algeria"; }
	if($country == "AS") { return "American Samoa"; }
	if($country == "AD") { return "Andorra"; }
	if($country == "AO") { return "Angola"; }
	if($country == "AI") { return "Anguilla"; }
	if($country == "AQ") { return "Antarctica"; }
	if($country == "AG") { return "Antigua & Barbuda"; }
	if($country == "AR") { return "Argentina"; }
	if($country == "AM") { return "Armenia"; }
	if($country == "AW") { return "Aruba"; }
	if($country == "AU") { return "Australia"; }
	if($country == "AT") { return "Austria"; }
	if($country == "AZ") { return "Azerbaijan"; }
	if($country == "BS") { return "Bahamas"; }
	if($country == "BH") { return "Bahrain"; }
	if($country == "BD") { return "Bangladesh"; }
	if($country == "BB") { return "Barbados"; }
	if($country == "BY") { return "Belarus"; }
	if($country == "BE") { return "Belgium"; }
	if($country == "BZ") { return "Belize"; }
	if($country == "BJ") { return "Benin"; }
	if($country == "BM") { return "Bermuda"; }
	if($country == "BT") { return "Bhutan"; }
	if($country == "BO") { return "Bolivia"; }
	if($country == "BA") { return "Bosnia & Herzegowina"; }
	if($country == "BW") { return "Botswana"; }
	if($country == "BV") { return "Bouvet Island"; }
	if($country == "BR") { return "Brazil"; }
	if($country == "IO") { return "British Indian Ocean Terr."; }
	if($country == "BN") { return "Brunei Darussalam"; }
	if($country == "BG") { return "Bulgaria"; }
	if($country == "BF") { return "Burkina Faso"; }
	if($country == "BI") { return "Burundi"; }
	if($country == "KH") { return "Cambodia"; }
	if($country == "CM") { return "Cameroon"; }
	if($country == "CA") { return "Canada"; }
	if($country == "CV") { return "Cape Verde"; }
	if($country == "KY") { return "Cayman Islands"; }
	if($country == "CF") { return "Central African Republic"; }
	if($country == "TD") { return "Chad"; }
	if($country == "CL") { return "Chile"; }
	if($country == "CN") { return "China"; }
	if($country == "CX") { return "Christmas Island"; }
	if($country == "CC") { return "Cocos (Keeling) Islands"; }
	if($country == "CO") { return "Colombia"; }
	if($country == "KM") { return "Comoros"; }
	if($country == "CG") { return "Congo"; }
	if($country == "CK") { return "Cook Islands"; }
	if($country == "CR") { return "Costa Rica"; }
	if($country == "CI") { return "Cote D'Ivoire"; }
	if($country == "HR") { return "Croatia"; }
	if($country == "CU") { return "Cuba"; }
	if($country == "CY") { return "Cyprus"; }
	if($country == "CZ") { return "Czech Republic"; }
	if($country == "DK") { return "Denmark"; }
	if($country == "DJ") { return "Djibouti"; }
	if($country == "DM") { return "Dominica"; }
	if($country == "DO") { return "Dominican Republic"; }
	if($country == "TP") { return "East Timor"; }
	if($country == "EC") { return "Ecuador"; }
	if($country == "EG") { return "Egypt"; }
	if($country == "SV") { return "El Salvador"; }
	if($country == "GQ") { return "Equatorial Guinea"; }
	if($country == "ER") { return "Eritrea"; }
	if($country == "EE") { return "Estonia"; }
	if($country == "ET") { return "Ethiopia"; }
	if($country == "FK") { return "Falkland Islands"; }
	if($country == "FO") { return "Faroe Islands"; }
	if($country == "FJ") { return "Fiji"; }
	if($country == "FI") { return "Finland"; }
	if($country == "FR") { return "France"; }
	if($country == "FX") { return "France, Metropolitan"; }
	if($country == "GF") { return "French Guiana"; }
	if($country == "PF") { return "French Polynesia"; }
	if($country == "TF") { return "French Southern Territories"; }
	if($country == "GA") { return "Gabon"; }
	if($country == "GM") { return "Gambia"; }
	if($country == "GE") { return "Georgia"; }
	if($country == "DE") { return "Germany"; }
	if($country == "GH") { return "Ghana"; }
	if($country == "GI") { return "Gibraltar"; }
	if($country == "GR") { return "Greece"; }
	if($country == "GL") { return "Greenland"; }
	if($country == "GD") { return "Grenada"; }
	if($country == "GP") { return "Guadeloupe"; }
	if($country == "GU") { return "Guam"; }
	if($country == "GT") { return "Guatemala"; }
	if($country == "GN") { return "Guinea"; }
	if($country == "GW") { return "Guinea-Bissau"; }
	if($country == "GY") { return "Guyana"; }
	if($country == "HT") { return "Haiti"; }
	if($country == "HM") { return "Heard & McDonald Islands"; }
	if($country == "HN") { return "Honduras"; }
	if($country == "HK") { return "Hong Kong"; }
	if($country == "HU") { return "Hungary"; }
	if($country == "IS") { return "Iceland"; }
	if($country == "IN") { return "India"; }
	if($country == "ID") { return "Indonesia"; }
	if($country == "IR") { return "Iran"; }
	if($country == "IQ") { return "Iraq"; }
	if($country == "IE") { return "Ireland"; }
	if($country == "IL") { return "Israel"; }
	if($country == "IT") { return "Italy"; }
	if($country == "JM") { return "Jamaica"; }
	if($country == "JP") { return "Japan"; }
	if($country == "JO") { return "Jordan"; }
	if($country == "KZ") { return "Kazakhstan"; }
	if($country == "KE") { return "Kenya"; }
	if($country == "KI") { return "Kiribati"; }
	if($country == "KP") { return "North Korea"; }
	if($country == "KR") { return "South Korea"; }
	if($country == "KW") { return "Kuwait"; }
	if($country == "KG") { return "Kyrgyzstan"; }
	if($country == "LA") { return "Lao People's Republic"; }
	if($country == "LV") { return "Latvia"; }
	if($country == "LB") { return "Lebanon"; }
	if($country == "LS") { return "Lesotho"; }
	if($country == "LR") { return "Liberia"; }
	if($country == "LY") { return "Libyan Arab Jamahiriya"; }
	if($country == "LI") { return "Liechtenstein"; }
	if($country == "LT") { return "Lithuania"; }
	if($country == "LU") { return "Luxembourg"; }
	if($country == "MO") { return "Macau"; }
	if($country == "MK") { return "Macedonia"; }
	if($country == "MG") { return "Madagascar"; }
	if($country == "MW") { return "Malawi"; }
	if($country == "MY") { return "Malaysia"; }
	if($country == "MV") { return "Maldives"; }
	if($country == "ML") { return "Mali"; }
	if($country == "MT") { return "Malta"; }
	if($country == "MH") { return "Marshall Islands"; }
	if($country == "MQ") { return "Martinique"; }
	if($country == "MR") { return "Mauritania"; }
	if($country == "MU") { return "Mauritius"; }
	if($country == "YT") { return "Mayotte"; }
	if($country == "MX") { return "Mexico"; }
	if($country == "FM") { return "Micronesia"; }
	if($country == "MD") { return "Moldova"; }
	if($country == "MC") { return "Monaco"; }
	if($country == "MN") { return "Mongolia"; }
	if($country == "MS") { return "Montserrat"; }
	if($country == "MA") { return "Morocco"; }
	if($country == "MZ") { return "Mozambique"; }
	if($country == "MM") { return "Myanmar"; }
	if($country == "NA") { return "Namibia"; }
	if($country == "NR") { return "Nauru"; }
	if($country == "NP") { return "Nepal"; }
	if($country == "NL") { return "Netherlands"; }
	if($country == "AN") { return "Netherlands Antilles"; }
	if($country == "NC") { return "New Caledonia"; }
	if($country == "NZ") { return "New Zealand"; }
	if($country == "NI") { return "Nicaragua"; }
	if($country == "NE") { return "Niger"; }
	if($country == "NG") { return "Nigeria"; }
	if($country == "NU") { return "Niue"; }
	if($country == "NF") { return "Norfolk Island"; }
	if($country == "MP") { return "Northern Mariana Islands"; }
	if($country == "NO") { return "Norway"; }
	if($country == "OM") { return "Oman"; }
	if($country == "PK") { return "Pakistan"; }
	if($country == "PW") { return "Palau"; }
	if($country == "PA") { return "Panama"; }
	if($country == "PG") { return "Papua NewGuinea"; }
	if($country == "PY") { return "Paraguay"; }
	if($country == "PE") { return "Peru"; }
	if($country == "PH") { return "Philippines"; }
	if($country == "PN") { return "Pitcairn"; }
	if($country == "PL") { return "Poland"; }
	if($country == "PT") { return "Portugal"; }
	if($country == "PR") { return "Puerto Rico"; }
	if($country == "QA") { return "Qatar"; }
	if($country == "RE") { return "Reunion"; }
	if($country == "RO") { return "Romania"; }
	if($country == "RU") { return "Russian Federation"; }
	if($country == "RW") { return "Rwanda"; }
	if($country == "KN") { return "Saint Kitts & Nevis"; }
	if($country == "LC") { return "Saint Lucia"; }
	if($country == "VC") { return "St Vincent/The Grenadines"; }
	if($country == "WS") { return "Samoa"; }
	if($country == "SM") { return "San Marino"; }
	if($country == "ST") { return "Sao Tome & Principe"; }
	if($country == "SA") { return "Saudi Arabia"; }
	if($country == "SN") { return "Senegal"; }
	if($country == "SC") { return "Seychelles"; }
	if($country == "SL") { return "Sierra Leone"; }
	if($country == "SG") { return "Singapore"; }
	if($country == "SK") { return "Slovakia"; }
	if($country == "SI") { return "Slovenia"; }
	if($country == "SB") { return "Solomon Islands"; }
	if($country == "SO") { return "Somalia"; }
	if($country == "ZA") { return "South Africa"; }
	if($country == "GS") { return "South Georgia/S.Sandwich Isl."; }
	if($country == "ES") { return "Spain"; }
	if($country == "LK") { return "Sri Lanka"; }
	if($country == "SH") { return "St Helena"; }
	if($country == "PM") { return "St Pierre and Miquelon"; }
	if($country == "SD") { return "Sudan"; }
	if($country == "SR") { return "Suriname"; }
	if($country == "SJ") { return "Svalbard & Jan Mayen Isl."; }
	if($country == "SZ") { return "Swaziland"; }
	if($country == "SE") { return "Sweden"; }
	if($country == "CH") { return "Switzerland"; }
	if($country == "SY") { return "Syrian Arab Republic"; }
	if($country == "TW") { return "Taiwan"; }
	if($country == "TJ") { return "Tajikistan"; }
	if($country == "TZ") { return "Tanzania"; }
	if($country == "TH") { return "Thailand"; }
	if($country == "TG") { return "Togo"; }
	if($country == "TK") { return "Tokelau"; }
	if($country == "TO") { return "Tonga"; }
	if($country == "TT") { return "Trinidad & Tobago"; }
	if($country == "TN") { return "Tunisia"; }
	if($country == "TR") { return "Turkey"; }
	if($country == "TM") { return "Turkmenistan"; }
	if($country == "TC") { return "Turks & Caicos Islands"; }
	if($country == "TV") { return "Tuvalu"; }
	if($country == "UG") { return "Uganda"; }
	if($country == "UA") { return "Ukraine"; }
	if($country == "AE") { return "United Arab Emirates"; }
	if($country == "GB") { return "United Kingdom"; }
	if($country == "US") { return "United States"; }
	if($country == "US") { return "United States of America"; }
	if($country == "UM") { return "United States Minor Outlying Isl."; }
	if($country == "UY") { return "Uruguay"; }
	if($country == "UZ") { return "Uzbekistan"; }
	if($country == "VU") { return "Vanuatu"; }
	if($country == "VA") { return "Vatican City State"; }
	if($country == "VE") { return "Venezuela"; }
	if($country == "VN") { return "Viet Nam"; }
	if($country == "VG") { return "Virgin Islands (British)"; }
	if($country == "VI") { return "Virgin Islands (U.S.)"; }
	if($country == "WF") { return "Wallis & Futuna Islands"; }
	if($country == "EH") { return "Western Sahara"; }
	if($country == "YE") { return "Yemen"; }
	if($country == "ZR") { return "Zaire"; }
	if($country == "ZM") { return "Zambia"; }
	if($country == "ZW") { return "Zimbabwe"; }
}


function country_to_calling_code($incoming_country) {

	$country = strtoupper(trim($incoming_country));
	
	if($country == "USA") { return "1"; }
	if($country == "U.S.") { return "1"; }
	if($country == "U.S.A.") { return "1"; }
	
	$country = ucwords(strtolower(trim($country)));
	
	if($country == "Afghanistan") { return "93"; }
	if($country == "Albania") { return "355"; }
	if($country == "Algeria") { return "213"; }
	if($country == "American Samoa") { return "1684"; }
	if($country == "Andorra") { return "376"; }
	if($country == "Angola") { return "244"; }
	if($country == "Anguilla") { return "1264"; }
	
	if($country == "Antigua And Barbuda") { return "1268"; }
	if($country == "Antigua/Barbuda") { return "1268"; }
	if($country == "Antigua & Barbuda") { return "1268"; }
	if($country == "Antigua") { return "1268"; }
	
	if($country == "Argentina") { return "54"; }
	if($country == "Armenia") { return "374"; }
	if($country == "Aruba") { return "297"; }

	if($country == "Asencsion") { return "247"; }

	if($country == "Australia") { return "61"; }
	if($country == "Australian External Territories") { return "672"; }
	
	if($country == "Austria") { return "43"; }
	if($country == "Azerbaijan") { return "994"; }
	if($country == "Bahamas") { return "1242"; }
	if($country == "Bahrain") { return "973"; }
	if($country == "Bangladesh") { return "880"; }
	if($country == "Barbados") { return "1246"; }

	if($country == "Barbuda") { return "1268"; }

	if($country == "Belarus") { return "375"; }
	if($country == "Belgium") { return "32"; }
	if($country == "Belize") { return "501"; }
	if($country == "Benin") { return "229"; }
	if($country == "Bermuda") { return "1441"; }
	if($country == "Bhutan") { return "975"; }
	if($country == "Bolivia") { return "591"; }
	if($country == "Bosnia And Herzegowina") { return "387"; }
	if($country == "Botswana") { return "267"; }
	
	if($country == "Bouvet Island") { return ""; }
	
	if($country == "Brazil") { return "55"; }
	
	if($country == "British Indian Ocean Terr.") { return "1284"; }
	if($country == "British Virgin Islands") { return "1284"; }
	
	if($country == "Brunei Darussalam") { return "673"; }
	if($country == "Bulgaria") { return "359"; }
	if($country == "Burkina Faso") { return "226"; }
	if($country == "Burundi") { return "257"; }
	if($country == "Cambodia") { return "855"; }
	if($country == "Cameroon") { return "237"; }
	if($country == "Canada") { return "1"; }
	
	if($country == "Cape Verde") { return "238"; }
	if($country == "Cape Verde Islands") { return "238"; }
	
	if($country == "Cayman Islands") { return "1345"; }
	if($country == "Central African Republic") { return "236"; }
	if($country == "Chad") { return "235"; }

	if($country == "Chatham Island (New Zealand)") { return "64"; }
	
	if($country == "Chile") { return "56"; }
	
	if($country == "China") { return "86"; }
	if($country == "China (PRC)") { return "86"; }
	if($country == "Peoples Republic of China") { return "86"; }

	if($country == "Christmas Island") { return "618"; }
	
	if($country == "Cocos (Keeling) Islands") { return "61"; }
	if($country == "Cocos-Keeling Islands") { return "61"; }
	
	if($country == "Colombia") { return "57"; }
	if($country == "Comoros") { return "269"; }
	
	if($country == "Congo") { return "242"; }
	if($country == "Congo, De. Rep. of (Zaire)") { return "243"; }
	
	if($country == "Cook Islands") { return "682"; }
	if($country == "Costa Rica") { return "506"; }
	
	if($country == "Cote D'Ivoire") { return "225"; }
	if($country == "Cote D'Ivoire (Ivory Coast)") { return "225"; }
	if($country == "Ivory Coast") { return "225"; }
	
	if($country == "Croatia") { return "385"; }
	
	if($country == "Cuba") { return "53"; }
	if($country == "Cuba (Guantanamo Bay)") { return "5399"; }
	if($country == "Guantanamo Bay") { return "5399"; }
	
	if($country == "Cyprus") { return "357"; }
	if($country == "Czech Republic") { return "420"; }
	if($country == "Denmark") { return "45"; }
	
	if($country == "Diego Garcia") { return "246"; }
	
	if($country == "Djibouti") { return "253"; }
	if($country == "Dominica") { return "1767"; }
	if($country == "Dominican Republic") { return "1"; }
	if($country == "East Timor") { return "670"; }
	
	if($country == "Easter Island") { return "56"; }
	
	if($country == "Ecuador") { return "593"; }
	if($country == "Egypt") { return "20"; }
	if($country == "El Salvador") { return "503"; }
	
	if($country == "Ellipso (Mobile Satellite service)") { return "881"; }
	if($country == "EMSAT (Mobile Satellite service)") { return "88213"; }
	
	if($country == "Equatorial Guinea") { return "240"; }
	if($country == "Eritrea") { return "291"; }
	if($country == "Estonia") { return "372"; }
	if($country == "Ethiopia") { return "251"; }
	if($country == "Falkland Islands") { return "500"; }
	if($country == "Faroe Islands") { return "298"; }
	if($country == "Fiji") { return "679"; }
	if($country == "Finland") { return "358"; }
	if($country == "France") { return "33"; }
	
	if($country == "France, Metropolitan") { return ""; }
	if($country == "French Antillies") { return "596"; }
	
	if($country == "French Guiana") { return "594"; }
	if($country == "French Polynesia") { return "689"; }
	
	if($country == "French Southern Territories") { return ""; }
	
	if($country == "Gabon") { return "241"; }
	if($country == "Gabonese Republic") { return "241"; }
	
	if($country == "Gambia") { return "220"; }
	if($country == "Georgia") { return "995"; }
	if($country == "Germany") { return "49"; }
	if($country == "Ghana") { return "233"; }
	if($country == "Gibraltar") { return "350"; }

	if($country == "Global Mobile Satellite System (GMSS)") { return "881"; }
	if($country == "Globalstar (Mobile Satellite Service)") { return "881"; }
	
	if($country == "Greece") { return "30"; }
	if($country == "Greenland") { return "299"; }
	if($country == "Grenada") { return "1473"; }
	if($country == "Guadeloupe") { return "590"; }
	if($country == "Guam") { return "1671"; }
	if($country == "Guatemala") { return "502"; }
	if($country == "Guinea") { return "224"; }
	if($country == "Guinea-Bissau") { return "245"; }
	if($country == "Guyana") { return "592"; }
	if($country == "Haiti") { return "509"; }
	
	if($country == "Heard And McDonald Islands") { return ""; }
	
	if($country == "Honduras") { return "504"; }
	if($country == "Hong Kong") { return "852"; }
	if($country == "Hungary") { return "36"; }
	if($country == "Iceland") { return "354"; }
	
	if($country == "ICO Global (Mobile Satellite Service)") { return "881"; }
	
	if($country == "India") { return "91"; }
	if($country == "Indonesia") { return "62"; }
	
	if($country == "Inmarsat (Atlantic Ocean - East)") { return "871"; }
	if($country == "Inmarsat (Atlantic Ocean - West)") { return "874"; }
	if($country == "Inmarsat (Indian Ocean)") { return "873"; }
	if($country == "Inmarsat (Pacific Ocean)") { return "872"; }
	if($country == "Inmarsat SNAC") { return "870"; }
	if($country == "International Freephone Service") { return "800"; }
	if($country == "International Shared Cost Service (ISCS)") { return "808"; }

	if($country == "Iran") { return "98"; }
	if($country == "Iraq") { return "964"; }
	if($country == "Ireland") { return "353"; }

	if($country == "Iridium (Mobile Satellite service)") { return "881"; }
	
	if($country == "Israel") { return "972"; }
	if($country == "Italy") { return "39"; }
	if($country == "Jamaica") { return "1876"; }
	if($country == "Japan") { return "81"; }
	if($country == "Jordan") { return "962"; }
	if($country == "Kazakhstan") { return "7"; }
	if($country == "Kenya") { return "254"; }
	if($country == "Kiribati") { return "686"; }
	
	if($country == "North Korea") { return "850"; }
	if($country == "N. Korea") { return "850"; }
	if($country == "Korea (North)") { return "850"; }
	if($country == "Korea (South") { return "82"; }
	if($country == "S. Korea") { return "82"; }
	if($country == "South Korea") { return "82"; }
	
	if($country == "Kuwait") { return "965"; }
	
	if($country == "Kyrgyzstan") { return ""; }
	if($country == "Kyrgyz Republic") { return "996"; }
	
	if($country == "Lao People's Republic") { return "856"; }
	if($country == "Laos") { return "856"; }
	
	if($country == "Latvia") { return "371"; }
	if($country == "Lebanon") { return "961"; }
	if($country == "Lesotho") { return "266"; }
	if($country == "Liberia") { return "231"; }
	if($country == "Libyan Arab Jamahiriya") { return "218"; }
	
	if($country == "Libya") { return "218"; }
	
	if($country == "Liechtenstein") { return "423"; }
	if($country == "Lithuania") { return "370"; }
	if($country == "Luxembourg") { return "352"; }
	if($country == "Macau") { return "853"; }
	if($country == "Macedonia") { return "389"; }
	if($country == "Madagascar") { return "261"; }
	if($country == "Malawi") { return "265"; }
	if($country == "Malaysia") { return "60"; }
	if($country == "Maldives") { return "960"; }
	
	if($country == "Mali") { return "223"; }
	if($country == "Mali Republic") { return "223"; }
	
	if($country == "Malta") { return "356"; }
	if($country == "Marshall Islands") { return "692"; }
	if($country == "Martinique") { return "596"; }
	if($country == "Mauritania") { return "222"; }
	if($country == "Mauritius") { return "230"; }
	if($country == "Mayotte") { return "262"; }
	
	if($country == "Mayotte Island") { return "262"; }
	
	if($country == "Mexico") { return "52"; }
	if($country == "Micronesia") { return "691"; }
	
	if($country == "Micronesia, (Federal States of)") { return "691"; }
	if($country == "Midway Island") { return "1808"; }
	
	if($country == "Moldova") { return "373"; }
	if($country == "Monaco") { return "377"; }
	if($country == "Mongolia") { return "976"; }
	
	if($country == "Montenegro") { return "382"; }
	
	if($country == "Montserrat") { return "1664"; }
	if($country == "Morocco") { return "212"; }
	if($country == "Mozambique") { return "258"; }
	if($country == "Myanmar") { return "95"; }
	if($country == "Namibia") { return "264"; }
	if($country == "Nauru") { return "674"; }
	if($country == "Nepal") { return "977"; }
	if($country == "Netherlands") { return "31"; }
	if($country == "Netherlands Antilles") { return "599"; }
	
	if($country == "Nevis") { return "1869"; }
	
	if($country == "New Caledonia") { return "687"; }
	if($country == "New Zealand") { return "64"; }
	if($country == "Nicaragua") { return "505"; }
	if($country == "Niger") { return "227"; }
	if($country == "Nigeria") { return "234"; }
	if($country == "Niue") { return "683"; }
	if($country == "Norfolk Island") { return "672"; }
	if($country == "Northern Mariana Islands") { return "1670"; }
	if($country == "Norway") { return "47"; }
	if($country == "Oman") { return "968"; }
	if($country == "Pakistan") { return "92"; }
	if($country == "Palau") { return "680"; }
	
	if($country == "Palestine") { return "970"; }
	if($country == "Palestine Settlement") { return "970"; }
	
	if($country == "Panama") { return "507"; }
	
	if($country == "Papua New Guinea") { return "675"; }
	
	if($country == "Paraguay") { return "595"; }
	if($country == "Peru") { return "51"; }
	if($country == "Philippines") { return "63"; }
	
	if($country == "Pitcairn") { return ""; }
	
	if($country == "Poland") { return "48"; }
	if($country == "Portugal") { return "351"; }
	if($country == "Puerto Rico") { return "1"; }
	if($country == "Qatar") { return "974"; }
	
	if($country == "Reunion") { return "262"; }
	if($country == "Reunion Island") { return "262"; }
	
	if($country == "Romania") { return "40"; }
	
	if($country == "Russian Federation") { return "7"; }
	if($country == "Russia") { return "7"; }
	
	if($country == "Rwanda") { return "250"; }
	if($country == "Rwandese Republic") { return "250"; }
	if($country == "St. Helena") { return "290"; }
	
	if($country == "Saint Kitts And Nevis") { return "1869"; }
	if($country == "St. Kitts/Nevis") { return "1869"; }
	
	if($country == "Saint Lucia") { return "1758"; }
	if($country == "St. Lucia") { return "1758"; }
	
	if($country == "St Vincent/The Grenadines") { return "1758"; }
	if($country == "St. Vincent/The Grenadines") { return "1758"; }
	if($country == "St. Vincent and The Grenadines") { return "1758"; }
	if($country == "St. Vincent and Grenadines") { return "1758"; }
	if($country == "St. Vincent/Grenadines") { return "1758"; }
	
	if($country == "Samoa") { return "685"; }
	if($country == "San Marino") { return "378"; }
	if($country == "Sao Tome And Principe") { return "239"; }
	if($country == "Saudi Arabia") { return "966"; }
	if($country == "Senegal") { return "221"; }
	
	if($country == "Serbia") { return "381"; }
	
	if($country == "Seychelles") { return ""; }
	if($country == "Seychelles republic") { return "248"; }
	
	if($country == "Sierra Leone") { return "232"; }
	if($country == "Singapore") { return "65"; }
	
	if($country == "Slovakia") { return "421"; }
	if($country == "Slovak Republic") { return "421"; }
	
	if($country == "Slovenia") { return "386"; }
	if($country == "Solomon Islands") { return "677"; }
	
	if($country == "Somalia") { return "252"; }
	if($country == "Sonali Democratic Republic") { return "252"; }
	
	
	if($country == "South Africa") { return "27"; }
	
	if($country == "South Georgia/S.Sandwich Isl.") { return ""; }
	
	if($country == "Spain") { return "34"; }
	if($country == "Sri Lanka") { return "94"; }
	
	if($country == "St Helena") { return ""; }
	if($country == "St Pierre and Miquelon") { return ""; }
	
	if($country == "Sudan") { return "249"; }
	if($country == "Suriname") { return "597"; }
	
	if($country == "Svalbard And Jan Mayen Isl.") { return ""; }
	
	if($country == "Swaziland") { return "268"; }
	if($country == "Sweden") { return "46"; }
	if($country == "Switzerland") { return "41"; }
	
	if($country == "Syrian Arab Republic") { return "963"; }
	if($country == "Syria") { return "963"; }
	
	if($country == "Taiwan") { return "886"; }
	if($country == "Tajikistan") { return "992"; }
	if($country == "Tanzania") { return "255"; }
	if($country == "Thailand") { return "66"; }
	
	if($country == "Thuraya (Mobile Satellite service)") { return "88216"; }
	if($country == "Timor Leste") { return "670"; }
	
	if($country == "Togo") { return "228"; }
	if($country == "Togolese Republic") { return "228"; }
	
	if($country == "Tokelau") { return "690"; }
	
	if($country == "Tonga") { return "676"; }
	if($country == "Tonga Islands") { return "676"; }
	
	if($country == "Trinidad And Tobago") { return "1868"; }
	if($country == "Tunisia") { return "216"; }
	if($country == "Turkey") { return "90"; }
	if($country == "Turkmenistan") { return "993"; }
	if($country == "Turks And Caicos Islands") { return "1649"; }
	if($country == "Tuvalu") { return "688"; }
	if($country == "Uganda") { return "256"; }
	if($country == "Ukraine") { return "380"; }
	if($country == "United Arab Emirates") { return "971"; }
	if($country == "United Kingdom") { return "44"; }
	
	if($country == "United States") { return "1"; }
	if($country == "United States of America") { return "1"; }

	if($country == "Universal Personal Telecommunications (UPT)") { return "878"; }
	if($country == "United States Minor Outlying Isl.") { return "1340"; }
	if($country == "US Virgin Islands") { return "1340"; }
	
	if($country == "Uruguay") { return "598"; }
	if($country == "Uzbekistan") { return "998"; }
	if($country == "Vanuatu") { return "678"; }
	
	if($country == "Vatican City State") { return "3"; }
	if($country == "Vatican City") { return "3"; }
	
	if($country == "Venezuela") { return "58"; }
	
	if($country == "Vietnam") { return "84"; }
	
	if($country == "Virgin Islands (British)") { return "1284"; }
	if($country == "Virgin Islands (U.S.)") { return "1340"; }
	if($country == "Virgin Islands (US)") { return "1340"; }
	
	if($country == "Wallis And Futuna Islands") { return "681"; }
	
	if($country == "Western Sahara") { return ""; }
	
	if($country == "Yemen") { return "260"; }
	
	if($country == "Zaire") { return ""; }
	
	if($country == "Zambia") { return "260"; }
	
	if($country == "Zanzibar") { return "255"; }
	
	if($country == "Zimbabwe") { return "263"; }
	
	return null;
}





function calling_code_to_country_code($incoming_country_code) {

	//logf("/tmp/functions.txt","function start..........");

	$country_code = strtoupper(trim($incoming_country_code));
	
	if($country_code == "93") { return "AF"; }
	if($country_code == "355") { return "AL"; }
	if($country_code == "213") { return "DZ"; }
	if($country_code == "1784") { return "AS"; }
	if($country_code == "376") { return "AD"; }
	if($country_code == "244") { return "AO"; }
	if($country_code == "1264") { return "AI"; }
	if($country_code == "672") { return "AQ"; }
	if($country_code == "1268") { return "AG"; }
	if($country_code == "54") { return "AR"; }
	if($country_code == "374") { return "AM"; }
	if($country_code == "297") { return "AW"; }
	if($country_code == "61") { return "AU"; }
	if($country_code == "672") { return "AT"; }
	if($country_code == "994") { return "AZ"; }
	if($country_code == "1242") { return "BS"; }
	if($country_code == "973") { return "BH"; }
	if($country_code == "880") { return "BD"; }
	if($country_code == "1246") { return "BB"; }
	if($country_code == "375") { return "BY"; }
	if($country_code == "32") { return "BE"; }
	if($country_code == "501") { return "BZ"; }
	if($country_code == "229") { return "BJ"; }
	if($country_code == "1441") { return "BM"; }
	if($country_code == "975") { return "BT"; }
	if($country_code == "591") { return "BO"; }
	if($country_code == "387") { return "BA"; }
	if($country_code == "267") { return "BW"; }
	if($country_code == "n/a") { return "BV"; }
	if($country_code == "55") { return "BR"; }
	if($country_code == "1284") { return "IO"; }
	if($country_code == "673") { return "BN"; }
	if($country_code == "359") { return "BG"; }
	if($country_code == "226") { return "BF"; }
	if($country_code == "257") { return "BI"; }
	if($country_code == "855") { return "KH"; }
	if($country_code == "237") { return "CM"; }
	if($country_code == "1") { return "CA"; }
	if($country_code == "238") { return "CV"; }
	if($country_code == "1345") { return "KY"; }
	if($country_code == "236") { return "CF"; }
	if($country_code == "235") { return "TD"; }
	if($country_code == "56") { return "CL"; }
	if($country_code == "86") { return "CN"; }
	if($country_code == "618") { return "CX"; }
	if($country_code == "61") { return "CC"; }
	if($country_code == "242") { return "CO"; }
	if($country_code == "n/a") { return "KM"; }
	if($country_code == "242") { return "CG"; }
	if($country_code == "682") { return "CK"; }
	if($country_code == "385") { return "CR"; }
	if($country_code == "225") { return "CI"; }
	if($country_code == "385") { return "HR"; }
	if($country_code == "53") { return "CU"; }
	if($country_code == "357") { return "CY"; }
	if($country_code == "420") { return "CZ"; }
	if($country_code == "45") { return "DK"; }
	if($country_code == "253") { return "DJ"; }
	if($country_code == "1767") { return "DM"; }
	if($country_code == "1") { return "DO"; }
	if($country_code == "670") { return "TP"; }
	if($country_code == "593") { return "EC"; }
	if($country_code == "20") { return "EG"; }
	if($country_code == "503") { return "SV"; }
	if($country_code == "240") { return "GQ"; }
	if($country_code == "291") { return "ER"; }
	if($country_code == "372") { return "EE"; }
	if($country_code == "251") { return "ET"; }
	if($country_code == "500") { return "FK"; }
	if($country_code == "298") { return "FO"; }
	if($country_code == "679") { return "FJ"; }
	if($country_code == "358") { return "FI"; }
	if($country_code == "33") { return "FR"; }
	if($country_code == "n/a") { return "FX"; }
	if($country_code == "594") { return "GF"; }
	if($country_code == "689") { return "PF"; }
	if($country_code == "n/a") { return "TF"; }
	if($country_code == "241") { return "GA"; }
	if($country_code == "220") { return "GM"; }
	if($country_code == "995") { return "GE"; }
	if($country_code == "49") { return "DE"; }
	if($country_code == "233") { return "GH"; }
	if($country_code == "350") { return "GI"; }
	if($country_code == "30") { return "GR"; }
	if($country_code == "299") { return "GL"; }
	if($country_code == "1473") { return "GD"; }
	if($country_code == "590") { return "GP"; }
	if($country_code == "1671") { return "GU"; }
	if($country_code == "502") { return "GT"; }
	if($country_code == "224") { return "GN"; }
	if($country_code == "245") { return "GW"; }
	if($country_code == "592") { return "GY"; }
	if($country_code == "509") { return "HT"; }
	if($country_code == "n/a") { return "HM"; }
	if($country_code == "504") { return "HN"; }
	if($country_code == "852") { return "HK"; }
	if($country_code == "36") { return "HU"; }
	if($country_code == "354") { return "IS"; }
	if($country_code == "91") { return "IN"; }
	if($country_code == "62") { return "ID"; }
	if($country_code == "98") { return "IR"; }
	if($country_code == "964") { return "IQ"; }
	if($country_code == "353") { return "IE"; }
	if($country_code == "972") { return "IL"; }
	if($country_code == "39") { return "IT"; }
	if($country_code == "1876") { return "JM"; }
	if($country_code == "81") { return "JP"; }
	if($country_code == "962") { return "JO"; }
	if($country_code == "7") { return "KZ"; }
	if($country_code == "254") { return "KE"; }
	if($country_code == "686") { return "KI"; }
	if($country_code == "850") { return "KP"; }
	if($country_code == "82") { return "KR"; }
	if($country_code == "965") { return "KW"; }
	if($country_code == "996") { return "KG"; }
	if($country_code == "856") { return "LA"; }
	if($country_code == "371") { return "LV"; }
	if($country_code == "961") { return "LB"; }
	if($country_code == "266") { return "LS"; }
	if($country_code == "231") { return "LR"; }
	if($country_code == "218") { return "LY"; }
	if($country_code == "423") { return "LI"; }
	if($country_code == "370") { return "LT"; }
	if($country_code == "352") { return "LU"; }
	if($country_code == "853") { return "MO"; }
	if($country_code == "389") { return "MK"; }
	if($country_code == "261") { return "MG"; }
	if($country_code == "265") { return "MW"; }
	if($country_code == "60") { return "MY"; }
	if($country_code == "960") { return "MV"; }
	if($country_code == "223") { return "ML"; }
	if($country_code == "356") { return "MT"; }
	if($country_code == "692") { return "MH"; }
	if($country_code == "596") { return "MQ"; }
	if($country_code == "222") { return "MR"; }
	if($country_code == "230") { return "MU"; }
	if($country_code == "262") { return "YT"; }
	if($country_code == "52") { return "MX"; }
	if($country_code == "691") { return "FM"; }
	if($country_code == "1808") { return "MD"; }
	if($country_code == "377") { return "MC"; }
	if($country_code == "976") { return "MN"; }
	if($country_code == "1664") { return "MS"; }
	if($country_code == "212") { return "MA"; }
	if($country_code == "258") { return "MZ"; }
	if($country_code == "95") { return "MM"; }
	if($country_code == "264") { return "NA"; }
	if($country_code == "674") { return "NR"; }
	if($country_code == "977") { return "NP"; }
	if($country_code == "31") { return "NL"; }
	if($country_code == "599") { return "AN"; }
	if($country_code == "687") { return "NC"; }
	if($country_code == "64") { return "NZ"; }
	if($country_code == "505") { return "NI"; }
	if($country_code == "227") { return "NE"; }
	if($country_code == "234") { return "NG"; }
	if($country_code == "683") { return "NU"; }
	if($country_code == "672") { return "NF"; }
	if($country_code == "1670") { return "MP"; }
	if($country_code == "47") { return "NO"; }
	if($country_code == "968") { return "OM"; }
	if($country_code == "92") { return "PK"; }
	if($country_code == "680") { return "PW"; }
	if($country_code == "970") { return "PA"; }
	if($country_code == "675") { return "PG"; }
	if($country_code == "595") { return "PY"; }
	if($country_code == "51") { return "PE"; }
	if($country_code == "63") { return "PH"; }
	if($country_code == "n/a") { return "PN"; }
	if($country_code == "48") { return "PL"; }
	if($country_code == "351") { return "PT"; }
	if($country_code == "1") { return "PR"; }
	if($country_code == "974") { return "QA"; }
	if($country_code == "974") { return "RE"; }
	if($country_code == "40") { return "RO"; }
	if($country_code == "7") { return "RU"; }
	if($country_code == "250") { return "RW"; }
	if($country_code == "1869") { return "KN"; }
	if($country_code == "1758") { return "LC"; }
	if($country_code == "1758") { return "VC"; }
	if($country_code == "685") { return "WS"; }
	if($country_code == "378") { return "SM"; }
	if($country_code == "239") { return "ST"; }
	if($country_code == "966") { return "SA"; }
	if($country_code == "221") { return "SN"; }
	if($country_code == "248") { return "SC"; }
	if($country_code == "232") { return "SL"; }
	if($country_code == "65") { return "SG"; }
	if($country_code == "421") { return "SK"; }
	if($country_code == "386") { return "SI"; }
	if($country_code == "677") { return "SB"; }
	if($country_code == "252") { return "SO"; }
	if($country_code == "27") { return "ZA"; }
	if($country_code == "n/a") { return "GS"; }
	if($country_code == "34") { return "ES"; }
	if($country_code == "94") { return "LK"; }
	if($country_code == "n/a") { return "SH"; }
	if($country_code == "n/a") { return "PM"; }
	if($country_code == "249") { return "SD"; }
	if($country_code == "597") { return "SR"; }
	if($country_code == "n/a") { return "SJ"; }
	if($country_code == "268") { return "SZ"; }
	if($country_code == "46") { return "SE"; }
	if($country_code == "41") { return "CH"; }
	if($country_code == "963") { return "SY"; }
	if($country_code == "886") { return "TW"; }
	if($country_code == "992") { return "TJ"; }
	if($country_code == "255") { return "TZ"; }
	if($country_code == "66") { return "TH"; }
	if($country_code == "228") { return "TG"; }
	if($country_code == "690") { return "TK"; }
	if($country_code == "690") { return "TO"; }
	if($country_code == "1868") { return "TT"; }
	if($country_code == "216") { return "TN"; }
	if($country_code == "90") { return "TR"; }
	if($country_code == "993") { return "TM"; }
	if($country_code == "1649") { return "TC"; }
	if($country_code == "688") { return "TV"; }
	if($country_code == "256") { return "UG"; }
	if($country_code == "380") { return "UA"; }
	if($country_code == "971") { return "AE"; }
	if($country_code == "44") { return "GB"; }
	if($country_code == "1") { return "US"; }
	if($country_code == "1340") { return "UM"; }
	if($country_code == "598") { return "UY"; }
	if($country_code == "998") { return "UZ"; }
	if($country_code == "678") { return "VU"; }
	if($country_code == "3") { return "VA"; }
	if($country_code == "58") { return "VE"; }
	if($country_code == "84") { return "VN"; }
	if($country_code == "1340") { return "VG"; }
	if($country_code == "1284") { return "VI"; }
	if($country_code == "681") { return "WF"; }
	if($country_code == "n/a") { return "EH"; }
	if($country_code == "260") { return "YE"; }
	if($country_code == "n/a") { return "ZR"; }
	if($country_code == "260") { return "ZM"; }
	if($country_code == "263") { return "ZW"; }
	
	return "country code does not exist";
}


function test($name,$variable,$return) {
	//echo "test(): " . $returnz;
	
	if((is_array($variable)) ||	(is_object($variable))) {
		if($return != 1) {
			echo "<pre>$name: "; print_r($variable); echo "</pre><br>\n";
		} else {
			//echo "XXXXXXXXXXXXXXXXXX";
			return "<pre>$name: "; print_r($variable); echo "</pre>" . str_repeat("-", 150) . "<br>\n";
		}
	} else {
		if($return != 1) {
			echo "<pre>$name: $variable</pre><br>\n";
		} else {
			//echo "XXXXXXXXXXXXXXXXXX";
			return "<pre>$name: $variable</pre>" . str_repeat("-", 150) . "<br>\n";
		}
	}
}


function notify_business($status) {
	global $gateway;
	global $template;
	
	$tmp_transaction_session = $_SESSION['template']['company']['simple_name'] . "_transaction_session";
  $tmp_transaction_status = $_SESSION['template']['company']['simple_name'] . "_transaction_status";
 	
 	$$tmp_transaction_session = urlencode($gateway['session_id']);
  $$tmp_transaction_status = urlencode($status);
  	
	$response = kurl($gateway['response_url'],$tmp_transaction_session . "=" . $$tmp_transaction_session . "&" . $tmp_transaction_status . "=" . $$tmp_transaction_status);
	return $response;
}



function kurl($kurl_url, $kurl_parameters, $kurl_post) {
	
	logger3("kurl(): kurl_url",$kurl_url);
	logger3("kurl(): kurl_parameters",$kurl_parameters);
	
	##REPLACE whitespace with %20, cURL doesn't like whitespace
	$kurl_url = str_replace ( ' ', '%20', $kurl_url);
	logger3("kurl(): kurl_url",$kurl_url);		
			
	global $master_config_type;
	//make domain in lower case
	$url_parts = parse_url ($kurl_url);        
	$url_parts['host'] = strtolower($url_parts['host']);        
	$kurl_url = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
	//logger3("kurl(): kurl_url",$kurl_url);
	//end
	//echo $kurl_url;
	//$kurl_parameters = urldecode($kurl_parameters);

	# prepare
	$ch = curl_init();

	#set headers:
	curl_setopt($ch, CURLOPT_HEADER, 0);

	#set number of parameters // 
	if($kurl_post) {
		//multi-part mime encoded
		curl_setopt($ch, CURLOPT_POST, 1);
	} else {
		// url-encoded
		curl_setopt($ch, CURLOPT_POST, 0);
	}
	
	# set url:
	curl_setopt($ch, CURLOPT_URL,$kurl_url . "?" . $kurl_parameters);
	
	#set parameter values:
	curl_setopt($ch, CURLOPT_POSTFIELDS,0);
	
	
	curl_setopt($ch, CURLOPT_FAILONERROR, 1);

	//curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
    
    //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    //curl_setopt($geocurl, CURLOPT_RETURNTRANSFER, 1);
		
	# dunno what this does:
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  //The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
	curl_setopt($ch, CURLOPT_TIMEOUT, 0); //The maximum number of seconds to allow cURL functions to execute.
	
	
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST , false); // allows curl to connect to non-valid hosts are something.
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // allows curl to connect to self-signed cerificates.
	
	# execute
	#test("ch",$ch);
	$response = curl_exec($ch);  
	
	if(!$response) {
		$response = curl_error($ch);
	}	
	# close session:
	curl_close($ch);

	# return
	return $response;
}


function kurl_check($kurl_url) {

	# prepare
	$ch = curl_init();

	#set headers:
	curl_setopt($ch, CURLOPT_HEADER, 0);

	#set number of parameters
	curl_setopt($ch, CURLOPT_POST, 1);
	
	# dunno what this does:
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
	curl_setopt($ch, CURLOPT_FAILONERROR, 1);
	
	curl_setopt($ch, CURLOPT_URL,$kurl_url);
	
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // allows curl to connect to self-signed cerificates.
		
	# execute
	#test("ch",$ch);
	$response = curl_exec($ch);
		
	# close session:
  curl_close($ch);

	# return
	return $response;
}

function get_city_from_google_avs($known_street,$known_postalcode,$known_country) {
	
	//$known_street = "2840 S COLLEGE RD";
	//$known_postalcode = "28412";
	//$known_country = "USA";
	
	
	$kurl_url = "http://maps.googleapis.com/maps/api/geocode/json";
	
	
	$kurl_parameters .= NULL;
	$kurl_parameters .= "address=" . str_replace(" ","+",$known_street) . "+" . str_replace(" ","+",$known_postalcode) . "+" . str_replace(" ","+",$known_country);
	//$kurl_parameters .= "address=2840+S+COLLEGE+RD+28412+USA";
	$kurl_parameters .= "&sensor=false";
	
	
	//test("kurl",$kurl_url . "?" . $kurl_parameters);
	//test("kurl_url",);
	
	$json_response = kurl($kurl_url, $kurl_parameters,1);
	
	$json_decoded = json_decode($json_response);
	
	//test("json_decoded",$json_decoded);
	
	
	//test("json_decoded->results[0]->3->[long_name]",$json_decoded->results->0->3->long_name);
	
	// returns city
	return $json_decoded->results[0]->address_components[3]->long_name;	
}

function geobytes_parser($html) {

	$parser = array();
	
	# country code
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls12\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	//test("country code",$tmp_parser[0]);
	echo $parser[country_code] = $tmp_parser[0];
	
	#country name
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls13\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[country_name] = $tmp_parser[0];
	
	#region / state
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls15\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[state_name] = $tmp_parser[0];
	
	#city
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls17\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[city_name] = $tmp_parser[0];


	#Latitude
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls10\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[latitude] = $tmp_parser[0];

	#Longitude
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls19\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[longitude] = $tmp_parser[0];
	
	#currency
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls1\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[currency] = $tmp_parser[0];	
	
	#currency_name
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls1\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[currency_name] = $tmp_parser[0];	
	
	#currency_code
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[currency_code] = $tmp_parser[0];	

	#timezone
	$tmp_parser = array();
	$tmp_parser = explode("<input name=\"ro-no_bots_pls9\" value=\"",$html);
	$tmp_parser = explode("\" size=\"",$tmp_parser[1]);
	#test("country code",$tmp_parser[0]);
	$parser[timezone] = $tmp_parser[0];	
	
	#test("parser",$parser);
	
	return $parser;
	
}

require_once("/$master_config_root_path/shared/MML2/vendor/autoload.php");
use GeoIp2\Database\Reader;

function MML2($ip){    
    global $master_config_root_path;   
    $tmp = null;         
    $reader = new Reader("/$master_config_root_path/shared/MML2/maxmind-db/GeoLite2-City.mmdb");  
    try{
        $record = $reader->city($ip);
        //test('city', $record);
        $tmp = array();
        $tmp['known'] = 'true';
        $tmp['locationcode'] = '';
        $tmp['fips104'] = $record->country->isoCode;
        $tmp['iso2'] = $record->country->isoCode;
        $tmp['iso3'] = geo_data($tmp['iso2'], 'iso2','iso3');
        $tmp['ison'] = '';
        $tmp['internet'] = $record->country->isoCode;
        $tmp['countryid'] = '';
        $tmp['country'] = $record->country->name;
        if(empty($tmp['country'])) {
            $tmp['country'] = geo_data($tmp['iso2'], 'iso2','name');
        }
        $tmp['regionid'] = '';
        $tmp['region'] = '';
        $tmp['regioncode'] = '';
        $tmp['adm1code'] = '';
        $tmp['cityid'] = '';
        $tmp['city'] = $record->city->name;
        $tmp['zip_code'] = $record->postal->code;
        $tmp['latitude'] = $record->location->latitude;
        $tmp['longitude'] = $record->location->longitude;
        $tmp['timezone'] = get_timezone_offset($tmp['latitude'], $tmp['longitude'], $tmp['iso2']);
        $tmp['certainty'] = '';
        $tmp['ip'] = $record->traits->ipAddress;
        $tmp['ip_from'] = '';
        $tmp['ip_to'] = '';

        if(empty($tmp['iso3'])) $tmp['known'] = 'false';

        //$record = $reader->country($ip);
        //test('country', $record);
    }catch(Exception $ex){}
    return $tmp;
}

function get_timezone_offset($cur_lat, $cur_long, $country_code = ''){
    $timezone_id = get_nearest_timezone($cur_lat, $cur_long, $country_code) ;
    $timezone = new DateTimeZone($timezone_id);
    $timezone_offset = new DateTime('now', $timezone);
    return $timezone_offset->format('P');
}

function get_nearest_timezone($cur_lat, $cur_long, $country_code = '') {
    $timezone_ids = ($country_code) ? DateTimeZone::listIdentifiers(DateTimeZone::PER_COUNTRY, $country_code)
                                    : DateTimeZone::listIdentifiers();

    if($timezone_ids && is_array($timezone_ids) && isset($timezone_ids[0])) {

        $time_zone = '';
        $tz_distance = 0;

        //only one identifier?
        if (count($timezone_ids) == 1) {
            $time_zone = $timezone_ids[0];
        } else {

            foreach($timezone_ids as $timezone_id) {
                $timezone = new DateTimeZone($timezone_id);
                $location = $timezone->getLocation();
                $tz_lat   = $location['latitude'];
                $tz_long  = $location['longitude'];

                $theta    = $cur_long - $tz_long;
                $distance = (sin(deg2rad($cur_lat)) * sin(deg2rad($tz_lat))) 
                + (cos(deg2rad($cur_lat)) * cos(deg2rad($tz_lat)) * cos(deg2rad($theta)));
                $distance = acos($distance);
                $distance = abs(rad2deg($distance));
                // echo '<br />'.$timezone_id.' '.$distance; 

                if (!$time_zone || $tz_distance > $distance) {
                    $time_zone   = $timezone_id;
                    $tz_distance = $distance;
                } 

            }
        }
        return  $time_zone;
    }
    return 'none?';
}


function geobytes($ip) {
	//test("ip",$ip);
	
	//logger("+++++++++++++++++++function: geobytes: ip: " . $ip);
	
	logger3("start: geobytes()",$X);
	//test("0. ip",$ip);
	//test("0. ip",$ip);
	
	### CONFIRM VALID IP:
	if(validate_public_ip($ip) == FALSE) {
		return FALSE;
	} 
	
	
	
	
	
	
	
	
	
	
	
	if( 
	(!$ip) ||
	($ip == "127.0.0.1") || 
	(strstr("localhost",$ip)) 
	) {
		//$ip = trim(postDATA("http://what-is-my-ip.net/?text",NULL));// kurl("what-is-my-ip.net","?text",NULL);
		//test("ip",$ip);
		//$ip = "67.29.138.1";
		$ip = "129.78.32.24"; ///AUS
	}
	
	//test("1. ip",$ip);
	//test("ip",$ip);
	
	$geobytes_method = "local";  // curl or local
	logger3("geobytes_method",$geobytes_method);	

        //return MML2 if found
        if(!stristr($master_config_type,"DEVELOPMENT")) $ip2location = MML2($ip);
        
        //test("MML2",$ip2location);
        if(
        ($ip2location) &&
        ($ip2location['known'] != "false")
        ) {
            return $ip2location;
        }
        
        /*
        //return ip2location if there is a macth in ip2location table
        $ip2location = ip2location($ip);
        test("ip2location",$ip2location);
        //exit;
        if(
        ($ip2location) &&
        ($ip2location['known'] != "false")
        ) {
            return $ip2location;
	}
	*/

	$metaTags = NULL;
	$metaTags = array();
	
	### REMOTE CURL
	if($geobytes_method == "curl") {
		$tmp_lookup = "http://www.geobytes.com/IpLocator.htm?GetLocation&pt_email=shea@worldwiderelations.com&pt_password=p455w0rd&template=php3.txt&IpAddress=" . $ip;	
		logger3("tmp_lookup",$tmp_lookup);
		
		
		$metaTags = get_meta_tags($tmp_lookup);
		logger3("metaTags",$metaTags);
	
	## LOCAL
	} else {
		list($o1,$o2,$o3,$o4) = explode(".",$ip);
		$ip = $o1.'.'.$o2.'.'.$o3;
		//test("subnetaddress", $ip);

		$query = "SELECT
			c.Code as locationcode,
			co.FIPS104 as fips104,
			co.ISO2 as iso2,
			co.ISO3 as iso3,
			co.ISON as ison,
			co.Internet as internet,
			co.CountryId as countryid,
			co.Country as country,
			c.RegionID as regionid,
			r.Region as region,
			r.Code as regioncode,
			r.ADM1Code as adm1code,
			c.CityId as cityid,
			c.City as city,
			c.Latitude as latitude,
			c.Longitude as longitude,
			c.TimeZone as timezone,
			s.Certainty as certainty 
			FROM Cities AS c 
			JOIN Subnets AS s on c.cityid=s.cityid 
			JOIN Regions AS r on c.regionid=r.regionid 
			JOIN Countries AS co on c.countryid=co.countryid 
			where s.subnetaddress='$ip'";

		$geo_object = readTHECASHIER($query, "geobytes");
		$metaTags = object2array($geo_object);
		
		//test("metaTags",$metaTags);

		logger3("before shift:metaTags",$metaTags);
		logger3("before shift:empty(metaTags)",empty($metaTags));

		if(empty($metaTags))
			array_unshift_assoc($metaTags, "known", "false");
		else			
			array_unshift_assoc($metaTags, "known", "true");

		logger3("after shift:metaTags",$metaTags);
		logger3("after shift:empty(metaTags)",empty($metaTags));
	}
	
	
	
	$metaTags['ip'] = $ip;
	
	//test("metaTags",$metaTags);
	//exit;
	return $metaTags;

	/*
	
	RETURNS:
	
	[known] => true
	[locationcode] => AUNSSYDN
	[fips104] => AS
	[iso2] => AU
	[iso3] => AUS
	[ison] => 36
	[internet] => AU
	[countryid] => 14
	[country] => Australia
	[regionid] => 4
	[region] => New South Wales
	[regioncode] => NS
	[adm1code] => AS02
	[cityid] => 1311
	[city] => Sydney
	[latitude] => -33.8830
	[longitude] => 151.2170
	[timezone] => +10:00
	[certainty] => 83 
	
	*/

}

function ip2location($ipaddress=null) {
	$tmp = array();        
        
	$number_to_lookup = ip2locationCONVERTER($ipaddress);
	//test("number_to_lookup",$number_to_lookup);
	
	$tmp_db = "ip2location";
	$tmp_sql = "SELECT * FROM ip2location WHERE 
				ip_from <= '".$number_to_lookup."'
				AND ip_to >= '".$number_to_lookup."';";
        
	//test("tmp_sql",$tmp_sql);
	
	$location_details = readTHECASHIER($tmp_sql,$tmp_db);
	//test("location_details",$location_details);
	
	if(empty($location_details)){
	    $location_details = false; //geobytes($ipaddress);
	} else{
	    $location_details = object2array($location_details);
	    $tmp['known'] = 'true';
	    $tmp['locationcode'] = '';
	    $tmp['fips104'] = $location_details['country_code'];
	    $tmp['iso2'] = $location_details['country_code'];
	    $tmp['iso3'] = geo_data($tmp['iso2'], 'iso2','iso3');
	    $tmp['ison'] = '';
	    $tmp['internet'] = $location_details['country_code'];
	    $tmp['countryid'] = '';
	    
	    if(!empty($location_details['country_name'])) {
	    	$tmp['country'] = $location_details['country_name'];
	    } else {
	    	$tmp['country'] = geo_data($tmp['iso2'], 'iso2','name');
	    }
	    $tmp['regionid'] = '';
	    $tmp['region'] = $location_details['region_name'];
	    $tmp['regioncode'] = '';
	    $tmp['adm1code'] = '';
	    $tmp['cityid'] = '';
	    $tmp['city'] = $location_details['city_name'];
	    $tmp['zip_code'] = $location_details['zip_code'];
	    $tmp['latitude'] = $location_details['latitude'];
	    $tmp['longitude'] = $location_details['longitude'];
	    $tmp['timezone'] = $location_details['time_zone'];
	    $tmp['certainty'] = '';
	    $tmp['ip'] = $ipaddress;
	    $tmp['ip_from'] = $location_details['ip_from'];
	    $tmp['ip_to'] = $location_details['ip_to'];
	    
	    if(empty($tmp['iso3'])) $tmp['known'] = 'false';
	
	    $location_details = $tmp;
	}
                
	return $location_details;	
}

function display_location_1($ip) {

	global $session;
	global $http;
	
	if(!$session[display_location_1]) {
	
		#lookup and set info
		$tmp_lookup = "http://www.geobytes.com/IpLocator.htm?GetLocation&pt_email=shea@worldwiderelations.com&pt_password=p455w0rd&template=php3.txt&IpAddress=" . $ip;
		
		
		$session[display_location_1] = get_meta_tags($tmp_lookup);
		#test("session",$session[display_location_1]);
		
		$session[display_location_1]['iso2'] = strtolower($session[display_location_1]['iso2']);
		
		#set mins offset
		$tmp_timezone = explode(":",$session[display_location_1][timezone]);
		$tmp_timezone_hour = $tmp_timezone[0] * 60;
		
		if($tmp_timezone_hour > 0) {
			$session[display_location_1][timezone_mins] = $tmp_timezone_hour + $tmp_timezone[1];
		} else {
			$session[display_location_1][timezone_mins] = $tmp_timezone_hour - $tmp_timezone[1];
		}
		
	
		#test("session",$session[display_location_1][timezone_mins]);
		#test("tags",$tags);
		#test("ip",$ip);
		#test("remote",$REMOTE_ADDR);
	
	}
	
	#test("session",$session[display_location_1]);
	#test("session",$session[display_location_1][timezone_mins]);
	/*
	return "<img src='" . image("local","opera_house_icon_11_v2a.png") . "' border=0>&nbsp;" . $session[display_location_1][city] . "&nbsp;<span id='timecontainer1'></span>
<script type=\"text/javascript\">
	new showLocalTime(\"timecontainer1\", \"server-php\", {$session[display_location_1][timezone_mins]}, \"short\")
</script>";
	*/
	
}







function display_location_2($ip) {

	global $session;
	global $http;
	
	if(!$session['display_location_2']) {
	
		#test("ip",$ip);
	
		#lookup and set info
		$tmp_lookup = "http://www.geobytes.com/IpLocator.htm?GetLocation&pt_email=shea@worldwiderelations.com&pt_password=p455w0rd&template=php3.txt&IpAddress=" . $ip;
		
		
		$session['display_location_2'] = get_meta_tags($tmp_lookup);
		#test("session",$session['display_location_2']);
		$session['display_location_2']['iso2'] = strtolower($session['display_location_2']['iso2']);
		#test("session",$session['display_location_2']['iso2']);
		
		
		#set mins offset
		$tmp_timezone = explode(":",$session['display_location_2']['timezone']);
		$tmp_timezone_hour = $tmp_timezone[0] * 60;
		
		if($tmp_timezone_hour > 0) {
			$session['display_location_2']['timezone_mins'] = $tmp_timezone_hour + $tmp_timezone[1];
		} else {
			$session['display_location_2']['timezone_mins'] = $tmp_timezone_hour - $tmp_timezone[1];
		}
		
		
	}
	
	return "<span id=\"timecontainer2\"></span>
<script type=\"text/javascript\">
	new showLocalTime(\"timecontainer2\", \"server-php\", {$session['display_location_2'][timezone_mins]}, \"short\")
</script>&nbsp;" . $session['display_location_2']['city'] . "&nbsp;<img src='" . image("local","flag_icons/" . $session['display_location_2']['iso2'] . ".png") . "' border='0'>";
}




function authorization_number($memberid) {
	
	if($memberid > 0) {
		//test("authorization_number function memberid",$memberid);
		$results = NULL;
		$results = array();
		$results = object2array(readTHECASHIER("SELECT * FROM phone_numbers WHERE 
		memberid = '" . $memberid . "' AND 
		memberid != '0' AND 
		memberid != '' AND 
		description = 'Authorization' AND 
		(status = 'Active' OR status = 'skip')
		;"));
		$results['authorization_number'] = $results['phone_number'] = $results['number']; //fix
		$results['country_calling_code'] = str_replace("+","",$results['calling_code']);
		$results['formatted_number'] = $results['calling_code'] . "/" . $results['number'];
		$results['clean_number'] = $results['calling_code'] . $results['number'];
		$results['voiceprintid'] = getTHECASHIER("SELECT voiceprintid FROM voiceprints WHERE 
		memberid = '" . $memberid . "' AND
		memberid != '' AND
		memberid != '' 
		AND description = 'Registration'
		;");
		
		return $results;
	}
}


function get_authorization_number($memberid) {
	
	return authorization_number($memberid);
	
}


function check_authorization_number($calling_code,$number) {
	$results = NULL;
	$results = array();
	$tmp_sql = "SELECT * FROM phone_numbers WHERE calling_code = '" . $calling_code . "' AND number = '" . $number . "' AND status = 'Active';";
	$results = object2array(readTHECASHIER($tmp_sql));
	return $results;
}


function clean_authorization_number($authorization_number) {


	if(!stristr($authorization_number,"@")) {
		# trim string
		$tmp_authorization_number = trim($authorization_number);
		# set pattern to only digits
		$tmp_pattern = "/[^0-9]*/";
 		# replace all non-digits with null
 		$tmp_authorization_number = preg_replace($tmp_pattern,null,$tmp_authorization_number);
 		# trim string again (probably unecessary)
 		$tmp_authorization_number = trim($tmp_authorization_number);
 		# count the string and subtract 1 for substr() function to work
 		$tmp_count = strlen($tmp_authorization_number) - 1;
 		# set an array
 		$tmp_authorization_array = array();
 		# break the string into an array
 		$tmp_authorization_array = str_split($tmp_authorization_number);
 		# if first digit in the string is "0", strip it and set final authorization number
 		if($tmp_authorization_array[0] == "0") {
 			return substr($tmp_authorization_number,-$tmp_count);
 		# if first digit is not zero, then set final authoriation value
 		} else {
 			return $tmp_authorization_number;
 		}
		# if there is nothing to clean up, then set session var to null.
	} else {
  		return null;
	}
}



function biometric_registration($memberid,$UUID,$description) {
	global $master_config_ibmsiv_host;
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "YES";
	if($logging) logf("/tmp/biometric_registration_function.txt","
	
	### Fucntion biometric_registration() ########################################################
	
	
	
	");
	if($logging) logf("/tmp/biometric_registration_function.txt","memberid: " . $memberid);
	if($logging) logf("/tmp/biometric_registration_function.txt","UUID: " . $UUID);
	if($logging) logf("/tmp/biometric_registration_function.txt","description: " . $description);
	
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	

	
	### PREPAIRE DATABASE / GET VOICEPRINTID:
	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`description`,
		`created`,
		`updated`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $voicefileid . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "')";
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logf("/tmp/biometric_registration_function.txt","tmp_query: " . $tmp_query);
	if($logging) logf("/tmp/biometric_registration_function.txt","voiceprintid: " . $voiceprintid);
	


	### UPDATE VOICEFILES WITH MEMBERID:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "UPDATE voicefiles SET memberid = '" . $memberid . "' WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '20' AND (description = 'Registration' OR description = 'PayMe') AND created LIKE '" . $tmp_date . "%'";
	$update_results = updateTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration_function.txt","update_results = : " . $update_results);
	
	

	### GET THE VOICEFILEIDS:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT voicefileid FROM voicefiles WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '20' AND (description = 'Registration' OR description = 'PayMe') AND created LIKE '" . $tmp_date . "%'";
	$voicefileids = arrayTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration_function.txt","voicefileids[0]: " . $voicefileids[0]);
	if($logging) logf("/tmp/biometric_registration_function.txt","voicefileids[1]: " . $voicefileids[1]);
	
	
	### GET THE FILENAMES:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT filename FROM voicefiles WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '20' AND (description = 'Registration' OR description = 'PayMe') AND created LIKE '" . $tmp_date . "%'";
	$filenames = arrayTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration_function.txt","filenames[0]: " . $filenames[0]);
	if($logging) logf("/tmp/biometric_registration_function.txt","filenames[1]: " . $filenames[1]);
	
	
	### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	if(!$filenames[2]) { # there should always be only two
		$filenames[1] = $filenames[0]; # sets the 2nd as the first
		$filenames[2] = $filenames[0]; # sets the 3rd as the first
		$filenames[3] = $filenames[0]; # sets the 3rd as the first
		
		if($logging) logf("/tmp/biometric_registration_function.txt","voicefileids[2]: " . $voicefileids[2]);
		if($logging) logf("/tmp/biometric_registration_function.txt","filenames[2]: " . $filenames[2]);
	}
	
	
	if($logging) logf("/tmp/biometric_registration_function.txt","
	
	
	#################### FILENAMES: $filenames
	
	
	");
	
	//test("filenames",$filenames);
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	logf("/tmp/biometric_registration_function.txt","
	
	############################################################
	### START: WHILE()
	############################################################
	
	");
	$send_results = NULL;
	$attempt = 1;
	
	while((!$send_results) && ($attempt < 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/biometric_registration_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/biometric_registration_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}

	logf("/tmp/biometric_registration_function.txt","
	
	############################################################
	### END: WHILE()
	### send_results: $send_results
	############################################################
	
	");
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		while(($enrollment_status[0] != "accepted") && ($attempt < 5)) {
		
			$post_fields = "input-wave-uri=/root/audio/incoming_voice_authorizations/" . $filenames[$vf] . ".al";
			if($logging) logf("/tmp/biometric_registration_function.txt","post url: " . $post_url . $post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/biometric_registration_function.txt","send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/biometric_registration_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				$final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				$final_voicefiles[$vf][filename] = $filenames[$vf];
				if($logging) logf("/tmp/biometric_registration_function.txt","final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				if($logging) logf("/tmp/biometric_registration_function.txt","final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logf("/tmp/biometric_registration_function.txt","enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$vf++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## all good... finish it up:
		} else {
		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logf("/tmp/biometric_registration_function.txt","post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt < 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/biometric_registration_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/biometric_registration_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				# count number of voicefiles used in enrollment
				$number_of_voicefiles = count($final_voicefiles);
			
				# create the voicefileid value
				$i = 0;
				while($final_voicefiles[$i]) {
					if($final_voicefiles[$i+1]) {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i][voicefileid] . ",";
					} else {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i][voicefileid];
					}
					$i++;
				}
			
			
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logf("/tmp/biometric_registration_function.txt","tmp_query: " . $tmp_query);
				if($logging) logf("/tmp/biometric_registration_function.txt","voiceprintids: " . $voiceprintid);
				return $voiceprintid;
			}
		}
	}
}



function biometric_registration_generic($memberid,$UUID,$description) {

	### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "on";
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","
	
	### Function biometric_registration_generic() ########################################################
	
	
	
	");
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","memberid: " . $memberid);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","UUID: " . $UUID);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","description: " . $description);
		
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	

	
	### PREPAIRE DATABASE / GET VOICEPRINTID:
	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`description`,
		`created`,
		`updated`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $voicefileid . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "')";
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","tmp_query: " . $tmp_query);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voiceprintid: " . $voiceprintid);
	


	### UPDATE VOICEFILES WITH MEMBERID:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "UPDATE voicefiles SET memberid = '" . $memberid . "' WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '20' AND description = '" . $description . "' AND created LIKE '" . $tmp_date . "%'";
	$update_results = updateTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","update_results = : " . $update_results);
	
	

	### GET THE VOICEFILEIDS:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT voicefileid FROM voicefiles WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '20' AND description = '" . $description . "' AND created LIKE '" . $tmp_date . "%'";
	$voicefileids = arrayTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[0]: " . $voicefileids[0]);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[1]: " . $voicefileids[1]);
	
	
	### GET THE FILENAMES:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT filename FROM voicefiles WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '20' AND description = '" . $description . "' AND created LIKE '" . $tmp_date . "%'";
	$filenames = arrayTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[0]: " . $filenames[0]);
	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[1]: " . $filenames[1]);
	
	
	### PREPARE *THIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	if(!$voicefileids[2]) { # there should always be only two
		$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
		$filenames[2] = $filenames[0]; # sets the first as the third, also\
		
		if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
		if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
		
		
	}
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt < 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/biometric_registration_generic_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/biometric_registration_generic_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		while(($enrollment_status[0] != "accepted") && ($attempt < 5)) {
		
			$final_audio_filename = $filenames[$vf];
			
			
			// $possible_audio_ext = substr($filenames[$vf], -3);
			// if(stristr($possible_audio_ext,".al")) $final_audio_filename = substr($filenames[$vf], 0, -3);
			// if(stristr($possible_audio_ext,".au")) $final_audio_filename = substr($filenames[$vf], 0, -3);
			// if(stristr($possible_audio_ext,".ul")) $final_audio_filename = substr($filenames[$vf], 0, -3);
			
			$possible_audio_ext = substr($filenames[$vf], -4);
			if(stristr($possible_audio_ext,".wav")) {
				$final_audio_filename = substr($filenames[$vf], 0, -4);				
				//if($logging) logf("/tmp/biometric_registration_generic_function.txt","000. final_audio_filenameurl: " . $final_audio_filename);
				$post_fields = "input-wave-uri=/root/audio/incoming_voice_authorizations/" . $final_audio_filename . ".au";
				
			} else {
				$post_fields = "input-wave-uri=/root/audio/incoming_voice_authorizations/" . $final_audio_filename . ".al";
			}
			
			
			
			if($logging) logf("/tmp/biometric_registration_generic_function.txt","post url: " . $post_url . $post_fields);
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/biometric_registration_generic_function.txt","send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				$final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				$final_voicefiles[$vf][filename] = $filenames[$vf];
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$vf++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## all good... finish it up:
		} else {
		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logf("/tmp/biometric_registration_generic_function.txt","post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt < 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/biometric_registration_generic_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				
			
				# count number of voicefiles used in enrollment
				$number_of_voicefiles = count($final_voicefiles);
			
				# create the voicefileid value
				$i = 0;
				while($final_voicefiles[$i]) {
					if($final_voicefiles[$i+1]) {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
					} else {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
					}
					$i++;
				}
			
			
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","tmp_query: " . $tmp_query);
				if($logging) logf("/tmp/biometric_registration_generic_function.txt","voiceprintids: " . $voiceprintid);
				return $voiceprintid;
			}
		}
	}
}





function convert_audio_to_alaw($audio_filename,$path_to_audio="/uploads/") {


	### LOGGING:
	$logging = "on";
	if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","
	
	### Function: convert_audio_to_alaw() ########################################################
	
	
	
	");
	
	
	if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","audio_filename: ". $audio_filename);
	if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","path_to_audio: ". $path_to_audio);
	
	
	
	//$path_to_audio = "./";
	$exploded_filename = explode(".", $audio_filename);
	if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","exploded_filename: ". $exploded_filename);
	
	
	### .MP3 -> .WAV
	if(strtoupper($exploded_filename[1]) == "MP3") {
	
		///cleanup filename:
		//$exploded_filename[0] = str_ireplace(" ", "", $exploded_filename[0]);
		
	
		// STEP 1: convert mp3 to wav
		//test("STEP 1","lame --decode ". $path_to_audio . $audio_filename ." ". $path_to_audio . $exploded_filename[0] .".wav");
		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","lame --decode ". $path_to_audio . $audio_filename ." ". $path_to_audio . $exploded_filename[0] .".wav");
		$lame_results = exec("lame --decode ". $path_to_audio . $audio_filename ." ". $path_to_audio . $exploded_filename[0] .".wav");
		//test("lame_results",$lame_results);

		// STEP 2: convert wav to .al
		//test("STEP 2","sox ". $path_to_audio . $exploded_filename[0] .".wav -r 8000 -c 1 -1 -e a-law ". $path_to_audio . $exploded_filename[0] .".al");
		
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		//$sox_results = exec("sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		$sox_results = exec("sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		// STEP 3: delete the huge wav file:
		//test("STEP 3",$path_to_audio . $exploded_filename[0] .".wav");
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","UNLINK: ". $path_to_audio . $exploded_filename[0] .".wav");
		
		//unlink($path_to_audio . $exploded_filename[0] .".wav");
		//test("sox_results",$sox_results);
		
		// STEP 3:  downsample and boost volume of original wave:
		//$sox_results_boosted_volume = exec("sox -v 10 ". $path_to_audio . $exploded_filename[0] .".wav ". $path_to_audio . $exploded_filename[0] .".wav");
		
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","RETURN: " . $exploded_filename[0] .".al");
		//return $exploded_filename[0] .".al";

		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","RETURN: " . $exploded_filename[0] .".au");
		return $exploded_filename[0] .".au";
		
	}
	
	
	else 
	
	if(
	(strtoupper($exploded_filename[1]) == "AL") ||
	(strtoupper($exploded_filename[1]) == "UL") ||
	(strtoupper($exploded_filename[1]) == "WAV")
	) {
		
		//test("sox","sox ". $path_to_audio . $audio_filename ." -r 8000 -c 1 -1 -e a-law ". $path_to_audio . $exploded_filename[0] .".al");
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		//$sox_results = exec("sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		$sox_results = exec("sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		
		// STEP 3:  downsample and boost volume of original wave:
		//$sox_results_boosted_volume = exec("sox -B ". $path_to_audio . $exploded_filename[0] .".wav -B ". $path_to_audio . $exploded_filename[0] .".wav");

		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","REURN: " . $exploded_filename[0] .".al");
		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","REURN: " . $exploded_filename[0] .".au");
		//return $exploded_filename[0] .".al";
		return $exploded_filename[0] .".au";
	}
	
	else {
		
		$sox_results = exec("sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","REURN: " . $exploded_filename[0] .".au");
		return $exploded_filename[0] .".au";
		
		
	}
	
	
	return FALSE;
	
}

function convert_biometricid_to_voiceprintid($unknown_biometric_id_string) {
	
	
	if(strlen($unknown_biometric_id_string) == 32) {
		
		$tmp_sql = "SELECT voiceprintid FROM voiceprints WHERE CUSTOMER_BIOMETRIC_ID =  '". $unknown_biometric_id_string ."';";
		logger3("convert_biometricid_to_voiceprintid() tmp_sql",$tmp_sql);
		
		$voiceprintid = getTHECASHIER($tmp_sql);
		
		
	} else {
		
		$voiceprintid = $unknown_biometric_id_string;
	}
	
	logger3("convert_biometricid_to_voiceprintid() voiceprintid",$voiceprintid);
	return $voiceprintid;
}


function convert_audio_to_ulaw($audio_filename,$path_to_audio="/uploads/") {


	### LOGGING:
	$logging = "on";
	if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","
	
	### Function: convert_audio_to_ulaw() ########################################################
	
	
	
	");
	
	
	if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","audio_filename: ". $audio_filename);
	if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","path_to_audio: ". $path_to_audio);
	
	
	
	//$path_to_audio = "./";
	$exploded_filename = explode(".", $audio_filename);
	if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","exploded_filename: ". $exploded_filename);
	
	
	### .MP3 -> .WAV
	if(strtoupper($exploded_filename[1]) == "MP3") {
	
		///cleanup filename:
		//$exploded_filename[0] = str_ireplace(" ", "", $exploded_filename[0]);
		
	
		// STEP 1: convert mp3 to wav
		//test("STEP 1","lame --decode ". $path_to_audio . $audio_filename ." ". $path_to_audio . $exploded_filename[0] .".wav");
		if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","lame --decode ". $path_to_audio . $audio_filename ." ". $path_to_audio . $exploded_filename[0] .".wav");
		$lame_results = exec("lame --decode ". $path_to_audio . $audio_filename ." ". $path_to_audio . $exploded_filename[0] .".wav");
		//test("lame_results",$lame_results);

		// STEP 2: convert wav to .al
		//test("STEP 2","sox ". $path_to_audio . $exploded_filename[0] .".wav -r 8000 -c 1 -1 -e a-law ". $path_to_audio . $exploded_filename[0] .".al");
		
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding u-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		//$sox_results = exec("sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		$sox_results = exec("sox ". $path_to_audio . $exploded_filename[0] .".wav --encoding u-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		// STEP 3: delete the huge wav file:
		//test("STEP 3",$path_to_audio . $exploded_filename[0] .".wav");
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","UNLINK: ". $path_to_audio . $exploded_filename[0] .".wav");
		
		//unlink($path_to_audio . $exploded_filename[0] .".wav");
		//test("sox_results",$sox_results);
		
		// STEP 3:  downsample and boost volume of original wave:
		//$sox_results_boosted_volume = exec("sox -v 10 ". $path_to_audio . $exploded_filename[0] .".wav ". $path_to_audio . $exploded_filename[0] .".wav");
		
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","RETURN: " . $exploded_filename[0] .".al");
		//return $exploded_filename[0] .".al";

		if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","RETURN: " . $exploded_filename[0] .".au");
		return $exploded_filename[0] .".au";
		
	}
	
	
	else 
	
	if(
	(strtoupper($exploded_filename[1]) == "AL") ||
	(strtoupper($exploded_filename[1]) == "UL") ||
	(strtoupper($exploded_filename[1]) == "WAV")
	) {
		
		//test("sox","sox ". $path_to_audio . $audio_filename ." -r 8000 -c 1 -1 -e a-law ". $path_to_audio . $exploded_filename[0] .".al");
		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","sox ". $path_to_audio . $audio_filename ." --encoding u-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		//$sox_results = exec("sox ". $path_to_audio . $audio_filename ." --encoding a-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".al");
		
		$sox_results = exec("sox ". $path_to_audio . $audio_filename ." --encoding u-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		
		
		// STEP 3:  downsample and boost volume of original wave:
		//$sox_results_boosted_volume = exec("sox -B ". $path_to_audio . $exploded_filename[0] .".wav -B ". $path_to_audio . $exploded_filename[0] .".wav");

		//if($logging) logf("/tmp/function_convert_audio_to_alaw.txt","REURN: " . $exploded_filename[0] .".al");
		if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","REURN: " . $exploded_filename[0] .".au");
		//return $exploded_filename[0] .".al";
		return $exploded_filename[0] .".au";
	}
	
	else {
		
		$sox_results = exec("sox ". $path_to_audio . $audio_filename ." --encoding u-law -b 8 -1 -c 1 -r 8000 ". $path_to_audio . $exploded_filename[0] .".au");
		if($logging) logf("/tmp/function_convert_audio_to_ulaw.txt","REURN: " . $exploded_filename[0] .".au");
		return $exploded_filename[0] .".au";
		
		
	}
	
	
	return FALSE;
	
}








function add_vocamatch_audio($audio_filename,$ip,$telephone_number) {


	$logging = "on";
	if($logging) logf("/tmp/function_add_vocamatch_audio.txt","audio_filename: ". $audio_filename);
	if($logging) logf("/tmp/function_add_vocamatch_audio.txt","ip: ". $ip);
	if($logging) logf("/tmp/function_add_vocamatch_audio.txt","telephone_number: ". $telephone_number);

	if($logging) logger3("audio_filename",$audio_filename);
	if($logging) logger3("ip",$ip);
	if($logging) logger3("telephone_number",$telephone_number);

	
	//$converted_filename = convert_audio_to_alaw($audio_filename,$path_to_audio="./link_blacklist_uploads/");
	
	//if($logging) logf("/tmp/function_add_vocamatch_audio.txt","converted_filename: ". $converted_filename);
	
	//$tmp_sql = "INSERT into vocamatch_audio
	$vocamatch_audio_id = "";
	$audio_filename = $audio_filename;
	$ip = $ip;
	$telephone_number = $telephone_number;
	$voiceprintid = "";
	$datetime = datetime();
	
	$tmp_query = "INSERT into vocamatch_audio (
		`vocamatch_audio_id`,
		`audio_filename`,
		`ip`,
		`telephone_number`,
		`voiceprintid`,
		`datetime`
	) VALUES (
		'" . $vocamatch_audio_id . "',
		'" . $audio_filename . "',
		'" . $ip . "',
		'" . $telephone_number . "',
		'" . $voiceprintid . "',
		'" . $datetime . "')";
	$vocamatch_audio_id = insertTHECASHIER($tmp_query);
	if($logging) logf("/tmp/function_add_vocamatch_audio.txt","tmp_query: ". $tmp_query);
	if($logging) logf("/tmp/function_add_vocamatch_audio.txt","vocamatch_audio_id: ". $vocamatch_audio_id);
	
	if($logging) logger3("tmp_query",$tmp_query);
	if($logging) logger3("vocamatch_audio_id",$vocamatch_audio_id);
	
	return $vocamatch_audio_id;
	
}





function biometric_registration_vocamatch_UPLOADED($vocamatch_audio_id,$voice_file_type="BASE") {

### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;
	$vocamatch_path_to_audio = "/mnt/WebServer/blacklist/uploads/";
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "on";
	if($logging) logger3("
	
	### Function biometric_registration_vocamatch() ########################################################
	
	
	
	");
	if($logging) logger3("vocamatch_audio_id: " . $vocamatch_audio_id);	
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	

	
	### PREPAIRE DATABASE / GET VOICEPRINTID (must be incremental fo ALL VOICEPRINTID's):
	$memberid = "";
	$voicefileids = "";
	$vocamatch_audio_id = $vocamatch_audio_id;
	$description = "vocaMATCH";
	
	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`vocamatch_audio_id`,
		`description`,
		`created`,
		`updated`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $voicefileid . "',
		'" . $vocamatch_audio_id . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "')";
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logger3("tmp_query: " . $tmp_query);
	if($logging) logger3("voiceprintid: " . $voiceprintid);
	
	
	### GET THE FILENAMES:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT audio_filename FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "'";
	$vocamatch_audio_filename = getTHECASHIER($tmp_sql);
	if($logging) logger3("tmp_sql: " . $tmp_sql);
	if($logging) logger3("vocamatch_audio_filename " . $vocamatch_audio_filename);

	
	
	### ### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	### if(!$voicefileids[2]) { # there should always be only two
	### 	$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
	### 	$filenames[2] = $filenames[0]; # sets the first as the third, also\
	### 	
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
	### }
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt <= 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logger3("attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logger3("attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		if(stristr($voice_file_type,"BASE")) {
			$number_of_allowed_enrollment_loops = 3;
		} else {
			$number_of_allowed_enrollment_loops = 3;
		}
		while(($enrollment_status[0] != "accepted") && ($attempt <= $number_of_allowed_enrollment_loops)) { /// i.e., no more than 2 loops.
		
			$post_fields = "input-wave-uri=". $vocamatch_path_to_audio . $vocamatch_audio_filename;
			if($logging) logger3("post url: " . $post_url . $post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logger3("send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logger3("attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				$final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				$final_voicefiles[$vf][filename] = $filenames[$vf];
				if($logging) logger3("final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				if($logging) logger3("final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logger3("enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$vf++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## after first attempt, does not maintain sufficient audio data
		} else	if($enrollment_status[0] != "accepted") {
		
			curl_close($send_session);
			if($logging) logger3("FAILED: enrollment_status[0]: " . $enrollment_status[0]);
			return "Insufficient Audio - Please try Again.";
		
		
		## all good... finish it up:
		} else {

		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logger3("post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt < 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logger3("attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logger3("attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				# count number of voicefiles used in enrollment
				$number_of_voicefiles = count($final_voicefiles);
			
				# create the voicefileid value
				$i = 0;
				while($final_voicefiles[$i]) {
					if($final_voicefiles[$i+1]) {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
					} else {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
					}
					$i++;
				}
			
			
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logger3("tmp_query: " . $tmp_query);
				if($update_results) logger3("update_results: " . $update_results);
				
				
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE vocamatch_audio SET voiceprintid = '" . $voiceprintid . "' WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logger3("tmp_query: " . $tmp_query);
				if($update_results) logger3("update_results: " . $update_results);
				
				
				// ### create boosted volume version:
				// $boosted_volume_sox_results = exec("sox -v 2.0 ". $vocamatch_path_to_audio . $vocamatch_audio_filename ." ". $vocamatch_path_to_audio . "boosted_volume_". $vocamatch_audio_filename .");
				
				
				return $voiceprintid;
			}
		}
	}
}



function biometric_registration_vocamatch_RECORDED($vocamatch_audio_id,$voice_file_type="BASE") {

### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;	        
        $vocamatch_path_to_audio = "/mnt/WebServer/blacklist/uploads/";
       
        if(isset($_SESSION['vocamatch_api'])){
            $vocamatch_path_to_audio = "/mnt/WebServer/authorizations/audio/";            
        }
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "on";
	$tmp_new_session = "
	
	### Function biometric_registration_vocamatch() ########################################################
	
	
	";
	if($logging) logger3($tmp_new_session,$x);
	

    if($logging) logger3("vocamatch_path_to_audio: " . $vocamatch_path_to_audio);
	if($logging) logger3("vocamatch_audio_id: " . $vocamatch_audio_id);	
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
		        
	
	### PREPAIRE DATABASE / GET VOICEPRINTID (must be incremental fo ALL VOICEPRINTID's):
	$memberid = "";
	$voicefileids = "";
	$vocamatch_audio_id = $vocamatch_audio_id;
	$description = "vocaMATCH";
	
	

    logger3("000 _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
    
	if(isset($_SESSION['voice_authorization_api'])) {                                    
	    if(is_array($_SESSION['voice_authorization_api'])){
                $vocamatch_path_to_audio = "/mnt/WebServer/www/audio_recorder/recordings/";
                ### REGISTRATION
                if(
                (stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Enrollment")) ||
                (stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Passphrase Enrollment"))
                ) {
                    //$_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] = hash_me();

                    $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] = $_SESSION['session']['biometric_registration_session']['email_verification_hash'];
                    $description = "Registration";

                }

                ### LOGIN
                else if(
                (stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Verification")) ||
                (stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Passphrase Verification"))
                ) {
                    $description = "Login";                
                }

                ### UPDATE
                else if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Password Update")) {
                    $description = "UpdatePassword";                
                }

                ### RESET
                else if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Password Reset")) {
                    $description = "PasswordReset";                
                }
            }
	}
	
	
	logger3("000 description",$description); 

	$biometric_status = "";

	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`vocamatch_audio_id`,
        `BUSINESS_PERMANENT_UUID`,
        `CUSTOMER_BIOMETRIC_ID`,
		`description`,
		`created`,
		`updated`,
        `biometric_status`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $voicefileid . "',
		'" . $vocamatch_audio_id . "',
		
		'" . $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'] . "',
		'" . $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] . "',
                
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "',
        '". $biometric_status ."'
       )";
	
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logger3("tmp_query",$tmp_query);
	if($logging) logger3("voiceprintid",$voiceprintid);
	
	
	### GET THE FILENAMES:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT audio_filename FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "'";
	$vocamatch_audio_filename = getTHECASHIER($tmp_sql);
	if($logging) logger3("tmp_sql",$tmp_sql);
	if($logging) logger3("vocamatch_audio_filename",$vocamatch_audio_filename);
	
	if(stristr(".wav",$vocamatch_audio_filename)) {
		$vocamatch_audio_filename = substr($vocamatch_audio_filename, 0, -4);
		$vocamatch_audio_filename = $vocamatch_audio_filename . ".au";
	}

	### ### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	### if(!$voicefileids[2]) { # there should always be only two
	### 	$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
	### 	$filenames[2] = $filenames[0]; # sets the first as the third, also\
	### 	
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
	### }
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt <= 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logger3("1. attempt #",$attempt);
		if($logging) logger3("1. send_results",$send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logger3("2. attempt #",$attempt);
			if($logging) logger3("2. send_results (error)",$send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		if(stristr($voice_file_type,"BASE")) {
			$number_of_allowed_enrollment_loops = 3;
		} else {
			$number_of_allowed_enrollment_loops = 3;
		}
		
		while(($enrollment_status[0] != "accepted") && ($attempt <= $number_of_allowed_enrollment_loops)) { /// allow for 2 loops
		
			
		
			$post_fields = "input-wave-uri=". $vocamatch_path_to_audio . $vocamatch_audio_filename;
			if($logging) logger3("post_url",$post_url);
			if($logging) logger3("post_fields",$post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logger3("3. attempt #",$attempt);
			if($logging) logger3("3. send_results",$send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logger3("4. attempt #",$attempt);
				if($logging) logger3("4. send_results (error)",$send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				$final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				$final_voicefiles[$vf][filename] = $filenames[$vf];
				if($logging) logger3("final_voicefiles[$vf][voicefileid]",$final_voicefiles[$vf]['voicefileid']);
				if($logging) logger3("final_voicefiles[$vf][filename]",$final_voicefiles[$vf]['filename']);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logger3("enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$vf++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## after first attempt, does not maintain sufficient audio data
		} else	if($enrollment_status[0] != "accepted") {
			curl_close($send_session);
			if($logging) logger3("FAILED: enrollment_status[0]",$enrollment_status[0]);
			return "Insufficient Audio";
		
		
		## all good... finish it up:
		} else {

		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logger3("post url",$post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt <= 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logger3("attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logger3("attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				# count number of voicefiles used in enrollment
				$number_of_voicefiles = count($final_voicefiles);
			
				# create the voicefileid value
				$i = 0;
				while($final_voicefiles[$i]) {
					if($final_voicefiles[$i+1]) {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
					} else {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
					}
					$i++;
				}
			
			
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logger3("tmp_query",$tmp_query);
				if($update_results) logger3("update_results",$update_results);
				
				
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE vocamatch_audio SET voiceprintid = '" . $voiceprintid . "' WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logger3("tmp_query",$tmp_query);
				if($update_results) logger3("update_results",$update_results);
				
				
				return $voiceprintid;
			}
		}
	}
}


function generate_voiceprint($path_to_audio,$audio_filename,$voice_file_type="Login") {

	logger3("
	########################################################
	### generate_voiceprint();
	########################################################
	
	");
	
	logger3("generate_voiceprint(): path_to_audio",$path_to_audio);
	logger3("generate_voiceprint(): audio_filename",$audio_filename);
	logger3("generate_voiceprint(): voice_file_type",$voice_file_type);
	

	global $master_config_ibmsiv_host;
	logger3("generate_voiceprint(): master_config_ibmsiv_host",$master_config_ibmsiv_host);
		        
    if(empty($path_to_audio)) $path_to_audio = "/mnt/WebServer/blacklist/uploads/";
	logger3("generate_voiceprint(): path_to_audio",$path_to_audio);
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");	
	logger3("generate_voiceprint(): timestamp",$timestamp);
	
	### PREPAIRE DATABASE / GET VOICEPRINTID (must be incremental fo ALL VOICEPRINTID's):
	$memberid = "";
	$voicefileids = "";
	//$vocamatch_audio_id = $vocamatch_audio_id;
	$description = $voice_file_type;
	
	

	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`vocamatch_audio_id`,
        `BUSINESS_PERMANENT_UUID`,
        `CUSTOMER_BIOMETRIC_ID`,
		`description`,
		`created`,
		`updated`,
                `biometric_status`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $voicefileid . "',
		'" . $vocamatch_audio_id . "',
        '" . $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'] . "',
        '" . $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "',
        'REJECTED'
       )";
	logger3("generate_voiceprint(): tmp_query",$tmp_query);
	
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	logger3("generate_voiceprint(): voiceprintid",$voiceprintid);
	
	### GET THE FILENAMES:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	logger3("generate_voiceprint(): tmp_date",$tmp_date);
	
	
	//$tmp_sql = "SELECT audio_filename FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "'";
	//$vocamatch_audio_filename = getTHECASHIER($tmp_sql);
	//if($logging) logger3("tmp_sql: " . $tmp_sql);
	//if($logging) logger3("vocamatch_audio_filename " . $vocamatch_audio_filename);


	### ### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	### if(!$voicefileids[2]) { # there should always be only two
	### 	$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
	### 	$filenames[2] = $filenames[0]; # sets the first as the third, also\
	### 	
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
	### }
	
	
	### get the voicefile id:
	
	
	$tmp_query = "SELECT * FROM voicefiles WHERE filename = '". $audio_filename ."';";
	logger3("generate_voiceprint(): tmp_voicefile_details_query",$tmp_query);
	
	$tmp_voicefile_details =  readTHECASHIER($tmp_query);
	logger3("generate_voiceprint(): tmp_voicefile_details_query",$tmp_query);
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = "";
	$attempt = 1;
	while((!$send_results) && ($attempt <= 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logger3("attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logger3("attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = "";
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = "";
		$send_results = "";
		$enrollment_status = "";
		$enrollment_status = array();
		$final_voicefiles = "";
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		$number_of_allowed_enrollment_loops = 3;
		
		
		while(
		(!stristr($enrollment_status[0],"accepted")) && 
		($attempt <= $number_of_allowed_enrollment_loops)
		) { /// allow for 2 loops
		
		
		
		
			$tmp_audio_filename = explode(".",$audio_filename);
		
			
			
			
			logger3("generate_voiceprint(): tmp_audio_filename[1]",$tmp_audio_filename[1]);
			if(empty($tmp_audio_filename[1])) {
				$audio_filename = $audio_filename . ".wav";
			}

			logger3("generate_voiceprint(): path_to_audio",$path_to_audio);
			logger3("generate_voiceprint(): audio_filename",$audio_filename);
			$post_fields = "input-wave-uri=". $path_to_audio . "/". $audio_filename;
			logger3("generate_voiceprint(): post_fields",$post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			logger3("generate_voiceprint(): send_results",$send_results);
			
			if(!$send_results) {
				
				$send_results = curl_error($send_session);
				logger3("generate_voiceprint(): attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = "";
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				$final_voicefiles[$vf]['voicefileid'] = $voicefileids[$vf];
				logger3("generate_voiceprint(): final_voicefiles[$vf][voicefileid]",$final_voicefiles[$vf]['voicefileid']);
				
				$final_voicefiles[$vf]['filename'] = $filenames[$vf];
				logger3("generate_voiceprint(): final_voicefiles[$vf][filename]",$final_voicefiles[$vf]['filename']);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				logger3("generate_voiceprint(): enrollment_status[0]",$enrollment_status[0]);
				
				## UPDATE voicefile:
				$vf++;
				logger3("generate_voiceprint(): vf",$vf);
			}
		
			# update attempt:
			$attempt++;
			logger3("generate_voiceprint(): 1_attempt",$attempt);
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## after first attempt, does not maintain sufficient audio data
		} else	if($enrollment_status[0] != "accepted") {
			curl_close($send_session);
			logger3("FAILED: enrollment_status[0]",$enrollment_status[0]);
			return "Insufficient Audio";
		
		
		## all good... finish it up:
		} else {

		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			logger3("generate_voiceprint(): post url",$post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt <= 2)) {
				
				$send_results = curl_exec($send_session);
				logger3("generate_voiceprint(): attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					logger3("generate_voiceprint(): attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = "";
				}
				$attempt++;
				
				logger3("generate_voiceprint(): 2_attempt",$attempt);
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				# count number of voicefiles used in enrollment
				$number_of_voicefiles = count($final_voicefiles);
				logger3("generate_voiceprint(): number_of_voicefiles",$number_of_voicefiles);
			
				# create the voicefileid value
				$i = 0;
				
				while($final_voicefiles[$i]) {
					
					logger3("generate_voiceprint(): final_voicefiles[$i+1]",$final_voicefiles[$i+1]);
					
					if($final_voicefiles[$i+1]) {
						//$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
						$enrollment_voicefileids = $enrollment_voicefileids . $tmp_voicefile_details->voicefileid . ",";
						
					} else {
						//$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
						$enrollment_voicefileids = $enrollment_voicefileids . $tmp_voicefile_details->voicefileid;
					}
					
					logger3("generate_voiceprint(): enrollment_voicefileids",$enrollment_voicefileids);
					
					logger3("generate_voiceprint(): 1_i",$i);
					$i++;
					logger3("generate_voiceprint(): 2_i",$i);
				
				}
			
			
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE voiceprints SET 
								voicefileids = '" . $enrollment_voicefileids . "' WHERE 
								voiceprintid LIKE '" . $voiceprintid . "';
								";
				logger3("generate_voiceprint(): tmp_query",$tmp_query);
				$update_results = updateTHECASHIER($tmp_query);
				logger3("generate_voiceprint(): update_results",$update_results);
				
				
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE vocamatch_audio SET 
								voiceprintid = '" . $voiceprintid . "' WHERE 
								vocamatch_audio_id = '" . $vocamatch_audio_id . "';
								";
				logger3("generate_voiceprint(): tmp_query",$tmp_query);
				$update_results = updateTHECASHIER($tmp_query);
				logger3("generate_voiceprint(): update_results",$update_results);
				
				logger3("generate_voiceprint(): RETURN voiceprintid",$voiceprintid);
				
				return $voiceprintid;
			}
		}
	}
}


function vocaPASS_biometric_registration_combination($voicefileids_array) {

### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;	        
    //$vocamatch_path_to_audio = "/mnt/WebServer/blacklist/uploads/";
       
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "on";
	$log_this = "
	
	### Function biometric_registration_combination() ########################################################
	
	
	
	";
	if($logging) logf("/tmp/funtion_biometric_registration_combination.txt",$log_this);
	if($logging) logger3("START NEW SESSION:",$log_this);
	
	if($logging) logger3("biometric_registration_combination() 1. voicefileids_array",$voicefileids_array);
	
	
    //if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","voicefileids_array: " . print_r($voicefileids_array));
    if($logging) logger3("biometric_registration_combination() voicefileids_array",$voicefileids_array);
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	$insert_voicefileids = "";
	foreach($voicefileids_array as $key => $voicefileid) {
		
		$insert_voicefileids .= $voicefileid;
		
		$insert_voicefileids .= ",";
	}
		        
	if($logging) logger3("biometric_registration_combination() insert_voicefileids",$insert_voicefileids);
	
	
	### PREPAIRE DATABASE / GET VOICEPRINTID (must be incremental fo ALL VOICEPRINTID's):
	$memberid = "";
	$voicefileids = "";
	//$vocamatch_audio_id = $vocamatch_audio_id;
	$description = "vocaONE";



	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`vocamatch_audio_id`,
        `BUSINESS_PERMANENT_UUID`,
        `CUSTOMER_BIOMETRIC_ID`,
		`description`,
		`created`,
		`updated`,
        `biometric_status`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $insert_voicefileids . "',
		'" . $vocamatch_audio_id . "',
        '" . $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'] . "',
        '" . $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "',
        'REJECTED'
       )";
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
	if($logging) logger3("biometric_registration_combination() tmp_query",$tmp_query);
	
	if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","voiceprintid: " . $voiceprintid);
	if($logging) logger3("biometric_registration_combination() voiceprintid",$voiceprintid);
	
	
	### GET THE FILENAMES:
	$i = 0;
	if($logging) logger3("biometric_registration_combination() 2. voicefileids_array",$voicefileids_array);
	foreach($voicefileids_array as $key => $voicefileid) {
		$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month

		### option 1A
		$tmp_sql = "SELECT * FROM voicefiles WHERE voicefileid = '" . $voicefileid . "';";		
		$tmp_sql_results = readTHECASHIER($tmp_sql);
		
		if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_sql: " . $tmp_sql);
		if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","vocamatch_audio_filename[$i] " . $vocamatch_audio_filename[$i]);
		
		if($logging) logger3("biometric_registration_combination() tmp_sql",$tmp_sql);
		if($logging) logger3("biometric_registration_combination() tmp_sql_results",$tmp_sql_results);
		
		
		if(!empty($tmp_sql_results->voicefileid)) {
			### option 1B
			$vocamatch_audio_filename[$i] = $tmp_sql_results->path_to_file . $tmp_sql_results->filename;
			if($logging) logger3("biometric_registration_combination() vocamatch_audio_filename[$i]",$vocamatch_audio_filename[$i]);
			
		} else {
			### option 2
			$tmp_sql = "SELECT audio_filename FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $voicefileid . "'";		
			$vocamatch_audio_filename[$i] = getTHECASHIER($tmp_sql);
			if($logging) logger3("biometric_registration_combination() tmp_sql",$tmp_sql);
			if($logging) logger3("biometric_registration_combination() vocamatch_audio_filename",$vocamatch_audio_filename);
			
		}
	
		$i++;
	
	}

	### ### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	### if(!$voicefileids[2]) { # there should always be only two
	### 	$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
	### 	$filenames[2] = $filenames[0]; # sets the first as the third, also\
	### 	
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
	### }
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt <= 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		$number_of_allowed_enrollment_loops = 10;
		# if(stristr($voice_file_type,"BASE")) {
		# 	$number_of_allowed_enrollment_loops = 3;
		# } else {
		# 	$number_of_allowed_enrollment_loops = 3;
		# }
		
		
		$i = 0;
		while(
		(
		(!empty($vocamatch_audio_filename[$i]))
		) &&
		($attempt <= $number_of_allowed_enrollment_loops)
		) {
		
			$post_fields = "input-wave-uri=". $vocamatch_path_to_audio . $vocamatch_audio_filename[$i];
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","post url: " . $post_url . $post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				// $final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				// $final_voicefiles[$vf][filename] = $filenames[$vf];
				// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$i++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## after first attempt, does not maintain sufficient audio data
		} else	if($enrollment_status[0] != "accepted") {
			curl_close($send_session);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","FAILED: enrollment_status[0]: " . $enrollment_status[0]);
			return "Insufficient Audio";
		
		
		## all good... finish it up:
		} else {

		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt <= 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				/// # count number of voicefiles used in enrollment
				/// $number_of_voicefiles = count($final_voicefiles);
				/// 
				/// # create the voicefileid value
				/// $i = 0;
				/// while($final_voicefiles[$i]) {
				/// 	if($final_voicefiles[$i+1]) {
				/// 		$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
				/// 	} else {
				/// 		$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
				/// 	}
				/// 	$i++;
				/// }
				/// 
				/// 
				/// ### UPDATE VOICEPRINT DATABASE ENTRY:
				/// $tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				/// updateTHECASHIER($tmp_query);
				/// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				/// if($update_results) logf("/tmp/funtion_biometric_registration_combination.txt","update_results: " . $update_results);
				
				### UPDATE voiceprints
				$tmp_query = "UPDATE voiceprints SET biometric_status = 'Approved' WHERE voiceprintid = '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				if($update_results) logf("/tmp/funtion_biometric_registration_combination.txt","update_results: " . $update_results);
				

				### UPDATE VOICEPRINT DATABASE ENTRY:
				/// $tmp_query = "UPDATE vocamatch_audio SET voiceprintid = '" . $voiceprintid . "' WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "';";
				/// updateTHECASHIER($tmp_query);
				/// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				/// if($update_results) logf("/tmp/funtion_biometric_registration_combination.txt","update_results: " . $update_results);
				
				return $voiceprintid;
			}
		}
	}
}



function biometric_registration_combination($voicefileids_array) {

### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;	        
    //$vocamatch_path_to_audio = "/mnt/WebServer/blacklist/uploads/";
       
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "on";
	$log_this = "
	
	### Function biometric_registration_combination() ########################################################
	
	
	
	";
	if($logging) logf("/tmp/funtion_biometric_registration_combination.txt",$log_this);
	if($logging) logger3("START NEW SESSION:",$log_this);
	
	if($logging) logger3("biometric_registration_combination() 1. voicefileids_array",$voicefileids_array);
	
	
    if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","voicefileids_array: " . print_r($voicefileids_array));
    if($logging) logger3("biometric_registration_combination() voicefileids_array",$voicefileids_array);
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	$insert_voicefileids = "";
	foreach($voicefileids_array as $key => $voicefileid) {
		
		$insert_voicefileids .= $voicefileid;
		
		$insert_voicefileids .= ",";
	}
		        
	if($logging) logger3("biometric_registration_combination() insert_voicefileids",$insert_voicefileids);
	
	
	### PREPAIRE DATABASE / GET VOICEPRINTID (must be incremental fo ALL VOICEPRINTID's):
	$memberid = "";
	$voicefileids = "";
	//$vocamatch_audio_id = $vocamatch_audio_id;
	$description = "vocaONE";



	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`vocamatch_audio_id`,
        `BUSINESS_PERMANENT_UUID`,
        `CUSTOMER_BIOMETRIC_ID`,
		`description`,
		`created`,
		`updated`,
        `biometric_status`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $insert_voicefileids . "',
		'" . $vocamatch_audio_id . "',
        '" . $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'] . "',
        '" . $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'] . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "',
        'REJECTED'
       )";
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
	if($logging) logger3("biometric_registration_combination() tmp_query",$tmp_query);
	
	if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","voiceprintid: " . $voiceprintid);
	if($logging) logger3("biometric_registration_combination() voiceprintid",$voiceprintid);
	
	
	### GET THE FILENAMES:
	$i = 0;
	if($logging) logger3("biometric_registration_combination() 2. voicefileids_array",$voicefileids_array);
	foreach($voicefileids_array as $key => $voicefileid) {
		$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month

		### option 1A
		$tmp_sql = "SELECT * FROM voicefiles WHERE voicefileid = '" . $voicefileid . "';";		
		$tmp_sql_results = readTHECASHIER($tmp_sql);
		
		if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_sql: " . $tmp_sql);
		if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","vocamatch_audio_filename[$i] " . $vocamatch_audio_filename[$i]);
		
		if($logging) logger3("biometric_registration_combination() tmp_sql",$tmp_sql);
		if($logging) logger3("biometric_registration_combination() tmp_sql_results",$tmp_sql_results);
		
		
		if(!empty($tmp_sql_results->voicefileid)) {
			### option 1B
			$vocamatch_audio_filename[$i] = $tmp_sql_results->path_to_file . $tmp_sql_results->filename;
			if($logging) logger3("biometric_registration_combination() vocamatch_audio_filename[$i]",$vocamatch_audio_filename[$i]);
			
		} else {
			### option 2
			$tmp_sql = "SELECT audio_filename FROM vocamatch_audio WHERE vocamatch_audio_id = '" . $voicefileid . "'";		
			$vocamatch_audio_filename[$i] = getTHECASHIER($tmp_sql);
			if($logging) logger3("biometric_registration_combination() tmp_sql",$tmp_sql);
			if($logging) logger3("biometric_registration_combination() vocamatch_audio_filename",$vocamatch_audio_filename);
			
		}
	
		$i++;
	
	}

	### ### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	### if(!$voicefileids[2]) { # there should always be only two
	### 	$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
	### 	$filenames[2] = $filenames[0]; # sets the first as the third, also\
	### 	
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
	### }
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt <= 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		$number_of_allowed_enrollment_loops = 2;
		# if(stristr($voice_file_type,"BASE")) {
		# 	$number_of_allowed_enrollment_loops = 3;
		# } else {
		# 	$number_of_allowed_enrollment_loops = 3;
		# }
		
		
		$i = 0;
		while(
		(
		(!empty($vocamatch_audio_filename[$i])) ||
		($enrollment_status[0] != "accepted")
		) &&
		($attempt <= $number_of_allowed_enrollment_loops)
		) {
		
			$post_fields = "input-wave-uri=". $vocamatch_path_to_audio . $vocamatch_audio_filename[$i];
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","post url: " . $post_url . $post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				// $final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				// $final_voicefiles[$vf][filename] = $filenames[$vf];
				// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$i++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## after first attempt, does not maintain sufficient audio data
		} else	if($enrollment_status[0] != "accepted") {
			curl_close($send_session);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","FAILED: enrollment_status[0]: " . $enrollment_status[0]);
			return "Insufficient Audio";
		
		
		## all good... finish it up:
		} else {

		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt <= 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				/// # count number of voicefiles used in enrollment
				/// $number_of_voicefiles = count($final_voicefiles);
				/// 
				/// # create the voicefileid value
				/// $i = 0;
				/// while($final_voicefiles[$i]) {
				/// 	if($final_voicefiles[$i+1]) {
				/// 		$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
				/// 	} else {
				/// 		$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
				/// 	}
				/// 	$i++;
				/// }
				/// 
				/// 
				/// ### UPDATE VOICEPRINT DATABASE ENTRY:
				/// $tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				/// updateTHECASHIER($tmp_query);
				/// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				/// if($update_results) logf("/tmp/funtion_biometric_registration_combination.txt","update_results: " . $update_results);
				
				### UPDATE voiceprints
				$tmp_query = "UPDATE voiceprints SET biometric_status = 'Approved' WHERE voiceprintid = '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				if($update_results) logf("/tmp/funtion_biometric_registration_combination.txt","update_results: " . $update_results);
				

				### UPDATE VOICEPRINT DATABASE ENTRY:
				/// $tmp_query = "UPDATE vocamatch_audio SET voiceprintid = '" . $voiceprintid . "' WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "';";
				/// updateTHECASHIER($tmp_query);
				/// if($logging) logf("/tmp/funtion_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				/// if($update_results) logf("/tmp/funtion_biometric_registration_combination.txt","update_results: " . $update_results);
				
				return $voiceprintid;
			}
		}
	}
}







function biometric_vocamatch($base_vocamatch_audio_id,$comparison_vocamatch_audio_id,$siv_tolerance="") {

	global $master_config_ibmsiv_host;
	global $master_config_testing_biometric_matching;
        $path_to_vocamatch_audio_files = "/mnt/WebServer/blacklist/uploads/";
        
        ### LOGIN
        if(isset($_SESSION['vocamatch_api'])){
            $path_to_vocamatch_audio_files = "/mnt/WebServer/authorizations/audio/";
        }
        
        if(isset($_SESSION['voice_authorization_api'])){
            if(!empty($_SESSION['voice_authorization_api'])){
                $path_to_vocamatch_audio_files = "/mnt/WebServer/www/audio_recorder/recordings/";
            }            
        }        
        
	if(empty($siv_tolerance)) {
		$tolerance = "0.6000"; // .5 == tight; .3 == moderate; .1 == lose
	} else {
		$tolerance = $siv_tolerance;
	}
	
	
	
	/// GET BASE VOCAMATCH DETAILS
	$tmp_sql = "SELECT * FROM vocamatch_audio WHERE vocamatch_audio_id = '". $base_vocamatch_audio_id ."';";
	logger3("tmp_sql",$tmp_sql);
	$base_audio_details = readTHECASHIER($tmp_sql);
	logger3("base_audio_details->audio_filename",$base_audio_details->audio_filename);
	logger3("base_audio_details->voiceprintid",$base_audio_details->voiceprintid);
	
	
	/// GET COMPARISON VOCAMATCH DETAILS
	$tmp_sql = "SELECT * FROM vocamatch_audio WHERE vocamatch_audio_id = '". $comparison_vocamatch_audio_id ."';";
	logger3("tmp_sql",$tmp_sql);
	$comparison_audio_details = readTHECASHIER($tmp_sql);
	logger3("comparison_audio_details->audio_filename",$comparison_audio_details->audio_filename);
	logger3("comparison_audio_details->voiceprintid",$comparison_audio_details->voiceprintid);
	
	
	
	# set url:
	$siv_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/score";
	
	# set parameters:
	$parameters = "voiceprint=" . $base_audio_details->voiceprintid . "&input-wave-uri=" . $path_to_vocamatch_audio_files . $comparison_audio_details->audio_filename;
	
	logger3("SIV URL [". $siv_url . "?" . $parameters . "]");

	# initialize:
	$ch = curl_init();
	logger3("ch: ",$ch);

	#set headers:
	curl_setopt($ch, CURLOPT_HEADER, 0);

	#set number of parameters
	curl_setopt($ch, CURLOPT_POST, 1);

	# dunno what this does:
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	#curl_setopt($ch, CURLOPT_VERBOSE, 1);

	# set path to server
	curl_setopt($ch, CURLOPT_URL,$siv_url);
		
	#set parameter values:
	curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters);

	# execute:
	$send_results = curl_exec($ch);
	logger3("send_results: ",$send_results);
	
	
	# if error, get details:
	if(!$send_results) {
		echo $send_results = curl_error($ch);
		logger3("send_results: ",$send_results);
		curl_close($ch);
		return;
	
	} else {
	
		# close session:
		curl_close($ch);
		
  		$tmp_send_results = explode("name=\"result.score\" expr=\"'",$send_results);
  		$tmp_send_results = explode("'\"/>",$tmp_send_results[1]);
  		logger3("tmp_send_results[0]: ",$tmp_send_results[0]);
  		$biometric_confidence = $tmp_send_results[0];
  	
                if(isset($_SESSION['vocamatch_api'])){
                    return $biometric_confidence;
                }

  		/// DEV
  		if($master_config_testing_biometric_matching) { 
  			logger3("master_config_testing_biometric_matching: ",$master_config_testing_biometric_matching);
  			return "MATCHES";
  			
  		/// LIVE
  		} else { 
  			
  			if($biometric_confidence >= $tolerance) {
  				logger("FINAL RESULT: MATCHES");
                                //BIOMETRIC PASSWORD UPDATE
                                if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Password Update")) {
                                    return "MATCHES";
                                }
                                //BIOMETRIC LOGIN
                                if(isset($_SESSION['voice_authorization_api'])){
                                    if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Verification")) {            
                                        return "MATCHES";
                                    }
                                }
  				return "<nobr><span style='font-size:38px; color:#CC0000;'>Biometrics</span>&nbsp;&nbsp;&nbsp;<span style='font-size:38px; color:#BB0000; font-family:arial-black;'><i>MATCH!</i></span></nobr>";
  			} else {
  				logger("FINAL RESULT: DOES NOT MATCH");
                                //BIOMETRIC PASSWORD UPDATE                                 
                                if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Password Update")) {
                                    $security_level_auto_update = "0.4";
                                    if(isset($_SESSION['authorization_service']['security_level_auto_update']))
                                    {
                                        if(!empty($_SESSION['authorization_service']['security_level_auto_update']))
                                        {
                                            $security_level_auto_update = $_SESSION['authorization_service']['security_level_auto_update'];
                                        }
                                    }
                                    if($biometric_confidence < $security_level_auto_update) return "INVALID";
                                    return "MATCHES";
                                }
                                //BIOMETRIC LOGIN
                                if(isset($_SESSION['voice_authorization_api'])){
                                    if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Verification")) {            
                                        return "DOES NOT MATCH";
                                    }
                                }
                                return "<span style='font-size:24px; color:#666666;'>Biometrics <u>DO <i>NOT</i></u> Match.</span>";
                                
			}	
  		}
  	}
}



function biometric_vocamatch_voiceprintid($base_voiceprintid,$comparison_vocamatch_audio_id,$siv_tolerance="") {

	global $master_config_ibmsiv_host;
	global $master_config_testing_biometric_matching;
        $path_to_vocamatch_audio_files = "/mnt/WebServer/blacklist/uploads/";
        
        ### LOGIN
        if(isset($_SESSION['voice_authorization_api'])){
            if(!empty($_SESSION['voice_authorization_api'])){
                $path_to_vocamatch_audio_files = "/mnt/WebServer/www/audio_recorder/recordings/";
            }            
        }
	if(empty($siv_tolerance)) {
		$tolerance = "0.6000"; // .5 == tight; .3 == moderate; .1 == lose
	} else {
		$tolerance = $siv_tolerance;
	}
				
	
	/// GET COMPARISON VOCAMATCH DETAILS
	$tmp_sql = "SELECT * FROM vocamatch_audio WHERE vocamatch_audio_id = '". $comparison_vocamatch_audio_id ."';";
	logger3("tmp_sql",$tmp_sql);
	$comparison_audio_details = readTHECASHIER($tmp_sql);
	logger3("comparison_audio_details->audio_filename",$comparison_audio_details->audio_filename);
	logger3("comparison_audio_details->voiceprintid",$comparison_audio_details->voiceprintid);
	
	
	
	# set url:
	$siv_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/score";
	
	# set parameters:
	$parameters = "voiceprint=" . $base_voiceprintid . "&input-wave-uri=" . $path_to_vocamatch_audio_files . $comparison_audio_details->audio_filename;
	
	logger3("SIV URL [". $siv_url . "?" . $parameters . "]");

	# initialize:
	$ch = curl_init();
	logger3("ch: ",$ch);

	#set headers:
	curl_setopt($ch, CURLOPT_HEADER, 0);

	#set number of parameters
	curl_setopt($ch, CURLOPT_POST, 1);

	# dunno what this does:
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	#curl_setopt($ch, CURLOPT_VERBOSE, 1);

	# set path to server
	curl_setopt($ch, CURLOPT_URL,$siv_url);
		
	#set parameter values:
	curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters);

	# execute:
	$send_results = curl_exec($ch);
	logger3("send_results: ",$send_results);
	
	
	# if error, get details:
	if(!$send_results) {
		echo $send_results = curl_error($ch);
		logger3("send_results: ",$send_results);
		curl_close($ch);
		return;
	
	} else {
	
		# close session:
		curl_close($ch);
		
  		$tmp_send_results = explode("name=\"result.score\" expr=\"'",$send_results);
  		$tmp_send_results = explode("'\"/>",$tmp_send_results[1]);
  		logger3("tmp_send_results[0]: ",$tmp_send_results[0]);
  		$biometric_confidence = $tmp_send_results[0];
  	
  		/// DEV
  		if($master_config_testing_biometric_matching) { 
  			logger3("master_config_testing_biometric_matching: ",$master_config_testing_biometric_matching);
  			return "MATCHES";
  			
  		/// LIVE
  		} else { 
  			
  			if($biometric_confidence >= $tolerance) {
  				logger("FINAL RESULT: MATCHES");
                                //BIOMETRIC PASSWORD UPDATE
                                if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Password Update")) {
                                    return "MATCHES";
                                }
                                //BIOMETRIC LOGIN
                                if(isset($_SESSION['voice_authorization_api'])){
                                    if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Verification")) {            
                                        return "MATCHES";
                                    }
                                }
  				return "<nobr><span style='font-size:38px; color:#CC0000;'>Biometrics</span>&nbsp;&nbsp;&nbsp;<span style='font-size:38px; color:#BB0000; font-family:arial-black;'><i>MATCH!</i></span></nobr>";
  			} else {
  				logger("FINAL RESULT: DOES NOT MATCH");
                                //BIOMETRIC PASSWORD UPDATE
                                if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Password Update")) {
                                    $security_level_auto_update = "0.4";
                                    if(isset($_SESSION['authorization_service']['security_level_auto_update']))
                                    {
                                        if(!empty($_SESSION['authorization_service']['security_level_auto_update']))
                                        {
                                            $security_level_auto_update = $_SESSION['authorization_service']['security_level_auto_update'];
                                        }
                                    }
                                    if($biometric_confidence < $security_level_auto_update) return "INVALID";
                                    return "MATCHES";
                                }
                                //BIOMETRIC LOGIN
                                if(isset($_SESSION['voice_authorization_api'])){
                                    if(stristr($_SESSION['voice_authorization_api']['authorization_template_details']['template_name'],"Biometric Verification")) {            
                                        return "DOES NOT MATCH";
                                    }
                                }
  				return "<span style='font-size:24px; color:#666666;'>Biometrics <u>DO <i>NOT</i></u> Match.</span>";
			}	
  		}
  	}
}


function vocaPASS_For_Internet_biometric_registration_combination($voicefileids_array) {

	logger3("vocaPASS_For_Internet_biometric_registration_combination(000)",0);
	
	/// api
	$_SESSION['function']['BUSINESS_ACCOUNT_ID'] = $_SESSION['function']['BUSINESS_ACCOUNT_ID'];
	$_SESSION['function']['CUSTOMER_BIOMETRIC_ID'] = $_SESSION['function']['CUSTOMER_BIOMETRIC_ID'];
	


	### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;	        
    //$vocamatch_path_to_audio = "/mnt/WebServer/blacklist/uploads/";
       
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "yes";;
	if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","
	
	### Function vocaPASS_For_Internet_biometric_registration_combination() ########################################################
	
	
	
	");
        //logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","voicefileids_array: " . print_r($voicefileids_array));	
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	$insert_voicefileids = "";
	foreach($voicefileids_array as $key => $voicefileid) {
		
		$insert_voicefileids .= $voicefileid;
		
		$insert_voicefileids .= ",";
	}
		        
	
	### PREPAIRE DATABASE / GET VOICEPRINTID (must be incremental fo ALL VOICEPRINTID's):
	$memberid = "";
	$voicefileids = "";
	//$vocamatch_audio_id = $vocamatch_audio_id;
	$description = "vocaPASS_For_Internet";



	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`vocamatch_audio_id`,
        `BUSINESS_PERMANENT_UUID`,
        `CUSTOMER_BIOMETRIC_ID`,
		`description`,
		`created`,
		`updated`,
        `biometric_status`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $insert_voicefileids . "',
		'" . $vocamatch_audio_id . "',
        '" . $_SESSION['function']['BUSINESS_ACCOUNT_ID'] . "',
        '" . $_SESSION['function']['CUSTOMER_BIOMETRIC_ID'] . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "',
        'REJECTED'
       )";
    logger3("tmp_query",$tmp_query);
       
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	logger3("voiceprintid",$voiceprintid);
	
	
	if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
	
	///logger3("voiceprintid",$voiceprintid);
	
	if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","voiceprintid: " . $voiceprintid);
	
	
	
	
	### GET THE FILENAMES:
	$i = 0;
	foreach($voicefileids_array as $key => $voicefileid) {
		
		//$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
		$tmp_sql = "SELECT * FROM voicefiles WHERE voicefileid = '" . $voicefileid . "';";
		if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","tmp_sql: " . $tmp_sql);
		
		
		$voicefileid_details[$i] = object2array(readTHECASHIER($tmp_sql));
		logger3("voicefileid_details[$i]",$voicefileid_details[$i]);
		
		
		if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","voicefileid_details[$i] " . $voicefileid_details[$i]);
		
		
		
		$i++;
	
	}

	### ### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	### if(!$voicefileids[2]) { # there should always be only two
	### 	$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
	### 	$filenames[2] = $filenames[0]; # sets the first as the third, also\
	### 	
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","voicefileids[2]: " . $voicefileids[2]);
	### 	if($logging) logf("/tmp/biometric_registration_generic_function.txt","filenames[2]: " . $filenames[2]);
	### }
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt <= 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		logger3("send_results",$send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		$number_of_allowed_enrollment_loops = 15; // for vocaPASS_For_Internet
		$full_cycle = count($voicefileids_array) - 1; // to adjust fro array starts with 0
		if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","full_cycle: " . $full_cycle);
		
		logger3("full_cycle",$full_cycle);
		
		# if(stristr($voice_file_type,"BASE")) {
		# 	$number_of_allowed_enrollment_loops = 3;
		# } else {
		# 	$number_of_allowed_enrollment_loops = 3;
		# }
		
		$i = 0;
		while(
		(
		($enrollment_status[0] != "accepted") ||
		($attempt <= $full_cycle)
		)
		&&
		($attempt <= $number_of_allowed_enrollment_loops)
		) {
		
			if($logging) if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","
			
			
			LOOP # " . $i . "
			
			
			
			");
			
			logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","voicefileid_details[$i]['voicefileid']: " . $voicefileid_details[$i]['voicefileid']);
			
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","voicefileid_details[$i]['path_to_file']: " . $voicefileid_details[$i]['path_to_file']);
			
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","voicefileid_details[$i]['filename']: " . $voicefileid_details[$i]['filename']);



			
			$post_fields = "input-wave-uri=". $voicefileid_details[$i]['path_to_file'] . $voicefileid_details[$i]['filename'];
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","post url: " . $post_url . $post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				// $final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				// $final_voicefiles[$vf][filename] = $filenames[$vf];
				// if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				// if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$i++;
			}
		
			# update attempt:
			$attempt++;
			
			/// loop back around if necessary
			if($i > $full_cycle) $i = 0; // reset loop back around
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## after first attempt, does not maintain sufficient audio data
		} else	if($enrollment_status[0] != "accepted") {
			curl_close($send_session);
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","FAILED: enrollment_status[0]: " . $enrollment_status[0]);
			return "Insufficient Audio";
		
		
		## all good... finish it up:
		} else {

		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt <= 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
				
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				/// # count number of voicefiles used in enrollment
				/// $number_of_voicefiles = count($final_voicefiles);
				/// 
				/// # create the voicefileid value
				/// $i = 0;
				/// while($final_voicefiles[$i]) {
				/// 	if($final_voicefiles[$i+1]) {
				/// 		$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
				/// 	} else {
				/// 		$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
				/// 	}
				/// 	$i++;
				/// }
				/// 
				/// 
				/// ### UPDATE VOICEPRINT DATABASE ENTRY:
				/// $tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				/// updateTHECASHIER($tmp_query);
				/// if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				/// if($update_results) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","update_results: " . $update_results);
				
				### UPDATE voiceprints
				$tmp_query = "UPDATE voiceprints SET biometric_status = 'Approved' WHERE voiceprintid = '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				if($update_results) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","update_results: " . $update_results);
				

				### UPDATE VOICEPRINT DATABASE ENTRY:
				/// $tmp_query = "UPDATE vocamatch_audio SET voiceprintid = '" . $voiceprintid . "' WHERE vocamatch_audio_id = '" . $vocamatch_audio_id . "';";
				/// updateTHECASHIER($tmp_query);
				/// if($logging) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","tmp_query: " . $tmp_query);
				/// if($update_results) logf("/tmp/function_vocaPASS_For_Internet_biometric_registration_combination.txt","update_results: " . $update_results);
				
				return $voiceprintid . "||" . $_SESSION['function']['CUSTOMER_BIOMETRIC_ID'];
			}
		}
	}
}



function transaction($transactionid=null) {

	if(
	(empty($transactionid)) ||
	(stristr($transactionid,"LIST"))
	) {
		$tmp_sql = "SELECT transactionid FROM transactions;";
		return arrayTHECASHIER($tmp_sql);
		exit;
	}

	logger3("function transacion(transactionid): ",$transactionid);
	
	$tmp_sql = "SELECT * FROM transactions WHERE hash = '" . $transactionid . "';";
	logger3("transacion(): tmp_sql",$tmp_sql);
	
	$variable = object2array(readTHECASHIER($tmp_sql));
	logger3("transacion(): variable",$variable);
	
	if(empty($variable['transactionid'])) {
		$tmp_sql = "SELECT * FROM transactions WHERE transactionid LIKE '" . $transactionid . "';";
		$variable = object2array(readTHECASHIER($tmp_sql));
	}


	### ADD TRANSLOG
	logger3("variable['translogid']",$variable['translogid']);
	
	if(!empty($variable['translogid'])) {
		$tmp_sql = "SELECT * FROM translog WHERE translogid LIKE '" . $variable['translogid'] . "';";
		logger3("tmp_sql",$tmp_sql);
		$variable['translog'] = object2array(readTHECASHIER($tmp_sql));
		logger3("variable['translog']",$variable['translog']);
	}
	
	### ADD CARD DETAILS:
	if(
	($variable['method'] == "MASTERCARD") ||
	($variable['method'] == "VISA") ||
	($variable['method'] == "AMEX") ||
	($variable['method'] == "DISCOVER") ||
	($variable['method'] == "JBL") ||
	($variable['method'] == "CUP")
	) {
		$exploded_account_details = explode("][",$variable['method_details']);
		$variable['card_details'] = card_details($exploded_account_details[1]);
		
	}
	
	
	
	
	
	return $variable;
}



function biometric_registration_payme($memberid,$UUID,$description) {

### SOME WILL HAVE THREE VOICEFILES.  SOME WILL HAVE TWO.  JUST DEPENDS ON WHEN IT ACTUALLY IS ACCPTED AS A VALID ENROLLMENT.


	global $master_config_ibmsiv_host;
	
	### NOTE: $description options:
		# "Registration" (for multiple identity registartion screening)
		# "Transaction" (for actual transactions)
	
	
	### LOGGING:
	$logging = "on";
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","
	
	### Fucntion biometric_registration() ########################################################
	
	
	
	");
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","memberid: " . $memberid);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","UUID: " . $UUID);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","description: " . $description);
		
	
	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	

	
	### PREPAIRE DATABASE / GET VOICEPRINTID:
	$tmp_query = "INSERT into voiceprints (
		`voiceprintid`,
		`memberid`,
		`voicefileids`,
		`description`,
		`created`,
		`updated`
	) VALUES (
		'" . $voiceprintid . "',
		'" . $memberid . "',
		'" . $voicefileid . "',
		'" . $description . "',
		'" . $timestamp . "',
		'" . $timestamp . "')";
	$voiceprintid = insertTHECASHIER($tmp_query); # gets base print id to send/set in sv reprository
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","tmp_query: " . $tmp_query);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","voiceprintid: " . $voiceprintid);
	


	### UPDATE VOICEFILES WITH MEMBERID:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "UPDATE voicefiles SET memberid = '" . $memberid . "' WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '50' AND description = 'PayMe' AND created LIKE '" . $tmp_date . "%'";
	$update_results = updateTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","update_results = : " . $update_results);
	
	

	### GET THE VOICEFILEIDS:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT voicefileid FROM voicefiles WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '50' AND description = 'PayMe' AND created LIKE '" . $tmp_date . "%'";
	$voicefileids = arrayTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","voicefileids[0]: " . $voicefileids[0]);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","voicefileids[1]: " . $voicefileids[1]);
	
	
	### GET THE FILENAMES:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "SELECT filename FROM voicefiles WHERE filename LIKE '" . $UUID . "%' AND confidence_asr >= '50' AND description = 'PayMe' AND created LIKE '" . $tmp_date . "%'";
	$filenames = arrayTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","filenames[0]: " . $filenames[0]);
	if($logging) logf("/tmp/biometric_registration__payme_function.txt","filenames[1]: " . $filenames[1]);
	
	
	### PREPARE *THIIRD* LOOP JUST IN CASE IBM DOES NOT "ACCEPT" THE FIRST TWO FILES AS BEING SUFFICIENT:
	if(!$voicefileids[2]) { # there should always be only two
		$voicefileids[2] = $voicefileids[0]; # sets the first as the third, also
		$filenames[2] = $filenames[0]; # sets the first as the third, also\
		
		if($logging) logf("/tmp/biometric_registration__payme_function.txt","voicefileids[2]: " . $voicefileids[2]);
		if($logging) logf("/tmp/biometric_registration__payme_function.txt","filenames[2]: " . $filenames[2]);
	}
	
	
	
		
	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	curl_setopt($send_session, CURLOPT_URL, "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession");
	curl_setopt($send_session, CURLOPT_POSTFIELDS,"mode=enroll&voiceprint=" . $voiceprintid);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt < 2)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/biometric_registration__payme_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/biometric_registration__payme_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		curl_close($send_session);
		return FALSE;
		
	
	## all good, keep going:
	} else {
	
		# prep for next curl stage:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		
		$number_of_audio_files = NULL;
		$send_results = NULL;
		$enrollment_status = NULL;
		$enrollment_status = array();
		$final_voicefiles = NULL;
		$final_voicefiles = array();
		
		$vf = 0;
		$attempt = 1;
		while(($enrollment_status[0] != "accepted") && ($attempt < 5)) {
		
			$post_fields = "input-wave-uri=/root/audio/incoming_voice_authorizations/" . $filenames[$vf] . ".al";
			if($logging) logf("/tmp/biometric_registration__payme_function.txt","post url: " . $post_url . $post_fields);
			
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			
			
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/biometric_registration__payme_function.txt","send_results: " . $send_results);
			
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
				
			} else { # success, keep going....
				
				### RECORD WHICH VOICEFILEIDS/FILENAMES ARE BEING USED:
				$final_voicefiles[$vf][voicefileid] = $voicefileids[$vf];
				$final_voicefiles[$vf][filename] = $filenames[$vf];
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","final_voicefiles[$vf][voicefileid]: " . $final_voicefiles[$vf][voicefileid]);
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","final_voicefiles[$vf][filename]: " . $final_voicefiles[$vf][filename]);
				
				
				### GET THE RESULT:
				$enrollment_status = explode("<assign name=\"result.decision\" expr=\"'",$send_results);
				$enrollment_status = explode("'\"/>",$enrollment_status[1]);
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","enrollment_status[0]: " . $enrollment_status[0]);
				
				## UPDATE voicefile:
				$vf++;
			}
		
			# update attempt:
			$attempt++;
		}
		
		
		
		## if there was an error with the enrollment communication:
		if(!$send_results) {
			curl_close($send_session);
			return FALSE;
	
		## all good... finish it up:
		} else {
		
			### prep to close the session:
			$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
			if($logging) logf("/tmp/biometric_registration__payme_function.txt","post url: " . $post_url);

			# execute session:
			$send_results = NULL;
			$attempt = 1;
			while((!$send_results) && ($attempt < 2)) {
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/biometric_registration__payme_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
					$send_results = NULL;
				}
				$attempt++;
			}
	
			## if there was an error with this final communication:
			if(!$send_results) {
				curl_close($send_session);
				return FALSE;
			
			### ALL GOOD, NOW UPDATED THE VOICEFILE & VOICEPRINT DATABASE:
			} else {
			
				# count number of voicefiles used in enrollment
				$number_of_voicefiles = count($final_voicefiles);
			
				# create the voicefileid value
				$i = 0;
				while($final_voicefiles[$i]) {
					if($final_voicefiles[$i+1]) {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'] . ",";
					} else {
						$enrollment_voicefileids = $enrollment_voicefileids . $final_voicefiles[$i]['voicefileid'];
					}
					$i++;
				}
			
			
				### UPDATE VOICEPRINT DATABASE ENTRY:
				$tmp_query = "UPDATE voiceprints SET voicefileids = '" . $enrollment_voicefileids . "' WHERE voiceprintid LIKE '" . $voiceprintid . "';";
				updateTHECASHIER($tmp_query);
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","tmp_query: " . $tmp_query);
				if($logging) logf("/tmp/biometric_registration__payme_function.txt","voiceprintids: " . $voiceprintid);
				return $voiceprintid;
			}
		}
	}
}



function biometric_transaction($memberid,$filename) {
	
	global $master_config_ibmsiv_host;

	### SET DATETIME:
	$timestamp = date("Y-m-d H:i:s");
	
	
	### LOGGING:
	$logging = "ON";
	if($logging) logf("/tmp/biometric_transaction_function.txt","
	
	
	
	
	### Fucntion biometric_transaction() ########################################################
	
	");
	if($logging) logf("/tmp/biometric_transaction_function.txt","timestamp: " . $timestamp);
	if($logging) logf("/tmp/biometric_transaction_function.txt","memberid: " . $memberid);
	if($logging) logf("/tmp/biometric_transaction_function.txt","filename: " . $filename);
	if($logging) logf("/tmp/biometric_transaction_function.txt","description: " . $description);
	
	
	### FIX POSSIBLE ISSUE WITH TRANSACTION FILE NOT HAVING MEMBERID (COMES FROM USERS WHO CLAIM TO BE NEW USERS): might need to perfect to save dataasing time.
	global $member;
	$broad_filename = explode("_",$filename);
	### UPDATE VOICEFILES WITH MEMBERID:
	$tmp_date = date("Y-m"); # security procation is all.  look for matching year-month
	$tmp_sql = "UPDATE voicefiles SET memberid = '" . $member["memberid"] . "' WHERE filename LIKE '" . $broad_filename[0] . "%' AND confidence_asr >= '50' AND description = 'PayMe' AND created LIKE '" . $tmp_date . "%' AND memberid = '';";
	$update_results = updateTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","update_results = : " . $update_results);
	
	
	
	### GET VOICEFILEID:
	$tmp_sql = "SELECT voicefileid FROM voicefiles WHERE memberid = '$memberid' AND filename = '" . $filename . "'";
	$voicefileid = getTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","voicefileid: " . $voicefileid);
	
	
	### GET VOICEPRINTID:
	$tmp_sql = "SELECT voiceprintid FROM voiceprints WHERE memberid = '$memberid' AND description = 'Transaction'";
	$voiceprintid = getTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","voiceprintid: " . $voiceprintid);
	
	
	### GET VOICEFILEIDS FORM VOICEPRINT:
	$tmp_sql = "SELECT voicefileids FROM voiceprints WHERE memberid = '$memberid' AND description = 'Transaction'";
	$current_voicefileids = getTHECASHIER($tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","current_voicefileids: " . $current_voicefileids);
	
	
	### EXPLODE & COUNT NUMBER OF VOICEPRINTS:
	$current_voicefileids = explode(",",$current_voicefileids);
	$number_of_voicefileids = count($current_voicefileids);
	
	
	### PREP NEW ENROLLMENT ARRAY:
	$number_of_voicefileids = $number_of_voicefileids - 1; # gets the value to work for the while loop.
	$new_filenames = NULL;
	$new_filenames = array();
	$tmp_voicefileids = NULL;
	$tmp_voicefileids = array();
	$i = 0;
	while(($current_voicefileids[$number_of_voicefileids]) && ($i < 4)) { # make sure there are only 4 or less (note:i=0)
	
			### GET & BUILD FILENAME FOR EACH:
		$tmp_sql = "SELECT filename FROM voicefiles WHERE voicefileid LIKE '{$current_voicefileids[$number_of_voicefileids]}'";
		$new_filenames[$i] = getTHECASHIER($tmp_sql);
		if($logging) logf("/tmp/biometric_transaction_function.txt","tmp_sql: " . $tmp_sql);
		if($logging) logf("/tmp/biometric_transaction_function.txt","voiceprintid: " . $new_filenames[$i]);
		
		### BUILD NEW VOICEFILEIDS VALUE:
		$tmp_voicefileids[$i] = $current_voicefileids[$number_of_voicefileids];
		if($logging) logf("/tmp/biometric_transaction_function.txt","new_voicefileids[$i]: " . $new_voicefileids[$i]);
		
		$i++;
		$number_of_voicefileids = $number_of_voicefileids - 1;
	}
	
	
	### COMPLETE ENROLLMENT ARRAY:
	$new_filenames = array_reverse($new_filenames); #gets the values in the correct order for loopings
	$i = count($new_filenames);
	$new_filenames[$i] = $filename;
	
	### BUILD & COMPLETE NEW VOICEFILEIDS VALUE:
	$i = 0;
	while($tmp_voicefileids[$i]) {
		$new_voicefileids = $tmp_voicefileids[$i] . "," . $new_voicefileids;
		$i++;
	}
	
	$new_voicefileids = $new_voicefileids . $voicefileid;
	
	
	### UPDATE VOICEPRINT DATABASE:
	$tmp_query = "UPDATE voiceprints SET voicefileids = '$new_voicefileids' WHERE voiceprintid LIKE '$voiceprintid'";
	updateTHECASHIER($tmp_query);
	if($logging) logf("/tmp/biometric_transaction_function.txt","tmp_sql: " . $tmp_sql);
	if($logging) logf("/tmp/biometric_transaction_function.txt","new_voicefileids: " . $new_voicefileids);
	
	
		
	### ENROLL THE VOICEPRINT: #######################
		

	# SET COMMON VARS:
	$send_session = curl_init();
	curl_setopt ($send_session, CURLOPT_HEADER,0);
	curl_setopt($send_session, CURLOPT_POST,1);
	curl_setopt($send_session, CURLOPT_RETURNTRANSFER,1);
	
	
	#create tmp file for cookie
	$cookie_file = tempnam ("/tmp", "CURLCOOKIE");
	curl_setopt ($send_session, CURLOPT_COOKIEJAR, $cookie_file); 
	
	
	$post_url =  "http://" . $master_config_ibmsiv_host . "/ibmsiv/startsession";
	$post_fields = "mode=enroll&voiceprint=" . $voiceprintid;
	
	//test("post_url",$post_url);
	//test("post_fields",$post_fields);
	//exit;
	
	curl_setopt($send_session, CURLOPT_URL, $post_url);
	curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
	
	if($logging) logf("/tmp/biometric_transaction_function.txt"," START SESSION: " . $post_url . "?" . $post_fields);
	
	
	
	# execute session:
	$send_results = NULL;
	$attempt = 1;
	while((!$send_results) && ($attempt < 5)) {
		$send_results = curl_exec($send_session);
		if($logging) logf("/tmp/biometric_transaction_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
		if(!$send_results) {
			$send_results = curl_error($send_session);
			if($logging) logf("/tmp/biometric_transaction_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
			$send_results = NULL;
		}
		$attempt++;
	}
	
	//exit;
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		$send_results = curl_error($send_session);
		if($logging) logf("/tmp/biometric_registration_function.txt","send_results (FINAL ERROR): " . $send_results);
		curl_close($send_session);
		return $send_results;
	
	} else {
		
		## all good, keep going:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/verify";
		
		# start looping through the files:
	
		$i = 0;
		while($new_filenames[$i]) {
		
			$post_fields = "input-wave-uri=/root/audio/incoming_voice_authorizations/" . $new_filenames[$i] . ".al";
			curl_setopt($send_session, CURLOPT_URL, $post_url);
			curl_setopt($send_session, CURLOPT_POSTFIELDS, $post_fields);
			if($logging) logf("/tmp/biometric_transaction_function.txt","post url: " . $post_url . $post_fields);
	
			$attempt = 1;
			$send_results = NULL;
			while((!$send_results) && ($attempt < 5)) {
				
				$send_results = curl_exec($send_session);
				if($logging) logf("/tmp/biometric_transaction_function.txt","send_results: " . $send_results);
		
				if(!$send_results) {
					$send_results = curl_error($send_session);
					if($logging) logf("/tmp/biometric_transaction_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				}
				
				$attempt++;
			
			}
			
			$i++;
		}
	}
	
	## if there was an error with this initial communication:
	if(!$send_results) {
		$send_results = curl_error($send_session);
		if($logging) logf("/tmp/biometric_registration_function.txt","send_results (FINAL ERROR): " . $send_results);
		curl_close($send_session);
		return $send_results;
	
	} else {
		
		### prep to close the session:
		$post_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/endsession";
		curl_setopt($send_session, CURLOPT_URL, $post_url);
		curl_setopt($send_session, CURLOPT_POSTFIELDS,NULL);
		if($logging) logf("/tmp/biometric_transaction_function.txt","post url: " . $post_url);

		# execute session:
		$send_results = NULL;
		$attempt = 1;
		while((!$send_results) && ($attempt < 5)) {
			$send_results = curl_exec($send_session);
			if($logging) logf("/tmp/biometric_transaction_function.txt","attempt #" . $attempt . " send_results: " . $send_results);
		
			if(!$send_results) {
				$send_results = curl_error($send_session);
				if($logging) logf("/tmp/biometric_transaction_function.txt","attempt #" . $attempt . " send_results (ERROR): " . $send_results);
				$send_results = NULL;
			}
			
			$attempt++;
		}
		
		return $voiceprintid;

	}
}

function bonus_percentage($command) {

	global $master_config_bonus_outgoing_payment;
	if($command == "larger") {
		$tmp_bonus_payment_percentage = "<span style='font-size:larger;'>" . number_format($master_config_bonus_outgoing_payment * 100,"1") . "%</span>";
	} else {
		$tmp_bonus_payment_percentage = number_format($master_config_bonus_outgoing_payment * 100,"1") . "%";
	}

	return $tmp_bonus_payment_percentage;
}




function faq_personalizer($text_to_personalize) {

	global $template;
	
	if(strtoupper($_SESSION['account']['accounttype']) == "BUSINESS") {
		$tmp_business_account_emailaddress = $_SESSION['account']['email_account_address'];
	} else {
		$tmp_business_account_emailaddress = "(your registered COMPANY_NAME Business Account Email Address)";
	}
	
	$text_to_personalize = str_replace("BUSINESS_ACCOUNT_EMAILADDRESS", $tmp_business_account_emailaddress, $text_to_personalize);
	
	$text_to_personalize = str_replace("COMPANY_SIMPLE_NAME", $_SESSION['template']['company']['simple_name'], $text_to_personalize);
	$text_to_personalize = str_replace("COMPANY_NAME", $_SESSION['template']['company']['name'], $text_to_personalize);
	$text_to_personalize = str_replace("COMPANY_DOMAIN", $_SESSION['template']['company']['domain'], $text_to_personalize);
	$text_to_personalize = str_replace("COMPANY_EMAILADDRESS_SUPPORT", $_SESSION['template']['company']['emailaddress_support'], $text_to_personalize);
	$text_to_personalize = str_replace("COMPANY_HOST_IMAGES", $_SESSION['template']['company']['host_images'], $text_to_personalize);
	$text_to_personalize = str_replace("UNIQUE_SESSION_ID", hash_me(), $text_to_personalize);
	
	
	
	$text_to_personalize = str_replace("QUESTION", "javascript:go_to_answer", $text_to_personalize);
	$text_to_personalize = str_replace("TOPIC", "javascript:list_the_questions", $text_to_personalize);
	
	$dynamic_processing_profile = get_dynamic_processing_profile();
	
	$text_to_personalize = str_replace("COMPANY_DYNAMIC_PROFILE", $dynamic_processing_profile['profile_html_table'], $text_to_personalize);
	
	
	
	
	$tmp_bonus_payment_percentage = bonus_percentage("larger");
	$text_to_personalize = str_replace("COMPANY_BONUS_OUTGOING_PAYMENT", $tmp_bonus_payment_percentage, $text_to_personalize);

	return $text_to_personalize;
}


function object_to_array($mixed) {
if(is_object($mixed)) $mixed = (array) $mixed;
if(is_array($mixed)) {
$new = array();
foreach($mixed as $key => $val) {
//$key = preg_replace("/^\(.*)\/�,�",$key);
$new[$key] = object_to_array($val);
}
}
else $new = $mixed;
return $new;
}


function object_2_array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}



function disguise_emailaddress($emailaddress) {

	$tmp_emailaddress = explode("@",$emailaddress);
	$split = str_split($tmp_emailaddress[0]);
	
	
	$reverse = array_reverse($split);
	$reverse[0] = "<span style='color:#888888;'>*</span>";
	$reverse[1] = "<span style='color:#888888;'>*</span>";
	$rereverse = array_reverse($reverse);
	$disgused_username = implode("",$rereverse);
	
	/*
	$i = 3;
	while($split[$i]) {
		$split[$i] = "<span style='color:#888888;'>*</span>";
		$i = $i + 4;
	}
	$disgused_username = implode("",$split);
	*/
	
	return $disgused_username . "@" . $tmp_emailaddress[1];
}


function disguise_emailaddress_text($emailaddress) {

	$tmp_emailaddress = explode("@",$emailaddress);
	$split = $tmp_emailaddress[0];
	
	
	
	$domain = $tmp_emailaddress[1];
	
	$domain = substr($domain, -6);    // returns "ef"
	
	$domain = "***".$domain;
	
	$split = substr($split, 0, 3);
	
	$split = $split. "***";
	
	$reverse = array_reverse($split);
	$reverse[0] = "*";
	$reverse[1] = "*";
	$rereverse = array_reverse($reverse);
	$disgused_username = implode("",$rereverse);
	
	/*
	$i = 3;
	while($split[$i]) {
		$split[$i] = "<span style='color:#888888;'>*</span>";
		$i = $i + 4;
	}
	$disgused_username = implode("",$split);
	*/
	
	return $split . "@" . $domain;
	//return $disgused_username . "@" . $tmp_emailaddress[1];
}


function update_authorization_number($memberid,$country_iso3,$calling_code,$phone_number) {	
	
	
	$current_authorization_number = authorization_number($memberid);
	
	logger3("F(update_authorization_number): current_authorization_number",$current_authorization_number);
	
	if(	
	($current_authorization_number['number'] != $phone_number) ||
	($current_authorization_number['calling_code'] != $calling_code)
	 
	) {
	
		### update current authorization number to inactive
		$tmp_timestamp = time();
		$tmp_sql = "UPDATE phone_numbers SET status = NULL, updated = '" . $_SESSION['authorization']['datetime'] . "' WHERE phonenumberid LIKE '" . $current_authorization_number['phonenumberid'] . "';";
		updateTHECASHIER($tmp_sql);
		
		
		### check to see if new authorization number is in the dataabase:
		$tmp_sql = "SELECT phonenumberid FROM phone_numbers WHERE memberid = '" . $memberid . "' AND calling_code = '" . $calling_code . "' AND number = '" . $phone_number . "';";
		logger3("tmp_query",$tmp_sql);
		$phonenumberid = getTHECASHIER($tmp_sql);
		
		
		# phone number existed - simply update status
		if($phonenumberid) {
			
			$tmp_sql = "UPDATE phone_numbers SET status = 'Active', description = 'Authorization', updated = '" . $_SESSION['authorization']['datetime'] . "' WHERE phonenumberid LIKE '" . $phonenumberid . "';";
			logger3("tmp_sql",$tmp_sql);
			updateTHECASHIER($tmp_sql);
		
		# phone number does NOT exist - add to database
		} else {
	
			### SET NEW AUTH. PHONE NUMBER:
			$tmp_sql = "INSERT into phone_numbers (
				`phonenumberid`,
				`memberid`,
				`country_iso3`,
				`calling_code`,
				`number`,
				`description`,
				`status`,
				`created`,
				`updated`
			) VALUES (
				'" . $phonenumberid . "',
				'" . $memberid . "',
				'" . $country_iso3 . "',
				'" . $calling_code . "',
				'" . $phone_number . "',
				'Authorization',
				'Active',
				'" . $_SESSION['authorization']['datetime'] . "',
				'" . $_SESSION['authorization']['datetime'] . "');";
			
			logger3("tmp_sql",$tmp_sql);
			
			$phonenumberid = insertTHECASHIER($tmp_sql);
		}
	
	## member used the same phone number
	} else {
		
		logger3("F(update_authorization_number): current_authorization_number['phonenumberid']",$current_authorization_number['phonenumberid']);
		$phonenumberid = $current_authorization_number['phonenumberid'];
	}
	
	return $phonenumberid;
}




function fx_convert_fee($fee_currency_iso3,$fee_value,$to_currency) {
	if($fee_currency_iso3 == "USD") {
		$fee_value['USD'] = $fee_value;
		$fee_value[$to_currency] = currency_format(number_format(get_fx("USD",$to_currency,$fee_value['USD'])));
	} else {
		$fee_value[$fee_currency_iso3] = $fee_value;
		$fee_value['USD'] = currency_format(number_format(get_fx($fee_currency,"USD",$fee_value[$fee_currency_iso3])));
		$fee_value[$to_currency] = get_fx("USD",$to_currency,$fee_value['USD']);
	}
	return $fee_value;
}






function get_fx($from_Currency,$to_Currency,$amount) {

	if( ($amount == "") || ($amount == " ") || ($amount == NULL) || ($amount == 0) || ($amount == 0.0) || ($amount == 0.00) || ($amount == "0") || ($amount == "0.0") || ($amount == "0.00") ) {
		return "0.00";
	}
	
	
	$amount = urlencode($amount);
	$from_Currency = urlencode($from_Currency);
	$to_Currency = urlencode($to_Currency);
	
	//test("to_Currency",$to_Currency);
	//test("amount",$amount);
	
	### SET VERSION:
	$use = "v2";
	
	
	if($use == "v1") {
		$url = "100USD";
	}
	if($use == "v2") {
		$url = "http://www.google.com/finance/converter?a=" . $amount . "&from=" . $from_Currency . "&to=" . $to_Currency;
	}
	if($use == "v3") {
		$url = "www.google.com/finance?q=" . "USD"  . "XCD";
	}
	if($use == "v4") {
		$yahoo_s = $from_Currency . $to_Currency;
		//test("cer",$yahoo_s);
		$url = "http://finance.yahoo.com/q/bc?s=" . $yahoo_s . "=X&t=5d&l=on&z=m&q=l&c=";
	}
	
	if($use == "v5") {
		$url = "http://fxtop.com/en/cnvhisto.php3?C1=" . $from_Currency . "&C2=" . $to_Currency;
	}
	
	if($use == "v6") {
		$url = "http://finance.yahoo.com/currency-converter/#from=" . $from_Currency . ";to=" . $to_Currency . ";amt=" . $amount;
	}
	
	
	$ch = curl_init();
	$timeout = 0;
	curl_setopt ($ch, CURLOPT_URL, $url);
	curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
	curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
	$rawdata = curl_exec($ch);
	curl_close($ch);
	 
	if($use == "v1") {
		$data = explode('"', $rawdata);
		$data = explode(' ', $data['3']);
		$var = $data['0'];
		return (float) preg_replace('/[^0-9.]*/','',$var);
	}
	
	if($use == "v000") {
		//test("data 0",$rawdata);
		$data = explode('currency_converter_result', $rawdata);
		//test("data 1",$data);
		$data = explode(' ', $data['1']);
		//test("data 2",$data);
		$var = $data['0'];
		return (float) preg_replace('/[^0-9.]*/','',$var);
	}
	
	if($use == "v2") {
		//test("data 0",$rawdata);
		$data = explode('<span class=bld>', $rawdata);
		//test("data 1",$data[1]);
		$data = explode(' ', $data['1']);
		//test("data 2",$data);
		$var = $data['0'];
		return (float) preg_replace('/[^0-9.]*/','',$var);
	}
	
	if($use == "v4") {
		//test("data 0",$rawdata);
		$data = explode('Last Trade:', $rawdata);
		//test("data 1",$data[1]);
		$data = explode('">', $data[1]);
		//test("data 2",$data);
		$data = explode('</', $data[2]);
		//test("data 3",$data);
		$var = $data[0];
		//test("var",$var);
		$var = preg_replace('/[^0-9.]*/','',$var);
		//test("var",$var);
		if(isset($amount) && ($amount != "1.00") || ($amount != "1")) {
			//test("amount",$amount);
			//test("var",$var);
			$var = $var * $amount;
			//test("var",$var);
		}
		//return $var;
		return number_format($var,4,".","");
	}
	
	if($use == "v5") {
		//test("data 0",$rawdata);
		$data = explode('<TD  align=center>', $rawdata);
		$data = explode('=', $data[2]);
		$data = explode($to_Currency, $data[1]);
		//test("data 0",$data);
		$var = str_replace(' ','',$data[0]);
		return $var;
	}

	if($use == "v6") {
		//test("data 0",$rawdata);
		$data = explode('Exchange rate of ', $rawdata);
		//test("data 0",$data[1]);
		$data = explode('on', $data[1]);
		$var = str_replace(' ','',$data[0]);
		return $var;
	}
	
}


function equals_symbol() {
	#key words: estimate, approx, approximate
	//$equal_symbol = "�";
	//$equal_symbol = "&#126;"; # single wavey
	//$equal_symbol = "&#8773;"; # three lines - top one wavey
	//$equal_symbol = "&#8776;"; # 
	$equal_symbol = "&#8776;"; # 
	return $equal_symbol;
}

function fx_name() {
	global $template;
	return "Google&reg; FX";
	//echo $_SESSION['template']['company']['fx_name'];
}

function fx_name_formal() {
	//global $template;
	return "Google Finance&reg;";
	//echo $_SESSION['template']['company']['fx_name'];
}

function currency_format($amount,$thousands_seperator) {
	//test("thousands_seperator",$thousands_seperator);
	# strip commas (if they exist)
	$amount = str_replace(",", "", $amount);
	if(
	($amount == "") ||
	($amount == " ") ||
	($amount == NULL) ||
	(!$amount) 
	) {
		$amount = "0.00";
	}
	if($thousands_seperator == ",") {
		
		$result = number_format($amount,2,".",$thousands_seperator);
		//test("0. result",$result);
		return $result;
	} else {
		$result = number_format($amount,2,".","");
		//test("1. result",$result);
		return $result;
	}
}

function country_to_currency($country_code) {


		$country_code = trim(strtoupper($country_code));

			if($country_code == "AFGHANISTAN" || $country_code == "AF" || $country_code == "AFG") return "AFN"; 
    //if($country_code == "�LAND ISLANDS" || $country_code == "AX" || $country_code == "ALA") return ""; 
    if($country_code == "ALBANIA" || $country_code == "AL" || $country_code == "ALB") return "ALL"; 
    //if($country_code == "ALDERNEY" || $country_code == "&nbsp;" || $country_code == "&nbsp;") return ""; 
    if($country_code == "ALGERIA" || $country_code == "DZ" || $country_code == "DZA") return "DZD"; 
    if($country_code == "AMERICAN SAMOA" || $country_code == "AS" || $country_code == "ASM") return "USD"; 
    if($country_code == "ANDORRA" || $country_code == "AD" || $country_code == "AND") return "EUR"; 
    if($country_code == "ANGOLA" || $country_code == "AO" || $country_code == "AGO") return "AOA"; 
    if($country_code == "ANGUILLA" || $country_code == "AI" || $country_code == "AIA") return "XCD"; 
    //if($country_code == "ANTARCTICA" || $country_code == "AQ" || $country_code == "ATA") return ""; 
    if($country_code == "ANTIGUA AND BARBUDA" || $country_code == "AG" || $country_code == "ATG") return "XCD"; 
    if($country_code == "ARGENTINA" || $country_code == "AR" || $country_code == "ARG") return "ARS"; 
    if($country_code == "ARMENIA" || $country_code == "AM" || $country_code == "ARM") return "AMD"; 
    if($country_code == "ARUBA" || $country_code == "AW" || $country_code == "ABW") return "AWG"; 
    //if($country_code == "ASCENSION ISLAND" || $country_code == "&nbsp;" || $country_code == "&nbsp;") return ""; 
    if($country_code == "AUSTRALIA" || $country_code == "AU" || $country_code == "AUS") return "AUD"; 
    if($country_code == "AUSTRIA" || $country_code == "AT" || $country_code == "AUT") return "EUR"; 
    if($country_code == "AZERBAIJAN" || $country_code == "AZ" || $country_code == "AZE") return "AZN"; 

    if($country_code == "BAHAMAS" || $country_code == "BS" || $country_code == "BHS") return "BSD"; 
    if($country_code == "BAHRAIN" || $country_code == "BH" || $country_code == "BHR") return "BHD"; 
    if($country_code == "BANGLADESH" || $country_code == "BD" || $country_code == "BGD") return "BDT"; 
    if($country_code == "BARBADOS" || $country_code == "BB" || $country_code == "BRB") return "BBD"; 
    if($country_code == "BELARUS" || $country_code == "BY" || $country_code == "BLR") return "BYR"; 
    if($country_code == "BELGIUM" || $country_code == "BE" || $country_code == "BEL") return "EUR"; 
    if($country_code == "BELIZE" || $country_code == "BZ" || $country_code == "BLZ") return "BZD"; 
    if($country_code == "BENIN" || $country_code == "BJ" || $country_code == "BEN") return "XOF"; 
    if($country_code == "BERMUDA" || $country_code == "BM" || $country_code == "BMU") return "BMD"; 
    if($country_code == "BHUTAN" || $country_code == "BT" || $country_code == "BTN") return "BTN"; 
    if($country_code == "BOLIVIA" || $country_code == "BO" || $country_code == "BOL") return "BOB"; 
    if($country_code == "BOSNIA AND HERZEGOVINA" || $country_code == "BA" || $country_code == "BIH") return "BAM"; 
    if($country_code == "BOTSWANA" || $country_code == "BW" || $country_code == "BWA") return "BWP"; 
    if($country_code == "BOUVET ISLAND" || $country_code == "BV" || $country_code == "BVT") return "NOK"; 
    if($country_code == "BRAZIL" || $country_code == "BR" || $country_code == "BRA") return "BRL"; 

    //if($country_code == "BRITISH INDIAN OCEAN TERRITORY" || $country_code == "IO" || $country_code == "IOT") return ""; 
    if($country_code == "BRUNEI DARUSSALAM" || $country_code == "BN" || $country_code == "BRN") return "BND"; 
    if($country_code == "BULGARIA" || $country_code == "BG" || $country_code == "BGR") return "BGN"; 
    if($country_code == "BURKINA FASO" || $country_code == "BF" || $country_code == "BFA") return "XOF"; 
    if($country_code == "BURUNDI" || $country_code == "BI" || $country_code == "BDI") return "BIF"; 
    if($country_code == "CAMBODIA" || $country_code == "KH" || $country_code == "KHM") return "KHR"; 
    if($country_code == "CAMEROON" || $country_code == "CM" || $country_code == "CMR") return "XAF"; 
    if($country_code == "CANADA" || $country_code == "CA" || $country_code == "CAN") return "CAD"; 
    if($country_code == "CAPE VERDE" || $country_code == "CV" || $country_code == "CPV") return "CVE"; 
    if($country_code == "CAYMAN ISLANDS" || $country_code == "KY" || $country_code == "CYM") return "KYD"; 
    if($country_code == "CENTRAL AFRICAN REPUBLIC" || $country_code == "CF" || $country_code == "CAF") return "XAF"; 
    if($country_code == "CHAD (Tchad)" || $country_code == "TD" || $country_code == "TCD") return "XAF"; 
    //if($country_code == "CHANNEL ISLANDS" || $country_code == "&nbsp;" || $country_code == "&nbsp;") return ""; 
    if($country_code == "CHILE" || $country_code == "CL" || $country_code == "CHL") return "CLP"; 
    if($country_code == "CHINA" || $country_code == "CN" || $country_code == "CHN") return "CNY"; 


    if($country_code == "CHRISTMAS ISLAND" || $country_code == "CX" || $country_code == "CXR") return "AUD"; 
    if($country_code == "COCOS (KEELING) ISLANDS" || $country_code == "CC" || $country_code == "CCK") return "AUD"; 
    if($country_code == "COLOMBIA" || $country_code == "CO" || $country_code == "COL") return "COP"; 
    if($country_code == "COMOROS" || $country_code == "KM" || $country_code == "COM") return "KMF"; 

    if($country_code == "CONGO, REPUBLIC OF" || $country_code == "CG" || $country_code == "COG") return "XAF"; 
    if($country_code == "CONGO, THE DEMOCRATIC REPUBLIC OF THE (formerly Zaire)" || $country_code == "CD" || $country_code == "COD") return "XAF"; 
    if($country_code == "COOK ISLANDS" || $country_code == "CK" || $country_code == "COK") return "NZD"; 
    if($country_code == "COSTA RICA" || $country_code == "CR" || $country_code == "CRI") return "CRC"; 
    if($country_code == "C�TE D'IVOIRE (Ivory Coast)" || $country_code == "CI" || $country_code == "CIV") return "XAF"; 
    if($country_code == "CROATIA (Hrvatska)" || $country_code == "HR" || $country_code == "HRV") return "HRK"; 
    if($country_code == "CUBA" || $country_code == "CU" || $country_code == "CUB") return "CUP"; 
    if($country_code == "CYPRUS" || $country_code == "CY" || $country_code == "CYP") return "CYP"; 
    if($country_code == "CZECH REPUBLIC" || $country_code == "CZ" || $country_code == "CZE") return "CZK"; 
    if($country_code == "DENMARK" || $country_code == "DK" || $country_code == "DNK") return "DKK"; 
    if($country_code == "DJIBOUTI" || $country_code == "DJ" || $country_code == "DJI") return "DJF"; 

    if($country_code == "DOMINICA" || $country_code == "DM" || $country_code == "DMA") return "XCD"; 
    if($country_code == "DOMINICAN REPUBLIC" || $country_code == "DO" || $country_code == "DOM") return "DOP"; 
    if($country_code == "ECUADOR" || $country_code == "EC" || $country_code == "ECU") return "USD"; 
    if($country_code == "EGYPT" || $country_code == "EG" || $country_code == "EGY") return "EGP"; 
    if($country_code == "EL SALVADOR" || $country_code == "SV" || $country_code == "SLV") return "SVC"; 
    if($country_code == "EQUATORIAL GUINEA" || $country_code == "GQ" || $country_code == "GNQ") return "XAF"; 
    if($country_code == "ERITREA" || $country_code == "ER" || $country_code == "ERI") return "ERN"; 
    if($country_code == "ESTONIA" || $country_code == "EE" || $country_code == "EST") return "EEK"; 
    if($country_code == "ETHIOPIA" || $country_code == "ET" || $country_code == "ETH") return "ETB"; 
    if($country_code == "FAEROE ISLANDS" || $country_code == "FO" || $country_code == "FRO") return "DKK"; 
    if($country_code == "FALKLAND ISLANDS (MALVINAS)" || $country_code == "FK" || $country_code == "FLK") return "FKP"; 
    if($country_code == "FIJI" || $country_code == "FJ" || $country_code == "FJI") return "FJD"; 
    if($country_code == "FINLAND" || $country_code == "FI" || $country_code == "FIN") return "EUR"; 
    if($country_code == "FRANCE" || $country_code == "FR" || $country_code == "FRA") return "EUR"; 

    if($country_code == "FRENCH GUIANA" || $country_code == "GF" || $country_code == "GUF") return "EUR"; 
    if($country_code == "FRENCH POLYNESIA" || $country_code == "PF" || $country_code == "PYF") return "XPF"; 
    if($country_code == "FRENCH SOUTHERN TERRITORIES" || $country_code == "TF" || $country_code == "ATF") return "EUR"; 
    if($country_code == "GABON" || $country_code == "GA" || $country_code == "GAB") return "XAF"; 
    if($country_code == "GAMBIA, THE" || $country_code == "GM" || $country_code == "GMB") return "GMD"; 
    if($country_code == "GEORGIA" || $country_code == "GE" || $country_code == "GEO") return "GEL"; 
    if($country_code == "GERMANY (Deutschland)" || $country_code == "DE" || $country_code == "DEU") return "EUR"; 
    if($country_code == "GHANA" || $country_code == "GH" || $country_code == "GHA") return "GHS"; 
    if($country_code == "GIBRALTAR" || $country_code == "GI" || $country_code == "GIB") return "GIP"; 
    if($country_code == "GREAT BRITAIN" || $country_code == "GB" || $country_code == "GBR") return "GBP"; 
    if($country_code == "GREECE" || $country_code == "GR" || $country_code == "GRC") return "EUR"; 
    if($country_code == "GREENLAND" || $country_code == "GL" || $country_code == "GRL") return "DKK"; 
    if($country_code == "GRENADA" || $country_code == "GD" || $country_code == "GRD") return "XCD"; 
    if($country_code == "GUADELOUPE" || $country_code == "GP" || $country_code == "GLP") return "EUR"; 
    if($country_code == "GUAM" || $country_code == "GU" || $country_code == "GUM") return "USD"; 
    if($country_code == "GUATEMALA" || $country_code == "GT" || $country_code == "GTM") return "GTQ"; 

    if($country_code == "GUERNSEY" || $country_code == "&nbsp;" || $country_code == "&nbsp;") return "GGP"; 
    if($country_code == "GUINEA" || $country_code == "GN" || $country_code == "GIN") return "GNF"; 
    if($country_code == "GUINEA-BISSAU" || $country_code == "GW" || $country_code == "GNB") return "XOF"; 
    if($country_code == "GUYANA" || $country_code == "GY" || $country_code == "GUY") return "GYD"; 
    if($country_code == "HAITI" || $country_code == "HT" || $country_code == "HTI") return "HTG"; 
    if($country_code == "HEARD ISLAND AND MCDONALD ISLANDS" || $country_code == "HM" || $country_code == "HMD") return "AUD"; 
    if($country_code == "HONDURAS" || $country_code == "HN" || $country_code == "HND") return "HNL"; 
    if($country_code == "HONG KONG (Special Administrative Region of China)" || $country_code == "HK" || $country_code == "HKG") return "HKD"; 
    if($country_code == "HUNGARY" || $country_code == "HU" || $country_code == "HUN") return "HUF"; 

    if($country_code == "ICELAND" || $country_code == "IS" || $country_code == "ISL") return "ISK"; 
    if($country_code == "INDIA" || $country_code == "IN" || $country_code == "IND") return "INR"; 
    if($country_code == "INDONESIA" || $country_code == "ID" || $country_code == "IDN") return "IDR"; 
    if($country_code == "IRAN (Islamic Republic of Iran)" || $country_code == "IR" || $country_code == "IRN") return "IRR"; 
    if($country_code == "IRAQ" || $country_code == "IQ" || $country_code == "IRQ") return "IQD"; 
    if($country_code == "IRELAND" || $country_code == "IE" || $country_code == "IRL") return "EUR"; 

    if($country_code == "ISLE OF MAN" || $country_code == "&nbsp;" || $country_code == "&nbsp;") return "IMP"; 
    if($country_code == "ISRAEL" || $country_code == "IL" || $country_code == "ISR") return "ILS"; 
    if($country_code == "ITALY" || $country_code == "IT" || $country_code == "ITA") return "EUR"; 
    if($country_code == "JAMAICA" || $country_code == "JM" || $country_code == "JAM") return "JMD"; 
    if($country_code == "JAPAN" || $country_code == "JP" || $country_code == "JPN") return "JPY"; 
    if($country_code == "JERSEY" || $country_code == "&nbsp;" || $country_code == "&nbsp;") return "JEP"; 
    if($country_code == "JORDAN (Hashemite Kingdom of Jordan)" || $country_code == "JO" || $country_code == "JOR") return "JOD"; 
    if($country_code == "KAZAKHSTAN" || $country_code == "KZ" || $country_code == "KAZ") return "KZT"; 
    if($country_code == "KENYA" || $country_code == "KE" || $country_code == "KEN") return "KES"; 
    if($country_code == "KIRIBATI" || $country_code == "KI" || $country_code == "KIR") return "AUD"; 
    if($country_code == "KOREA (Democratic Peoples Republic of [North] Korea)" || $country_code == "KP" || $country_code == "PRK") return "KPW"; 
    if($country_code == "KOREA (Republic of [South] Korea)" || $country_code == "KR" || $country_code == "KOR") return "KRW"; 
    if($country_code == "KUWAIT" || $country_code == "KW" || $country_code == "KWT") return "KWD"; 
    if($country_code == "KYRGYZSTAN" || $country_code == "KG" || $country_code == "KGZ") return "KGS"; 
    if($country_code == "LAO PEOPLE'S DEMOCRATIC REPUBLIC" || $country_code == "LA" || $country_code == "LAO") return "LAK"; 
    if($country_code == "LATVIA" || $country_code == "LV" || $country_code == "LVA") return "LVL"; 

    if($country_code == "LEBANON" || $country_code == "LB" || $country_code == "LBN") return "LBP"; 
    if($country_code == "LESOTHO" || $country_code == "LS" || $country_code == "LSO") return "LSL"; 
    if($country_code == "LIBERIA" || $country_code == "LR" || $country_code == "LBR") return "LRD"; 
    if($country_code == "LIBYA (Libyan Arab Jamahirya)" || $country_code == "LY" || $country_code == "LBY") return "LYD"; 
    if($country_code == "LIECHTENSTEIN (F�rstentum Liechtenstein)" || $country_code == "LI" || $country_code == "LIE") return "CHF"; 
    if($country_code == "LITHUANIA" || $country_code == "LT" || $country_code == "LTU") return "LTL"; 
    if($country_code == "LUXEMBOURG" || $country_code == "LU" || $country_code == "LUX") return "EUR"; 
    if($country_code == "MACAO (Special Administrative Region of China)" || $country_code == "MO" || $country_code == "MAC") return "MOP"; 
    if($country_code == "MACEDONIA (Former Yugoslav Republic of Macedonia)" || $country_code == "MK" || $country_code == "MKD") return "MKD"; 
    if($country_code == "MADAGASCAR" || $country_code == "MG" || $country_code == "MDG") return "MGA"; 
    if($country_code == "MALAWI" || $country_code == "MW" || $country_code == "MWI") return "MWK"; 
    if($country_code == "MALAYSIA" || $country_code == "MY" || $country_code == "MYS") return "MYR"; 
    if($country_code == "MALDIVES" || $country_code == "MV" || $country_code == "MDV") return "MVR"; 
    if($country_code == "MALI" || $country_code == "ML" || $country_code == "MLI") return "XOF"; 
    if($country_code == "MALTA" || $country_code == "MT" || $country_code == "MLT") return "EUR"; 

    if($country_code == "MARSHALL ISLANDS" || $country_code == "MH" || $country_code == "MHL") return "USD"; 
    if($country_code == "MARTINIQUE" || $country_code == "MQ" || $country_code == "MTQ") return "EUR"; 
    if($country_code == "MAURITANIA" || $country_code == "MR" || $country_code == "MRT") return "MRO"; 
    if($country_code == "MAURITIUS" || $country_code == "MU" || $country_code == "MUS") return "MUR"; 
    if($country_code == "MAYOTTE" || $country_code == "YT" || $country_code == "MYT") return "EUR"; 
    if($country_code == "MEXICO" || $country_code == "MX" || $country_code == "MEX") return "MXN"; 
    if($country_code == "MICRONESIA (Federated States of Micronesia)" || $country_code == "FM" || $country_code == "FSM") return "USD"; 
    if($country_code == "MOLDOVA" || $country_code == "MD" || $country_code == "MDA") return "MDL"; 
    if($country_code == "MONACO" || $country_code == "MC" || $country_code == "MCO") return "EUR"; 
    if($country_code == "MONGOLIA" || $country_code == "MN" || $country_code == "MNG") return "MNT"; 
    if($country_code == "MONTSERRAT" || $country_code == "MS" || $country_code == "MSR") return "XCD"; 
    if($country_code == "MOROCCO" || $country_code == "MA" || $country_code == "MAR") return "MAD"; 
    if($country_code == "MOZAMBIQUE (Mo�ambique)" || $country_code == "MZ" || $country_code == "MOZ") return "MZN"; 
    if($country_code == "MYANMAR (formerly Burma)" || $country_code == "MM" || $country_code == "MMR") return "MMK"; 

    if($country_code == "NAMIBIA" || $country_code == "NA" || $country_code == "NAM") return "NAD"; 

    if($country_code == "NAURU" || $country_code == "NR" || $country_code == "NRU") return "AUD"; 
    if($country_code == "NEPAL" || $country_code == "NP" || $country_code == "NPL") return "NPR"; 
    if($country_code == "NETHERLANDS" || $country_code == "NL" || $country_code == "NLD") return "ANG"; 
    if($country_code == "NETHERLANDS ANTILLES" || $country_code == "AN" || $country_code == "ANT") return "ANG"; 
    if($country_code == "NEW CALEDONIA" || $country_code == "NC" || $country_code == "NCL") return "XPF"; 
    if($country_code == "NEW ZEALAND" || $country_code == "NZ" || $country_code == "NZL") return "NZD"; 
    if($country_code == "NICARAGUA" || $country_code == "NI" || $country_code == "NIC") return "NIO"; 
    if($country_code == "NIGER" || $country_code == "NE" || $country_code == "NER") return "XOF"; 
    if($country_code == "NIGERIA" || $country_code == "NG" || $country_code == "NGA") return "NGN"; 
    if($country_code == "NIUE" || $country_code == "NU" || $country_code == "NIU") return "NZD"; 
    if($country_code == "NORFOLK ISLAND" || $country_code == "NF" || $country_code == "NFK") return "AUD"; 
    if($country_code == "NORTHERN MARIANA ISLANDS" || $country_code == "MP" || $country_code == "MNP") return "USD"; 
    if($country_code == "NORWAY" || $country_code == "NO" || $country_code == "NOR") return "NOK"; 
    if($country_code == "OMAN" || $country_code == "OM" || $country_code == "OMN") return "OMR"; 
    if($country_code == "PAKISTAN" || $country_code == "PK" || $country_code == "PAK") return "PKR"; 

    if($country_code == "PALAU" || $country_code == "PW" || $country_code == "PLW") return "USD"; 
    if($country_code == "PALESTINIAN TERRITORIES" || $country_code == "PS" || $country_code == "PSE") return "ILS"; 
    if($country_code == "PANAMA" || $country_code == "PA" || $country_code == "PAN") return "PAB"; 
    if($country_code == "PAPUA NEW GUINEA" || $country_code == "PG" || $country_code == "PNG") return "PGK"; 
    if($country_code == "PARAGUAY" || $country_code == "PY" || $country_code == "PRY") return "PYG"; 
    if($country_code == "PERU" || $country_code == "PE" || $country_code == "PER") return "PEN"; 
    if($country_code == "PHILIPPINES" || $country_code == "PH" || $country_code == "PHL") return "PHP"; 
    if($country_code == "PITCAIRN" || $country_code == "PN" || $country_code == "PCN") return "NZD"; 
    if($country_code == "POLAND" || $country_code == "PL" || $country_code == "POL") return "PLN"; 
    if($country_code == "PORTUGAL" || $country_code == "PT" || $country_code == "PRT") return "EUR"; 
    if($country_code == "PUERTO RICO" || $country_code == "PR" || $country_code == "PRI") return "USD"; 
    if($country_code == "QATAR" || $country_code == "QA" || $country_code == "QAT") return "QAR"; 
    if($country_code == "R�UNION" || $country_code == "RE" || $country_code == "REU") return "EUR"; 
    if($country_code == "ROMANIA" || $country_code == "RO" || $country_code == "ROU") return "RON"; 
    if($country_code == "RUSSIAN FEDERATION" || $country_code == "RU" || $country_code == "RUS") return "RUB"; 

    if($country_code == "RWANDA" || $country_code == "RW" || $country_code == "RWA") return "RWF"; 
    if($country_code == "SAINT HELENA" || $country_code == "SH" || $country_code == "SHN") return "SHP"; 
    if($country_code == "SAINT KITTS AND NEVIS" || $country_code == "KN" || $country_code == "KNA") return "XCD"; 
    if($country_code == "SAINT LUCIA" || $country_code == "LC" || $country_code == "LCA") return "XCD"; 
    if($country_code == "SAINT PIERRE AND MIQUELON" || $country_code == "PM" || $country_code == "SPM") return "EUR"; 
    if($country_code == "SAINT VINCENT AND THE GRENADINES" || $country_code == "VC" || $country_code == "VCT") return "XCD"; 
    if($country_code == "SAMOA (formerly Western Samoa)" || $country_code == "WS" || $country_code == "WSM") return "WST"; 
    if($country_code == "SAN MARINO (Republic of)" || $country_code == "SM" || $country_code == "SMR") return "EUR"; 
    if($country_code == "SAO TOME AND PRINCIPE" || $country_code == "ST" || $country_code == "STP") return "STD"; 
    if($country_code == "SAUDI ARABIA (Kingdom of Saudi Arabia)" || $country_code == "SA" || $country_code == "SAU") return "SAR"; 
    if($country_code == "SENEGAL" || $country_code == "SN" || $country_code == "SEN") return "XOF"; 
    if($country_code == "SERBIA AND MONTENEGRO (formerly Yugoslavia)" || $country_code == "CS" || $country_code == "SCG") return "RSD"; 
    if($country_code == "SEYCHELLES" || $country_code == "SC" || $country_code == "SYC") return "SCR"; 
    if($country_code == "SIERRA LEONE" || $country_code == "SL" || $country_code == "SLE") return "SLL"; 
    if($country_code == "SINGAPORE" || $country_code == "SG" || $country_code == "SGP") return "SGD"; 

    if($country_code == "SLOVAKIA (Slovak Republic)" || $country_code == "SK" || $country_code == "SVK") return "EUR"; 
    if($country_code == "SLOVENIA" || $country_code == "SI" || $country_code == "SVN") return "EUR"; 
    if($country_code == "SOLOMON ISLANDS" || $country_code == "SB" || $country_code == "SLB") return "SBD"; 
    if($country_code == "SOMALIA" || $country_code == "SO" || $country_code == "SOM") return "SOS"; 
    if($country_code == "SOUTH AFRICA (Zuid Afrika)" || $country_code == "ZA" || $country_code == "ZAF") return "ZAR"; 

    if($country_code == "SOUTH GEORGIA AND THE SOUTH SANDWICH ISLANDS" || $country_code == "GS" || $country_code == "SGS") return "GBP"; 
    if($country_code == "SPAIN (Espa�a)" || $country_code == "ES" || $country_code == "ESP") return "EUR"; 
    if($country_code == "SRI LANKA" || $country_code == "LK" || $country_code == "LKA") return "LKR"; 
    if($country_code == "SUDAN" || $country_code == "SD" || $country_code == "SDN") return "SDG"; 
    if($country_code == "SURINAME" || $country_code == "SR" || $country_code == "SUR") return "SRD"; 
    if($country_code == "SVALBARD AND JAN MAYEN" || $country_code == "SJ" || $country_code == "SJM") return "NOK"; 
    if($country_code == "SWAZILAND" || $country_code == "SZ" || $country_code == "SWZ") return "SZL"; 
    if($country_code == "SWEDEN" || $country_code == "SE" || $country_code == "SWE") return "SEK"; 
    if($country_code == "SWITZERLAND (Confederation of Helvetia)" || $country_code == "CH" || $country_code == "CHE") return "CHF"; 
    if($country_code == "SYRIAN ARAB REPUBLIC" || $country_code == "SY" || $country_code == "SYR") return "SYP"; 

    if($country_code == "TAIWAN (&quot;Chinese Taipei&quot; for IOC)" || $country_code == "TW" || $country_code == "TWN") return "TWD"; 
    if($country_code == "TAJIKISTAN" || $country_code == "TJ" || $country_code == "TJK") return "TJS"; 
    if($country_code == "TANZANIA" || $country_code == "TZ" || $country_code == "TZA") return "TZS"; 
    if($country_code == "THAILAND" || $country_code == "TH" || $country_code == "THA") return "THB"; 
    if($country_code == "TIMOR-LESTE (formerly East Timor)" || $country_code == "TL" || $country_code == "TLS") return "IDR"; 
    if($country_code == "TOGO" || $country_code == "TG" || $country_code == "TGO") return "XOF"; 
    if($country_code == "TOKELAU" || $country_code == "TK" || $country_code == "TKL") return "NZD"; 
    if($country_code == "TONGA" || $country_code == "TO" || $country_code == "TON") return "TOP"; 
    if($country_code == "TRINIDAD AND TOBAGO" || $country_code == "TT" || $country_code == "TTO") return "TTD"; 
    if($country_code == "TUNISIA" || $country_code == "TN" || $country_code == "TUN") return "TND"; 
    if($country_code == "TURKEY" || $country_code == "TR" || $country_code == "TUR") return "TRY"; 
    if($country_code == "TURKMENISTAN" || $country_code == "TM" || $country_code == "TKM") return "TMM"; 
    if($country_code == "TURKS AND CAICOS ISLANDS" || $country_code == "TC" || $country_code == "TCA") return "USD"; 
    if($country_code == "TUVALU" || $country_code == "TV" || $country_code == "TUV") return "TVD"; 
    if($country_code == "UGANDA" || $country_code == "UG" || $country_code == "UGA") return "UGX"; 
    if($country_code == "UKRAINE" || $country_code == "UA" || $country_code == "UKR") return "UAH"; 

    if($country_code == "UNITED ARAB EMIRATES" || $country_code == "AE" || $country_code == "ARE") return "AED"; 
    if($country_code == "UNITED KINGDOM (Great Britain)" || $country_code == "GB" || $country_code == "GBR") return "GBP"; 
    if($country_code == "UNITED STATES" || $country_code == "US" || $country_code == "USA") return "USD"; 
    if($country_code == "UNITED STATES MINOR OUTLYING ISLANDS" || $country_code == "UM" || $country_code == "UMI") return "USD"; 
    if($country_code == "URUGUAY" || $country_code == "UY" || $country_code == "URY") return "UYU"; 
    if($country_code == "UZBEKISTAN" || $country_code == "UZ" || $country_code == "UZB") return "UZS"; 
    if($country_code == "VANUATU" || $country_code == "VU" || $country_code == "VUT") return "VUV"; 
    if($country_code == "VATICAN CITY (Holy See)" || $country_code == "VA" || $country_code == "VAT") return "EUR"; 
    if($country_code == "VENEZUELA" || $country_code == "VE" || $country_code == "VEN") return "VEF"; 
    if($country_code == "VIET NAM" || $country_code == "VN" || $country_code == "VNM") return "VND"; 
    if($country_code == "VIRGIN ISLANDS, BRITISH" || $country_code == "VG" || $country_code == "VGB") return "USD"; 
    if($country_code == "VIRGIN ISLANDS, U.S." || $country_code == "VI" || $country_code == "VIR") return "USD"; 
    if($country_code == "WALLIS AND FUTUNA" || $country_code == "WF" || $country_code == "WLF") return "XPF"; 
    if($country_code == "WESTERN SAHARA (formerly Spanish Sahara)" || $country_code == "EH" || $country_code == "ESH") return "MAD"; 
    if($country_code == "YEMEN" || $country_code == "YE" || $country_code == "YEM") return "YER"; 

    if($country_code == "ZAMBIA" || $country_code == "ZM" || $country_code == "ZMB") return "ZMK"; 
    if($country_code == "ZIMBABWE" || $country_code == "ZW" || $country_code == "ZWE") return "SWD";
    
    return NULL;
}
	


function currency_0_1($value) {
	global $account;
	
	$tmp_string = $account['currency_0_iso3'] . "&nbsp;" . currency_format($value);
	
	if(($account['currency_translation'] != "Off")  && ($account['currency_code_1'])) {
		$tmp_string = $tmp_string . "&nbsp;<span style='font-weight:normal; font-size:smaller;'>(" . $account['currency_code_1'] . "&nbsp;" . currency_format(get_fx($account['currency_0_iso3'],$account['currency_code_1'],$value)) . ")</span>";
	}
	return $tmp_string;
}


function geo_data($data,$field,$output) {

	logger("FUNCTION: GEO_DATA()");
	logger3("data",$data);
	logger3("field",$field);
	logger3("output",$output);
	
	if( empty($data) || empty($field) || empty($output) ) return "";

	### EXAMPLE:
	##################################################################
	### geo_data($payme['ip_lookup']['iso2'],"iso2","currency_code");
	### geo_data($country_iso2,"iso2","printable_name");
	##################################################################
	### POSSIBLE FIELDS: 
	#	iso2 :: AF
	#	name :: AFGHANISTAN
	#	printable_name :: Afghanistan	
	#	alt1 :: NULL
	#	alt2 :: NULL
	#	alt3 :: NULL
	#	alt4 :: NULL
	#	alt5 :: NULL
	#	alt6 :: NULL
	#	alt7 :: NULL
	#	alt8 ::	NULL
	#	alt9 :: NULL
	#	alt10 :: NULL
	#	alt11 :: NULL
	#	alt12 :: NULL
	#	alt13 :: NULL
	#	alt14 :: NULL
	#	alt15 :: NULL
	#	alt16 :: NULL
	#	alt17 :: NULL
	#	alt18 :: NULL
	#	alt19 :: NULL
	#	alt20 :: NULL
	#	iso3 :: AFG
	#	numcode :: 4
	#	currency_code :: AFA
	#	currency_name :: Afghani
	#	currency_name_formal :: Afghanistan Afghani
	#	currency_symbol_unicode_decimal :: 1547
	#	currency_number :: 971
	### END
	
	if($field == "name") {
		$data = strtoupper($data);
		$tmp_sql = "SELECT * FROM geo_data WHERE name = '" . $data . "';";
		//test("tmp_sql",$tmp_sql);
		$tmp_results = readTHECASHIER($tmp_sql);
		//test("tmp_results",$tmp_results);
		$i = 1;
		### note:  $i = alt number... now only 20 alts in the database.
		while((!$tmp_results) && ($i <= "20")) {
		 	$tmp_results = readTHECASHIER("SELECT * FROM geo_data WHERE alt" . $i . " = '" . $data . "';");
		 	$i++;
		}
	
	} else {
		$tmp_sql = "SELECT * FROM geo_data WHERE " . $field . " = '" . $data . "';";
		logger3("tmp_sql",$tmp_sql);
		$tmp_results = readTHECASHIER($tmp_sql);
	}
	
	logger3("tmp_results",$tmp_results);
	
	if($output) {
		logger3("tmp_results->$output",$tmp_results->$output);
		#if($output == "currency_symbol_unicode_decimal") {
			#return "&#" . $tmp_results->$output . ";";
		#} else {
			return $tmp_results->$output;
		#}
	} else {
		return object2array($tmp_results);
	}
}


### HASH:  #####################################################################

function hash_me($encryption_type) {
	
	### NOTE:
	### MD5 = 32 chars  (DEFAULT)
	### SHA1 = 40 chars
	### SHA256 = 64 chars
	### SHA512 = 128 chars
	
	
	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random1 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random2 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random3 = rand();
	
	$final_seed = time() + $random1 + $random2 + $random3;
	
	if(!$encryption_type) {
		return md5($final_seed);
	} else {
		return hash($encryption_type,$final_seed);
	}
}


function make_hash($encryption_type) {
	
	### NOTE:
	### MD5 = 32 chars (DEFAULT)
	### SHA1 = 40 chars
	### SHA256 = 64 chars
	### SHA512 = 128 chars
	
	
	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random1 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random2 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random3 = rand();
	
	$final_seed = time() + $random1 + $random2 + $random3;
	
	if(!$encryption_type) {
		return md5($final_seed);
	} else {
		return hash($encryption_type,$final_seed);
	}
}



function hash_MD5($timestamp) {

	### NOTE: MD5 hash = 32 characters

	if(!$timestamp) $timestamp = null;
	
	list($usec, $sec) = explode(' ', microtime($timestamp));
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random1 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random2 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random3 = rand();
	
	return md5(time() + $random1 + $random2 + $random3);
}


function hash_SHA1() {

	### NOTE: SHA1 hash = 40 characters

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random1 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random2 = rand();

	list($usec, $sec) = explode(' ', microtime());
	$seed = srand((float) $sec + ((float) $usec * 100000));
	$random3 = rand();
	
	return hash("SHA1",time() + $random1 + $random2 + $random3);
}



function extract_hash() {

	global $REQUEST_URI;
	//test("REQUEST_URI",$REQUEST_URI);
	$tmp_uri = NULL;
	$tmp_uri = array();
	$tmp_uri = explode("/",$REQUEST_URI);
	$tmp_hash = explode("+",$tmp_uri[1]);
	if($tmp_hash[1]) {
		$variable['hash'] = $tmp_hash[1];
		$variable['emailaddress'] = $tmp_hash[0];
	} else {
		$variable['emailaddress'] = $tmp_uri[1];
	}
	
	return $variable;
}


function string2array($string,$myarray) {
	$lines = explode("\n",$string);
	foreach ($lines as $value) {
		$items = explode("&#183;",$value);
		if (sizeof($items) == 2) {
			$myarray[$items[0]] = $items[1];
		} else if (sizeof($items) == 3) {
			$myarray[$items[0]][$items[1]] = $items[2];
		}
	}
}


function validate_public_ip($ip) {
	if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) {
	  // it's valid
	  return TRUE;
	}
	else {
	  // it's not valid
	  return FALSE;
	}
}  


function validate_emailaddress($emailaddress) {
	
	$tmp_emailaddress = explode("@",$emailaddress);
  $tmp_emailaddress_2 = explode(".",$tmp_emailaddress[1]);
  if($tmp_emailaddress_2[1]) {
  	return TRUE;
  } else {
  	return FALSE;
  }
}


function source_deposit($transactionid) {
	
	# description: get the transaction details of the deposit (when you you only have the transactionid associated with the transfer / bonusid).
	
	$tmp_transaction = transaction($transactionid);
	
	//test("tmp_transaction",$tmp_transaction);
	
	
	$tmp_sql = "SELECT * FROM transactions WHERE description = 'Deposit' AND memberid = '" . $tmp_transaction['memberid'] . "' AND accountid LIKE '" . $tmp_transaction['accountid'] . "' AND  requested_datetime = '" . $tmp_transaction['requested_datetime'] . "';";
	
	
	//test("tmp_sql",$tmp_sql);
		
	$variable = object2array(readTHECASHIER($tmp_sql));
	//test("variable",$variable);
	
	
	if(empty($variable['transactionid'])) {
		
		//test("tmp_transaction['transactionid']",$tmp_transaction['transactionid']);
		$tmp_method_details = explode("][",$tmp_transaction['method_details']);
		//test("tmp_method_details",$tmp_method_details);
		
		$tmp_sql = "SELECT * FROM transactions WHERE description = 'Deposit' AND accountid LIKE '" . $tmp_method_details[1] . "' AND  requested_datetime = '" . $tmp_transaction['requested_datetime'] . "';";	
		//test("tmp_sql",$tmp_sql);
		$variable = object2array(readTHECASHIER($tmp_sql));
		//test("variable",$variable);
	}
	

	if(empty($variable['transactionid'])) {
		
		//test("tmp_transaction['transactionid']",$tmp_transaction['transactionid']);
		$tmp_method_details = explode("][",$tmp_transaction['method_details']);
		//test("tmp_method_details",$tmp_method_details);
		
		$tmp_sql = "SELECT * FROM transactions WHERE description = 'Outgoing' AND accountid LIKE '" . $tmp_method_details[1] . "' AND  updated_datetime = '" . $tmp_transaction['updated_datetime'] . "';";	
		//test("tmp_sql",$tmp_sql);
		$variable = object2array(readTHECASHIER($tmp_sql));
		//test("variable",$variable);
		
		if(!empty($variable['authorization'])) {
			
			$tmp_sql = "SELECT * FROM transactions WHERE description = 'Deposit' AND accountid LIKE '" . $tmp_method_details[1] . "' AND  authorization = '" . $variable['authorization'] . "';";
			//test("tmp_sql",$tmp_sql);
			$variable = object2array(readTHECASHIER($tmp_sql));
			//test("variable",$variable);
			
		}
		
		
		
	}
	
	
	
	//test("variable",$variable);
	return $variable;
}

function get_the_three_transactions($transactionid) {
	
	## GET DEPOSIT
	$tmp_transaction['deposit'] = source_deposit($transactionid);
	logger3("GTTT(): tmp_transaction['deposit']",$tmp_transaction['deposit']);
	//$tmp_transaction['deposit'] = transaction($tmp_transaction['deposit']['transactionid']);
	
	## GET OUTGOING
	$tmp_sql = "SELECT * FROM transactions WHERE description = 'Outgoing' AND transaction_gross_value = '" . $tmp_transaction['deposit']['transaction_gross_value'] . "' AND accountid LIKE '" . $tmp_transaction['deposit']['accountid'] . "' AND  requested_datetime = '" . $tmp_transaction['deposit']['requested_datetime'] . "';";
	
	$tmp_transaction['outgoing'] = object2array(readTHECASHIER($tmp_sql));
	logger3("GTTT(): tmp_sql",$tmp_sql);
	logger3("GTTT(): tmp_transaction['outgoing']",$tmp_transaction['outgoing']);
	
	$tmp_associated_accountid = explode("][",$tmp_transaction['outgoing']['account_details']);
	$tmp_associated_accountid = $tmp_associated_accountid[1];
	
	## GET INCOMING
	$tmp_sql = "SELECT * FROM transactions WHERE description = 'Incoming' AND transaction_gross_value = '" . $tmp_transaction['deposit']['transaction_gross_value'] . "' AND accountid LIKE '" . $tmp_associated_accountid . "' AND  requested_datetime = '" . $tmp_transaction['deposit']['requested_datetime'] . "';";
	$tmp_transaction['incoming'] = object2array(readTHECASHIER($tmp_sql));
	logger3("GTTT(): tmp_sql",$tmp_sql);
	logger3("GTTT(): tmp_transaction['incoming']",$tmp_transaction['outgoing']);
	

	## GET TRANSLOG:
	$tmp_sql = "SELECT * FROM translog WHERE translogid = '". $tmp_transaction['deposit']['translogid'] . "';";
	$tmp_transaction['translog'] = object2array(readTHECASHIER($tmp_sql));
	logger3("GTTT(): tmp_sql",$tmp_sql);
	logger3("GTTT(): tmp_transaction['incoming']",$tmp_transaction['outgoing']);

	
	return $tmp_transaction;
	
}
	
	
function pretty_member_name($tmp_memberid) {
	
	$tmp_member = member($tmp_memberid);
	
	if($tmp_member['salutation']) {
		return $tmp_member['salutation'] . " " . $tmp_member['lastname'];
	} else {
		return $tmp_member['firstname'] . " " . $tmp_member['lastname'];
	}
}



function get_voice_signature($tmp_memberid) {
	global $template;
	
	$tmp_sql = "SELECT * FROM voiceprints WHERE memberid = '" . $tmp_memberid . "' AND description = 'Signature';";
	//logger3("tmp_sql",$tmp_sql);
	$tmp_voiceprint = object2array(readTHECASHIER($tmp_sql));
	$tmp_voicefileids = explode(",",$tmp_voiceprint['voicefileids']);
	foreach($tmp_voicefileids as $key => $value) {
		$tmp_sql = "SELECT filename FROM voicefiles WHERE voicefileid LIKE '" . $value . "';";
		$tmp_audio_file = getTHECASHIER($tmp_sql);
		if(file_exists($_SESSION['template']['company']['file_path'] . "authorizations/audio/" . $tmp_audio_file . "_converted.wav")) {
			$flash_audio_player_file_url = "https://" . $_SESSION['template']['company']['host_www'] . "/link_authorizations/audio/" . $tmp_audio_file . "_converted.wav";
			break;
		}
	}
	return $flash_audio_player_file_url;
}


function extract_permissions($permissionsid) {
	
	$tmp_permissions = object2array(readTHECASHIER("SELECT * FROM permissions WHERE permissionsid LIKE '" . $permissionsid . "';"));
	
	$tmp_permissions_exploded = explode(",",$tmp_permissions['permissions']);
	
	//test("tmp_permissions_exploded",$tmp_permissions_exploded);
	
	$tmp_permissions_extracted['view_balance'] = "NO";
	$tmp_permissions_extracted['view_history'] = "NO";
	$tmp_permissions_extracted['view_details'] = "NO";
	$tmp_permissions_extracted['manage_details'] = "NO";
	$tmp_permissions_extracted['make_payments'] = "NO";
	$tmp_permissions_extracted['make_deposits'] = "NO";
	$tmp_permissions_extracted['make_transfers'] = "NO";
	$tmp_permissions_extracted['make_withdrawals'] = "NO";
	$tmp_permissions_extracted['manage_settings'] = "NO";
	$tmp_permissions_extracted['manage_permissions'] = "NO";
	$tmp_permissions_extracted['manage_identity'] = "NO";
	$tmp_permissions_extracted['manage_payment_requests'] = "NO";
	foreach($tmp_permissions_exploded as $key => $value) {
		//test("value",$value);
		if($value == "view_balance") $tmp_permissions_extracted['view_balance'] = "YES";
		if($value == "view_history") $tmp_permissions_extracted['view_history'] = "YES";
		if($value == "view_details") $tmp_permissions_extracted['view_details'] = "YES";
		if($value == "manage_details") $tmp_permissions_extracted['manage_details'] = "YES";
		if($value == "make_payments") $tmp_permissions_extracted['make_payments'] = "YES";
		if($value == "make_deposits") $tmp_permissions_extracted['make_deposits'] = "YES";
		if($value == "make_transfers") $tmp_permissions_extracted['make_transfers'] = "YES";
		if($value == "make_withdrawals") $tmp_permissions_extracted['make_withdrawals'] = "YES";
		if($value == "manage_settings") $tmp_permissions_extracted['manage_settings'] = "YES";
		if($value == "manage_permissions") $tmp_permissions_extracted['manage_permissions'] = "YES";
		if($value == "manage_identity") $tmp_permissions_extracted['manage_identity'] = "YES";
		if($value == "send_payment_requests") $tmp_permissions_extracted['send_payment_requests'] = "YES";
	}
	
	
	### MISC:
	if($tmp_permissions['login_biometric_verification'] == "OFF") {
		$tmp_permissions_extracted['login_biometric_verification'] = "OFF";
	} else {
		$tmp_permissions_extracted['login_biometric_verification'] = "ON";
	}

	
	return $tmp_permissions_extracted;
}




function transaction_limit($memberid) {
	
	global $master_config_basic_limits_per_member_per_transaction; // = "500.00";
	global $master_config_basic_limits_per_member_per_month; // = "1000.00";

	//LAST 18 HOURS
	$last_18_hours = date("Y-m-d H:i:s",strtotime("-18 hours"));
	$tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
			WHERE memberid = '". $memberid ."'
			AND description = 'DEPOSIT'
			AND (status = 'APPROVED' OR status = 'COMPLETED')
			AND requested_datetime > '". $last_18_hours ."'
			;";
	//test("tmp_sql",$tmp_sql);
	$results['last_18_hours_sum'] = getTHECASHIER($tmp_sql);
	//test("results['last_18_hours_sum']",$results['last_18_hours_sum']);
	//exit;
	
	//LAST 30 days
	$last_30_days = date("Y-m-d H:i:s",strtotime("-30 days"));
	$tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
			WHERE memberid = '". $memberid ."'
			AND description = 'DEPOSIT'
			AND (status = 'APPROVED' OR status = 'COMPLETED')
			AND requested_datetime > '". $last_30_days ."'
			;";
	$results['last_30_days_sum'] = getTHECASHIER($tmp_sql);

	return $results;
}


function current_full_url() {
 	
 	$pageURL = 'http';
 	
 	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 		$pageURL .= "://";
 	
 	if ($_SERVER["SERVER_PORT"] != "80") {
  		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 	} else {
  		$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 	}
 	
 	return $pageURL;
}

function display_name() {
	
	global $member;
	
	//test("tmp_memberid",$tmp_memberid);

	if($member['memberid']) {
	
		if($member['salutation']) {
			$tmp_display_name = $member['salutation'] . " " . $member['lastname'];
		} else {
			$tmp_display_name = $member['firstname'];
		}
	} else {
		$tmp_display_name = ":)";
	}
	
	return $tmp_display_name;
}


function generatePassword($length) {

	// start with a blank password
	$password = "";
	
	// define possible characters - any character in this string can be
	// picked for use in the password, so if you want to put vowels back in
	// or add special characters such as exclamation marks, this is where
	// you should do it
	$possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ";
	
	// we refer to the length of $possible a few times, so let's grab it now
	$maxlength = strlen($possible);
	
	// check for length overflow and truncate if necessary
	if ($length > $maxlength) {
		$length = $maxlength;
	}
	
	// set up a counter for how many characters are in the password so far
	$i = 0; 
	
	// add random characters to $password until $length is reached
	while ($i < $length) { 
	
		// pick a random character from the possible ones
		$char = substr($possible, mt_rand(0, $maxlength-1), 1);
		  
		// have we already used this character in $password?
		if (!strstr($password, $char)) { 
			// no, so it's OK to add it onto the end of whatever we've already got...
			$password .= $char;
			// ... and increase the counter by one
			$i++;
		}
	
	}
	
	// done!
	return $password;
}

function gen_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}


## function maxmind($ip_address) {
## //note: does not work� requuires ocuntry, too.  not a lookup� but� a confirmation.
## 	logger3("maxmind()",$ip_address);
## 
## 	/// SET KURL PARAMETERS
## 	$maxmind_parameters = "";
## 	$maxmind_parameters .= "i=" . $ip_address;
## 	//$maxmind_parameters .= "&city=" . $_SESSION['transaction']['maxmind']['city'];
## 	//$maxmind_parameters .= "&region=" . $_SESSION['transaction']['maxmind']['region'];
## 	//$maxmind_parameters .= "&postal=" . $_SESSION['transaction']['maxmind']['post_code'];
## 	//$maxmind_parameters .= "&country=" . $_SESSION['transaction']['maxmind']['country_iso2'];
## 	$maxmind_parameters .= "&license_key=TuG3uxB3yvj4";
## 	$maxmind_parameters .= "&requested_type=premium";
## 	//$maxmind_parameters .= "&txn_type=creditcard";
## 	//$maxmind_parameters .= "&bin=" . $_SESSION['transaction']['maxmind']['credit_card']['bin']; // first six digits of credit card
## 	
## 	/// KURL IT:
## 	$maxmind_url = "https://minfraud2.maxmind.com/app/ccv2r";
## 	$maxmind_results = processorCURLER($maxmind_url,$maxmind_parameters); // save results to session?
## 	logger3("maxmind_parameters",$maxmind_parameters);
## 	logger3("maxmind_results",$maxmind_results);
## 	
## 	//$tmp_maxmind_results = $_SESSION['transaction']['maxmind']['results'];
## 	//test("tmp_maxmind_results",$tmp_maxmind_results);
## 	
## 	
## 	$maxmind_results_exploded = explode(";",$maxmind_results);
## 	//test("tmp_exploded_results",$tmp_maxmind_results_exploded);
## 	
## 	foreach($maxmind_results_exploded as $key => $value) {
## 		//test("key",$key);
## 		//test("value",$value);
## 		$tmp_explosion = explode("=",$maxmind_results_exploded[$key]);
## 		if($key == 0) {
## 			$distance_explosion = explode("distance=",$tmp_explosion[1]);
## 			$input_transaction['maxmind']['distance'] = $distance_explosion[1];
## 		} else {
## 			 $maxmind[$tmp_explosion[0]] = $tmp_explosion[1];
## 		}
## 	}
## 	
## 	return $maxmind;
## 
## }


function maxmind($creditcard_bin,$customer_ip,$billing_city,$billing_region,$billing_postal_code,$billing_country,$customer_telephone) {

	logger3("maxmind(): creditcard_bin",$creditcard_bin);
	logger3("maxmind(): customer_ip",$customer_ip);
	logger3("maxmind(): billing_city",$billing_city);
	logger3("maxmind(): billing_region",$billing_region);
	logger3("maxmind(): billing_postal_code",$billing_postal_code);
	logger3("maxmind(): billing_country",$billing_country);
	logger3("maxmind(): customer_telephone",$customer_telephone);


	//USERID: 55335
	$maxmind_url = "https://minfraud2.maxmind.com/app/ccv2r";
	$maxmind_license_key = "TuG3uxB3yvj4";
	$maxmind_requested_type = "premium";
	$maxmind_txn_type = "creditcard";
	
	### PARAMETERS:
	$parameters = "";
	$parameters .= "i=" . $customer_ip;
	$parameters .= "&city=" . $billing_city;
	$parameters .= "&region=" . $billing_region;
	$parameters .= "&postal=" . $billing_postal_code;
	$parameters .= "&country=" . $billing_country;
	$parameters .= "&custPhone=" . $customer_telephone;
	
	$parameters .= "&license_key=" . $maxmind_license_key;
	$parameters .= "&requested_type=" . $maxmind_requested_type;
	$parameters .= "&txn_type=" . $maxmind_txn_type;
	$parameters .= "&bin=" . $creditcard_bin;
	
	$_SESSION['maxmind']['results'] = processorCURLER($maxmind_url,$parameters);
	$_SESSION['maxmind']['url'] = $maxmind_url;
	$_SESSION['maxmind']['parameters'] = $parameters;
	
	
	//$maxmind_exploded = explode(";",$_SESSION['maxmind']['results']);
	//logger3("maxmind_exploded",$maxmind_exploded);
	
	
	
	### NEW METHOD:
	$maxmind_first_explosion = explode("distance=",$_SESSION['maxmind']['results']);
	logger3("maxmind_first_explosion",$maxmind_first_explosion);
	
	$maxmind_exploded = explode(";",$maxmind_first_explosion[1]);
	logger3("maxmind_exploded",$maxmind_exploded);
	
	
	$maxmind_country_match = explode("=",$maxmind_exploded[1]);
	$_SESSION['maxmind']['country_match'] = $maxmind_country_match[1];
	
	$maxmind_customer_country = explode("=",$maxmind_exploded[2]);
	$_SESSION['maxmind']['customer_country'] = $maxmind_customer_country[1];
	
	logger3("maxmind_exploded[2]",$maxmind_exploded[2]);
	logger3("maxmind(SET): maxmind_customer_country[1]",$maxmind_customer_country[1]);
	logger3("maxmind(SET): _SESSION['maxmind']['customer_country']",$_SESSION['maxmind']['customer_country']);
	
	$maxmind_bin_country = explode("=",$maxmind_exploded[6]);
	$_SESSION['maxmind']['bin_country'] = $maxmind_bin_country[1];
	
	logger3("maxmind(SET): maxmind_exploded[6]",$maxmind_exploded[6]);
	logger3("maxmind(SET): maxmind_bin_country[1]",$maxmind_bin_country[1]);
	logger3("maxmind(SET): _SESSION['maxmind']['bin_country']",$_SESSION['maxmind']['bin_country']);
	
	$maxmind_bin_name = explode("=",$maxmind_exploded[13]);
	$_SESSION['maxmind']['bin_name'] = $maxmind_bin_name[1];

	$maxmind_bin_phone = explode("=",$maxmind_exploded[18]);
	$_SESSION['maxmind']['bin_phone'] = $maxmind_bin_phone[1];

	$maxmind_riskscore = explode("=",$maxmind_exploded[42]);
	$_SESSION['maxmind']['riskscore'] = $maxmind_riskscore[1];
	
	logger3("maxmind() _SESSION['maxmind']",$_SESSION['maxmind']);

	return $_SESSION['maxmind'];
}

function session_last_page() {

	$number_of_keys = array_keys($_SESSION['session']['session_history']) - 1;
	//test("number_of_keys",$number_of_keys);
	return $_SESSION['session']['session_history'][$number_of_keys];

}


function display_processing($display_message,$full_html_headers='',$spinner_placement='') {
	
//echo "BBBB";

	if(empty($full_html_headers)) $full_html_headers = "yes";
	
	if(empty($spinner_placement)) $spinner_placement = "inline";
	
	if(!isset($display_message)) {
		$generic_processing_message = "<span style='color:#444444; font-family:verdana,arial; font-size:26px;'>Processing Secured Data...";
	} else {
		$generic_processing_message = "<span style='color:#444444; font-family:verdana,arial; font-size:24px;'>" . $display_message;
	}
	
	//echo "CCCC";
	
	include($_SESSION['template']['company']['file_path'] . "shared/generic_processing_visual.shared");
	//echo "DDDD";
	
	//echo "<textarea>$generic_processing_visual_api</textarea>";
	
	echo $generic_processing_visual_api;
	
	//echo "EEEE";
	
}

function currency_symbol($currency_iso3) {

	if(!isset($currency_iso3)) $currency_iso3 = $_SESSION['template']['company']['currency1'];
	$tmp_unicode = geo_data($currency_iso3,"currency_code","currency_symbol_unicode_decimal");
	$tmp_unicode_exploded = explode(",",$tmp_unicode);
	if($tmp_unicode_exploded[1]) {
		
		$i = 0;
		unset($tmp_currency_symbol);
		while($tmp_unicode_exploded[$i]) {
			$tmp_currency_symbol .= "&#" . trim($tmp_unicode_exploded[$i]) . ";";
			$i += 1;
		}
		
	
	} else {
		//test("1",$n);
		$tmp_currency_symbol = "&#" . trim($tmp_unicode) . ";";
	}
	return $tmp_currency_symbol;
}

function array_unshift_assoc($arr, $key, $val) 
{ 
    $arr = array_reverse($arr, true); 
    $arr[$key] = $val; 
    $arr = array_reverse($arr, true); 
    return $arr;
} 

function get_user_browser()
{
    $u_agent = $_SERVER['HTTP_USER_AGENT'];
    $ub = '';
    if(preg_match('/MSIE/i',$u_agent))
    {
        $ub = "ie";
    }
    elseif(preg_match('/Firefox/i',$u_agent))
    {
        $ub = "firefox";
    }
    elseif(preg_match('/Safari/i',$u_agent))
    {
        $ub = "safari";
    }
    elseif(preg_match('/Chrome/i',$u_agent))
    {
        $ub = "chrome";
    }
    elseif(preg_match('/Flock/i',$u_agent))
    {
        $ub = "flock";
    }
    elseif(preg_match('/Opera/i',$u_agent))
    {
        $ub = "opera";
    }

    return $ub;
}

function check_email_smtp($email_address_to_verify)
{
	require_once ("email_verify.shared");
	//return validateEmail($email, true, true, 'support@nsdb.com', 'nsdb.com', true);
	$tmp_reply = validateEmail($email_address_to_verify, $domainCheck = true, $verify = true, $probe_address='support@nsdb.com', $helo_address='nsdb.com', $return_errors=true);
	
	if($tmp_reply == false) {
		return "VALID";
	} else {
		logger3("tmp_reply",$tmp_reply);
		return "INVALID";
	}
	
}

function parse_url_domain($url,$subdomain=TRUE) {
	
$raw_url= parse_url($url);
	if ($raw_url['host'] == '') {
// Fix for non-returning SERVER Variables -> use path info instead
$raw_url['host'] = $raw_url['path'];
}
// debug : print_r($raw_url);
// Check for presence of "www" part in the URL... if so, remove it!
	if( preg_match("/^www\./i", $raw_url['host'])) {
$www = true;
} else { $www = false;  }
	if ($www==false) {
$domain_only[1] = $raw_url['host'];
} else {
// cleanup the www part
preg_match ("/\.([^\/]+)/", $raw_url['host'] , $domain_only);
}
/// Subdomain Cleanup : If user entered that it's present, let's remove it... 
//  else, leave it alone, domain already ready
	if ($subdomain == true) {
preg_match ("/\.([^\/]+)/", $domain_only[1] , $domain_only);
}
// debug: print_r($domain_only);
/// Output : Case  lowered, only domain + tld shown
	return strtolower($domain_only[1]);
}

function getUrlParts($url) {
	$result = array();
	
	// Get the protocol, site and resource parts of the URL
	// original url = http://example.com/blog/index?name=foo
	// protocol = http://
	// site = example.com/
	// resource = blog/index?name=foo
	$regex = '#^(.*?//)*([\w\.\d]*)(:(\d+))*(/*)(.*)$#';
	$matches = array();
	preg_match($regex, $url, $matches);
			
	// Assign the matched parts of url to the result array
	$result['protocol'] = $matches[1];
	$result['port'] = $matches[4];
	$result['site'] = $matches[2];
	$result['resource'] = $matches[6];
	
	// clean up the site portion by removing the trailing /
	$result['site'] = preg_replace('#/$#', '', $result['site']);
	
	// clean up the protocol portion by removing the trailing ://
	$result['protocol'] = preg_replace('#://$#', '', $result['protocol']);
	
	return $result;
}


# function 
# 
# ($event,$month,$day,$year) {
#     // subtract desired date from current date and give an answer in terms of days
#     $remain = ceil( ( mktime( 0,0,0,$month,$day,$year ) - time() ) / 86400 );
#     // show the number of days left
#     
#     return $remain;
# /*
#     if( $remain > 0 )
#     {
#         print "<p><strong>$remain</strong> more sleeps until $event</p>";
#     }
#     // if the event has arrived, say so!
#     else
#     {
#         print "<p>$event has arrived!</p>";
#     }
# */
# }


function display_available_balance() {

$tmp_output = "
	<style>
	.available_balance {
		text-decoration:none;
		font-family:verdana;
		font-size:11px;
		font-weight:bold;
		color:#4F1F7A;
	}
	
	.available_balance A {
		text-decoration:none;
		font-family:verdana;
		font-size:11px;
		font-weight:bold;
		color:#4F1F7A;
	}
	
	.available_balance A:HOVER {
		text-decoration:underline;
		font-family:verdana;
		font-size:11px;
		font-weight:bold;
		color:#4F1F7A;
	}
	
	.TABLE_X_ROW_title_td_3 {
		/*width:auto;
		height:auto;*/
		background-color:transparent;
		
		border-spacing:0;
		border-width:0;
		border-collapse:collapse;
		border-style:none;
		border-color:transparent;	
	
		padding-top:0px;
		padding-bottom:0px;
		padding-left:0px;
		padding-right:0px;
		
		margin-left:0px;
		margin-right:0px;
		margin-top:0px;
		margin-bottom:0px;
		
		font-family:verdana,arial,helvetica,sans-serif;
		font-size:10px;
		font-weight:bold;
		color:#888888;
		/*vertical-align:bottom;
		text-align:right;*/	
	}
	
	
	</style>
	
	
	<table style='margin-left:auto; margin-top:auto; border-width:0px; border-color:#FF0000; border-style:solid;'>
	
		<tr>
			<td style='border-width:0px; border-color:#51B54E; border-top-style:solid;
	border-right-style:none; border-bottom-style:solid; border-left-style:solid;'>
						<span class='account_balance'>
							<nobr>&nbsp;
								<a href='javascript:openSUPPORT(59);'>" . display_image('popup.png',$vertical_align) . "&nbsp;AVAILABLE Balance</a>:
							</nobr>
						</span>
			</td>
			<td style='border-width:0px; border-color:#51B54E; border-top-style:solid;
	border-right-style:none; border-bottom-style:solid; border-left-style:none;'>
				<nobr>
					<span class='available_translation'>&nbsp;&nbsp;(" . $_SESSION['account']['currency_code_1'] . "&nbsp;" . currency_format(get_fx($_SESSION['template']['company']['currency1'], $_SESSION['account']['currency_code_1'], $_SESSION['balance']['balance']['available']),",") . ")&nbsp;&nbsp;
					</span>
				</nobr>
			</td>
			<td style='border-width:0px; border-color:#51B54E; border-top-style:solid;
	border-right-style:solid; border-bottom-style:solid; border-left-style:none;'>";
	
	
	if(multicurrency()) {
		$tmp_output .= "
		
				<nobr>
					<span class='account_balance_total'>
						" . $_SESSION['template']['company']['currency1'] . "&nbsp;" . currency_format($_SESSION['balance']['balance']['available'],",") . "
				   	</span>
				</nobr>";
	}
	
	$tmp_output .= "
			</td>
		</tr>
	</table>";
	
	return $tmp_output;
}

function multicurrency() {
	
	//global $template;
	
	if( 
	($_SESSION['template']['company']['currency1'] == $_SESSION['account']['currency_code_1']) || 
	($_SESSION['account']['currency_code_1'] == "") || 
	($_SESSION['account']['currency_code_1'] == NULL) || 
	($_SESSION['account']['currency_code_1'] == " ") ||
	(!stristr($_SESSION['account']['currency_translation'],"ON"))
	) {
		return FALSE;
	} else {
		return TRUE;
	}
}


function ascii2binary_too($character) {
	//test("character",$character);
	if($character == '<NUL>') return '00000000'; 
	if($character == '<SOH>') return '00000001'; 
	if($character == '<STX>') return '00000010'; 
	if($character == '<ETX>') return '00000011'; 
	if($character == '<EOT>') return '00000100'; 
	if($character == '<ENQ>') return '00000101'; 
	if($character == '<ACK>') return '00000110'; 
	if($character == '<BEL>') return '00000111'; 
	if($character == '<BS>') return '00001000'; 
	if($character == '<HT>') return '00001001'; 
	if($character == '<LF>') return '00001010'; 
	if($character == '<VT>') return '00001011'; 
	if($character == '<FF>') return '00001100'; 
	if($character == '<CR>') return '00001101'; 
	if($character == '<SO>') return '00001110'; 
	if($character == '<SI>') return '00001111'; 
	if($character == '<DLE>') return '00010000'; 
	if($character == '<DC1>') return '00010001'; 
	if($character == '<DC2>') return '00010010'; 
	if($character == '<DC3>') return '00010011'; 
	if($character == '<DC4>') return '00010100'; 
	if($character == '<NAK>') return '00010101'; 
	if($character == '<SYN>') return '00010110'; 
	if($character == '<ETB>') return '00010111'; 
	if($character == '<CAN>') return '00011000'; 
	if($character == '<EM>') return '00011001'; 
	if($character == '<SUB>') return '00011010'; 
	if($character == '<ESC>') return '00011011'; 
	if($character == '<FS>') return '00011100'; 
	if($character == '<GS>') return '00011101'; 
	if($character == '<RS>') return '00011110'; 
	if($character == '<US>') return '00011111'; 
	if($character == '<SPACE>') return '00100000';
	if($character == ' ') return '00100000';
	if($character == '!') return '00100001'; 
	if($character == '"') return '00100010'; 
	if($character == '#') return '00100011'; 
	if($character == '$') return '00100100'; 
	if($character == '%') return '00100101'; 
	if($character == '&') return '00100110'; 
	if($character == '\'') return '00100111'; 
	if($character == '(') return '00101000'; 
	if($character == ')') return '00101001'; 
	if($character == '*') return '00101010'; 
	if($character == '+') return '00101011'; 
	if($character == ',') return '00101100'; 
	if($character == '-') return '00101101'; 
	if($character == '.') return '00101110'; 
	if($character == '/') return '00101111'; 
	if($character == '0') return '00110000'; 
	if($character == '1') return '00110001'; 
	if($character == '2') return '00110010'; 
	if($character == '3') return '00110011'; 
	if($character == '4') return '00110100'; 
	if($character == '5') return '00110101'; 
	if($character == '6') return '00110110'; 
	if($character == '7') return '00110111'; 
	if($character == '8') return '00111000'; 
	if($character == '9') return '00111001'; 
	if($character == ':') return '00111010'; 
	if($character == ';') return '00111011'; 
	if($character == '<') return '00111100'; 
	if($character == '=') return '00111101'; 
	if($character == '>') return '00111110'; 
	if($character == '?') return '00111111'; 
	if($character == '@') return '01000000'; 
	if($character == 'A') return '01000001'; 
	if($character == 'B') return '01000010'; 
	if($character == 'C') return '01000011'; 
	if($character == 'D') return '01000100'; 
	if($character == 'E') return '01000101'; 
	if($character == 'F') return '01000110'; 
	if($character == 'G') return '01000111'; 
	if($character == 'H') return '01001000'; 
	if($character == 'I') return '01001001'; 
	if($character == 'J') return '01001010'; 
	if($character == 'K') return '01001011'; 
	if($character == 'L') return '01001100'; 
	if($character == 'M') return '01001101'; 
	if($character == 'N') return '01001110'; 
	if($character == 'O') return '01001111'; 
	if($character == 'P') return '01010000'; 
	if($character == 'Q') return '01010001'; 
	if($character == 'R') return '01010010'; 
	if($character == 'S') return '01010011'; 
	if($character == 'T') return '01010100'; 
	if($character == 'U') return '01010101'; 
	if($character == 'V') return '01010110'; 
	if($character == 'W') return '01010111'; 
	if($character == 'X') return '01011000'; 
	if($character == 'Y') return '01011001'; 
	if($character == 'Z') return '01011010'; 
	if($character == '[') return '01011011'; 
	if($character == '\\') return '01011100'; 
	if($character == ']') return '01011101'; 
	if($character == '^') return '01011110'; 
	if($character == '_') return '01011111'; 
	if($character == '`') return '01100000'; 
	if($character == 'a') return '01100001'; 
	if($character == 'b') return '01100010'; 
	if($character == 'c') return '01100011'; 
	if($character == 'd') return '01100100'; 
	if($character == 'e') return '01100101'; 
	if($character == 'f') return '01100110'; 
	if($character == 'g') return '01100111'; 
	if($character == 'h') return '01101000'; 
	if($character == 'i') return '01101001'; 
	if($character == 'j') return '01101010'; 
	if($character == 'k') return '01101011'; 
	if($character == 'l') return '01101100'; 
	if($character == 'm') return '01101101'; 
	if($character == 'n') return '01101110'; 
	if($character == 'o') return '01101111'; 
	if($character == 'p') return '01110000'; 
	if($character == 'q') return '01110001'; 
	if($character == 'r') return '01110010'; 
	if($character == 's') return '01110011'; 
	if($character == 't') return '01110100'; 
	if($character == 'u') return '01110101'; 
	if($character == 'v') return '01110110'; 
	if($character == 'w') return '01110111'; 
	if($character == 'x') return '01111000'; 
	if($character == 'y') return '01111001'; 
	if($character == 'z') return '01111010'; 
	if($character == '{') return '01111011'; 
	if($character == '|') return '01111100'; 
	if($character == '}') return '01111101'; 
	if($character == '~') return '01111110'; 
	if($character == '<DEL>') return '01111111'; 
	return FALSE;
}


function ascii2binary($character) {
	//test("character",$character);
	if($character == 'NUL') return '00000000'; 
	if($character == 'SOH') return '00000001'; 
	if($character == 'STX') return '00000010'; 
	if($character == 'ETX') return '00000011'; 
	if($character == 'EOT') return '00000100'; 
	if($character == 'ENQ') return '00000101'; 
	if($character == 'ACK') return '00000110'; 
	if($character == 'BEL') return '00000111'; 
	if($character == 'BS') return '00001000'; 
	if($character == 'HT') return '00001001'; 
	if($character == 'LF') return '00001010'; 
	if($character == 'VT') return '00001011'; 
	if($character == 'FF') return '00001100'; 
	if($character == 'CR') return '00001101'; 
	if($character == 'SO') return '00001110'; 
	if($character == 'SI') return '00001111'; 
	if($character == 'DLE') return '00010000'; 
	if($character == 'DC1') return '00010001'; 
	if($character == 'DC2') return '00010010'; 
	if($character == 'DC3') return '00010011'; 
	if($character == 'DC4') return '00010100'; 
	if($character == 'NAK') return '00010101'; 
	if($character == 'SYN') return '00010110'; 
	if($character == 'ETB') return '00010111'; 
	if($character == 'CAN') return '00011000'; 
	if($character == 'EM') return '00011001'; 
	if($character == 'SUB') return '00011010'; 
	if($character == 'ESC') return '00011011'; 
	if($character == 'FS') return '00011100'; 
	if($character == 'GS') return '00011101'; 
	if($character == 'RS') return '00011110'; 
	if($character == 'US') return '00011111'; 
	if($character == 'SPACE') return '00100000';
	if($character == ' ') return '00100000';
	if($character == '!') return '00100001'; 
	if($character == '"') return '00100010'; 
	if($character == '#') return '00100011'; 
	if($character == '$') return '00100100'; 
	if($character == '%') return '00100101'; 
	if($character == '&') return '00100110'; 
	if($character == '\'') return '00100111'; 
	if($character == '(') return '00101000'; 
	if($character == ')') return '00101001'; 
	if($character == '*') return '00101010'; 
	if($character == '+') return '00101011'; 
	if($character == ',') return '00101100'; 
	if($character == '-') return '00101101'; 
	if($character == '.') return '00101110'; 
	if($character == '/') return '00101111'; 
	if($character == '0') return '00110000'; 
	if($character == '1') return '00110001'; 
	if($character == '2') return '00110010'; 
	if($character == '3') return '00110011'; 
	if($character == '4') return '00110100'; 
	if($character == '5') return '00110101'; 
	if($character == '6') return '00110110'; 
	if($character == '7') return '00110111'; 
	if($character == '8') return '00111000'; 
	if($character == '9') return '00111001'; 
	if($character == ':') return '00111010'; 
	if($character == ';') return '00111011'; 
	if($character == '<') return '00111100'; 
	if($character == '=') return '00111101'; 
	if($character == '>') return '00111110'; 
	if($character == '?') return '00111111'; 
	if($character == '@') return '01000000'; 
	if($character == 'A') return '01000001'; 
	if($character == 'B') return '01000010'; 
	if($character == 'C') return '01000011'; 
	if($character == 'D') return '01000100'; 
	if($character == 'E') return '01000101'; 
	if($character == 'F') return '01000110'; 
	if($character == 'G') return '01000111'; 
	if($character == 'H') return '01001000'; 
	if($character == 'I') return '01001001'; 
	if($character == 'J') return '01001010'; 
	if($character == 'K') return '01001011'; 
	if($character == 'L') return '01001100'; 
	if($character == 'M') return '01001101'; 
	if($character == 'N') return '01001110'; 
	if($character == 'O') return '01001111'; 
	if($character == 'P') return '01010000'; 
	if($character == 'Q') return '01010001'; 
	if($character == 'R') return '01010010'; 
	if($character == 'S') return '01010011'; 
	if($character == 'T') return '01010100'; 
	if($character == 'U') return '01010101'; 
	if($character == 'V') return '01010110'; 
	if($character == 'W') return '01010111'; 
	if($character == 'X') return '01011000'; 
	if($character == 'Y') return '01011001'; 
	if($character == 'Z') return '01011010'; 
	if($character == '[') return '01011011'; 
	if($character == '\\') return '01011100'; 
	if($character == ']') return '01011101'; 
	if($character == '^') return '01011110'; 
	if($character == '_') return '01011111'; 
	if($character == '`') return '01100000'; 
	if($character == 'a') return '01100001'; 
	if($character == 'b') return '01100010'; 
	if($character == 'c') return '01100011'; 
	if($character == 'd') return '01100100'; 
	if($character == 'e') return '01100101'; 
	if($character == 'f') return '01100110'; 
	if($character == 'g') return '01100111'; 
	if($character == 'h') return '01101000'; 
	if($character == 'i') return '01101001'; 
	if($character == 'j') return '01101010'; 
	if($character == 'k') return '01101011'; 
	if($character == 'l') return '01101100'; 
	if($character == 'm') return '01101101'; 
	if($character == 'n') return '01101110'; 
	if($character == 'o') return '01101111'; 
	if($character == 'p') return '01110000'; 
	if($character == 'q') return '01110001'; 
	if($character == 'r') return '01110010'; 
	if($character == 's') return '01110011'; 
	if($character == 't') return '01110100'; 
	if($character == 'u') return '01110101'; 
	if($character == 'v') return '01110110'; 
	if($character == 'w') return '01110111'; 
	if($character == 'x') return '01111000'; 
	if($character == 'y') return '01111001'; 
	if($character == 'z') return '01111010'; 
	if($character == '{') return '01111011'; 
	if($character == '|') return '01111100'; 
	if($character == '}') return '01111101'; 
	if($character == '~') return '01111110'; 
	if($character == 'DEL') return '01111111'; 
	return FALSE;
}

# function add_binaries($x,$y) {
# 	
# 	test("x",$x);
# 	test("y",$y);
# 	$z = 110001^101010;
# 	test("z",$z);
# 	return $z;
# }

function add_binaries($text,$key){
    for($i=0; $i<strlen($text); $i++){
        $text[$i] = intval($text[$i])^intval($key[$i]);
    }
    return $text;
}





function binary2hex($binary) {
	if($binary == '00000000') return '0x00';
	if($binary == '00000001') return '0x01';
	if($binary == '00000010') return '0x02';
	if($binary == '00000011') return '0x03';
	if($binary == '00000100') return '0x04';
	if($binary == '00000101') return '0x05';
	if($binary == '00000110') return '0x06';
	if($binary == '00000111') return '0x07';
	if($binary == '00001000') return '0x08';
	if($binary == '00001001') return '0x09';
	if($binary == '00001010') return '0x0A';
	if($binary == '00001011') return '0x0B';
	if($binary == '00001100') return '0x0C';
	if($binary == '00001101') return '0x0D';
	if($binary == '00001110') return '0x0E';
	if($binary == '00001111') return '0x0F';
	if($binary == '00010000') return '0x10';
	if($binary == '00010001') return '0x11';
	if($binary == '00010010') return '0x12';
	if($binary == '00010011') return '0x13';
	if($binary == '00010100') return '0x14';
	if($binary == '00010101') return '0x15';
	if($binary == '00010110') return '0x16';
	if($binary == '00010111') return '0x17';
	if($binary == '00011000') return '0x18';
	if($binary == '00011001') return '0x19';
	if($binary == '00011010') return '0x1A';
	if($binary == '00011011') return '0x1B';
	if($binary == '00011100') return '0x1C';
	if($binary == '00011101') return '0x1D';
	if($binary == '00011110') return '0x1E';
	if($binary == '00011111') return '0x1F';
	if($binary == '00100000') return '0x20';
	if($binary == '00100001') return '0x21';
	if($binary == '00100010') return '0x22';
	if($binary == '00100011') return '0x23';
	if($binary == '00100100') return '0x24';
	if($binary == '00100101') return '0x25';
	if($binary == '00100110') return '0x26';
	if($binary == '00100111') return '0x27';
	if($binary == '00101000') return '0x28';
	if($binary == '00101001') return '0x29';
	if($binary == '00101010') return '0x2A';
	if($binary == '00101011') return '0x2B';
	if($binary == '00101100') return '0x2C';
	if($binary == '00101101') return '0x2D';
	if($binary == '00101110') return '0x2E';
	if($binary == '00101111') return '0x2F';
	if($binary == '00110000') return '0x30';
	if($binary == '00110001') return '0x31';
	if($binary == '00110010') return '0x32';
	if($binary == '00110011') return '0x33';
	if($binary == '00110100') return '0x34';
	if($binary == '00110101') return '0x35';
	if($binary == '00110110') return '0x36';
	if($binary == '00110111') return '0x37';
	if($binary == '00111000') return '0x38';
	if($binary == '00111001') return '0x39';
	if($binary == '00111010') return '0x3A';
	if($binary == '00111011') return '0x3B';
	if($binary == '00111100') return '0x3C';
	if($binary == '00111101') return '0x3D';
	if($binary == '00111110') return '0x3E';
	if($binary == '00111111') return '0x3F';
	if($binary == '01000000') return '0x40';
	if($binary == '01000001') return '0x41';
	if($binary == '01000010') return '0x42';
	if($binary == '01000011') return '0x43';
	if($binary == '01000100') return '0x44';
	if($binary == '01000101') return '0x45';
	if($binary == '01000110') return '0x46';
	if($binary == '01000111') return '0x47';
	if($binary == '01001000') return '0x48';
	if($binary == '01001001') return '0x49';
	if($binary == '01001010') return '0x4A';
	if($binary == '01001011') return '0x4B';
	if($binary == '01001100') return '0x4C';
	if($binary == '01001101') return '0x4D';
	if($binary == '01001110') return '0x4E';
	if($binary == '01001111') return '0x4F';
	if($binary == '01010000') return '0x50';
	if($binary == '01010001') return '0x51';
	if($binary == '01010010') return '0x52';
	if($binary == '01010011') return '0x53';
	if($binary == '01010100') return '0x54';
	if($binary == '01010101') return '0x55';
	if($binary == '01010110') return '0x56';
	if($binary == '01010111') return '0x57';
	if($binary == '01011000') return '0x58';
	if($binary == '01011001') return '0x59';
	if($binary == '01011010') return '0x5A';
	if($binary == '01011011') return '0x5B';
	if($binary == '01011100') return '0x5C';
	if($binary == '01011101') return '0x5D';
	if($binary == '01011110') return '0x5E';
	if($binary == '01011111') return '0x5F';
	if($binary == '01100000') return '0x60';
	if($binary == '01100001') return '0x61';
	if($binary == '01100010') return '0x62';
	if($binary == '01100011') return '0x63';
	if($binary == '01100100') return '0x64';
	if($binary == '01100101') return '0x65';
	if($binary == '01100110') return '0x66';
	if($binary == '01100111') return '0x67';
	if($binary == '01101000') return '0x68';
	if($binary == '01101001') return '0x69';
	if($binary == '01101010') return '0x6A';
	if($binary == '01101011') return '0x6B';
	if($binary == '01101100') return '0x6C';
	if($binary == '01101101') return '0x6D';
	if($binary == '01101110') return '0x6E';
	if($binary == '01101111') return '0x6F';
	if($binary == '01110000') return '0x70';
	if($binary == '01110001') return '0x71';
	if($binary == '01110010') return '0x72';
	if($binary == '01110011') return '0x73';
	if($binary == '01110100') return '0x74';
	if($binary == '01110101') return '0x75';
	if($binary == '01110110') return '0x76';
	if($binary == '01110111') return '0x77';
	if($binary == '01111000') return '0x78';
	if($binary == '01111001') return '0x79';
	if($binary == '01111010') return '0x7A';
	if($binary == '01111011') return '0x7B';
	if($binary == '01111100') return '0x7C';
	if($binary == '01111101') return '0x7D';
	if($binary == '01111110') return '0x7E';
	if($binary == '01111111') return '0x7F';
}



function binary2hex_too($binary) {
	if($binary == '00000000') return 0x00;
	if($binary == '00000001') return 0x01;
	if($binary == '00000010') return 0x02;
	if($binary == '00000011') return 0x03;
	if($binary == '00000100') return 0x04;
	if($binary == '00000101') return 0x05;
	if($binary == '00000110') return 0x06;
	if($binary == '00000111') return 0x07;
	if($binary == '00001000') return 0x08;
	if($binary == '00001001') return 0x09;
	if($binary == '00001010') return 0x0A;
	if($binary == '00001011') return 0x0B;
	if($binary == '00001100') return 0x0C;
	if($binary == '00001101') return 0x0D;
	if($binary == '00001110') return 0x0E;
	if($binary == '00001111') return 0x0F;
	if($binary == '00010000') return 0x10;
	if($binary == '00010001') return 0x11;
	if($binary == '00010010') return 0x12;
	if($binary == '00010011') return 0x13;
	if($binary == '00010100') return 0x14;
	if($binary == '00010101') return 0x15;
	if($binary == '00010110') return 0x16;
	if($binary == '00010111') return 0x17;
	if($binary == '00011000') return 0x18;
	if($binary == '00011001') return 0x19;
	if($binary == '00011010') return 0x1A;
	if($binary == '00011011') return 0x1B;
	if($binary == '00011100') return 0x1C;
	if($binary == '00011101') return 0x1D;
	if($binary == '00011110') return 0x1E;
	if($binary == '00011111') return 0x1F;
	if($binary == '00100000') return 0x20;
	if($binary == '00100001') return 0x21;
	if($binary == '00100010') return 0x22;
	if($binary == '00100011') return 0x23;
	if($binary == '00100100') return 0x24;
	if($binary == '00100101') return 0x25;
	if($binary == '00100110') return 0x26;
	if($binary == '00100111') return 0x27;
	if($binary == '00101000') return 0x28;
	if($binary == '00101001') return 0x29;
	if($binary == '00101010') return 0x2A;
	if($binary == '00101011') return 0x2B;
	if($binary == '00101100') return 0x2C;
	if($binary == '00101101') return 0x2D;
	if($binary == '00101110') return 0x2E;
	if($binary == '00101111') return 0x2F;
	if($binary == '00110000') return 0x30;
	if($binary == '00110001') return 0x31;
	if($binary == '00110010') return 0x32;
	if($binary == '00110011') return 0x33;
	if($binary == '00110100') return 0x34;
	if($binary == '00110101') return 0x35;
	if($binary == '00110110') return 0x36;
	if($binary == '00110111') return 0x37;
	if($binary == '00111000') return 0x38;
	if($binary == '00111001') return 0x39;
	if($binary == '00111010') return 0x3A;
	if($binary == '00111011') return 0x3B;
	if($binary == '00111100') return 0x3C;
	if($binary == '00111101') return 0x3D;
	if($binary == '00111110') return 0x3E;
	if($binary == '00111111') return 0x3F;
	if($binary == '01000000') return 0x40;
	if($binary == '01000001') return 0x41;
	if($binary == '01000010') return 0x42;
	if($binary == '01000011') return 0x43;
	if($binary == '01000100') return 0x44;
	if($binary == '01000101') return 0x45;
	if($binary == '01000110') return 0x46;
	if($binary == '01000111') return 0x47;
	if($binary == '01001000') return 0x48;
	if($binary == '01001001') return 0x49;
	if($binary == '01001010') return 0x4A;
	if($binary == '01001011') return 0x4B;
	if($binary == '01001100') return 0x4C;
	if($binary == '01001101') return 0x4D;
	if($binary == '01001110') return 0x4E;
	if($binary == '01001111') return 0x4F;
	if($binary == '01010000') return 0x50;
	if($binary == '01010001') return 0x51;
	if($binary == '01010010') return 0x52;
	if($binary == '01010011') return 0x53;
	if($binary == '01010100') return 0x54;
	if($binary == '01010101') return 0x55;
	if($binary == '01010110') return 0x56;
	if($binary == '01010111') return 0x57;
	if($binary == '01011000') return 0x58;
	if($binary == '01011001') return 0x59;
	if($binary == '01011010') return 0x5A;
	if($binary == '01011011') return 0x5B;
	if($binary == '01011100') return 0x5C;
	if($binary == '01011101') return 0x5D;
	if($binary == '01011110') return 0x5E;
	if($binary == '01011111') return 0x5F;
	if($binary == '01100000') return 0x60;
	if($binary == '01100001') return 0x61;
	if($binary == '01100010') return 0x62;
	if($binary == '01100011') return 0x63;
	if($binary == '01100100') return 0x64;
	if($binary == '01100101') return 0x65;
	if($binary == '01100110') return 0x66;
	if($binary == '01100111') return 0x67;
	if($binary == '01101000') return 0x68;
	if($binary == '01101001') return 0x69;
	if($binary == '01101010') return 0x6A;
	if($binary == '01101011') return 0x6B;
	if($binary == '01101100') return 0x6C;
	if($binary == '01101101') return 0x6D;
	if($binary == '01101110') return 0x6E;
	if($binary == '01101111') return 0x6F;
	if($binary == '01110000') return 0x70;
	if($binary == '01110001') return 0x71;
	if($binary == '01110010') return 0x72;
	if($binary == '01110011') return 0x73;
	if($binary == '01110100') return 0x74;
	if($binary == '01110101') return 0x75;
	if($binary == '01110110') return 0x76;
	if($binary == '01110111') return 0x77;
	if($binary == '01111000') return 0x78;
	if($binary == '01111001') return 0x79;
	if($binary == '01111010') return 0x7A;
	if($binary == '01111011') return 0x7B;
	if($binary == '01111100') return 0x7C;
	if($binary == '01111101') return 0x7D;
	if($binary == '01111110') return 0x7E;
	if($binary == '01111111') return 0x7F;
}


function char2hex_too($char) {
	//$char = "9";
	//$char = "<STX>";
	//test("0. tmp_string",$char);
	$char = ascii2binary_too($char);
	//test("1. tmp_string",$char);
	$char = binary2hex_too($char);
	//test("2. tmp_string",$char);
	$char = pack("C*",$char);
	//test("3. tmp_string",$char);
	return $char;
}

function char2hex($char) {
	//$char = "9";
	//$char = "STX";
	//test("0. tmp_string",$char);
	$char = ascii2binary($char);
	//test("1. tmp_string",$char);
	$char = binary2hex_too($char);
	//test("2. tmp_string",$char);
	$char = pack("C*",$char);
	//test("3. tmp_string",$char);
	return $char;
}

function make_LRC($payload) {
	
	$string = $payload;

	
	//$string = "<STX>*1NS11022009001234566#00010827842588454143<FS>@01<FS>";
	//$string = "<STX>*1N<FS>A<FS>";
	
	$exploded_string = explode(char2hex_too("<STX>"),$string);
	//$exploded_string = explode(pack("C*",0x1C),$string);
	//$exploded_string = ;
	$string_array = str_split($exploded_string[1]);
	
	
	### GET THE FIRST TWO:
	$first = ascii2binary($string_array[0]);
	logger3("first",$first);
	$second = ascii2binary($string_array[1]);
	logger3("second",$second);
	$binary_sum = add_binaries($first,$second);
	logger3("binary_sum",$binary_sum);
	
	### GET TEH REST:
	
	$z = count($string_array)-2;
	logger3("z",$z);
	$a = 2;
	while($z > 0) {
		logger3("string_array[$a]",$string_array[$a]);
		if($string_array[$a] == "<") {
			
			if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] == "<FS>") {
				$a = $a + 4;
				$z = $z - 4;
				$binary_to_add = ascii2binary("FS");
			
			} else if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] == "<US>") {
				$a = $a + 4;
				$z = $z - 4;
				$binary_to_add = ascii2binary("US");
			
			} else if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] . $string_array[$a+4] == "<ETX>") {
				$a = $a + 5;
				$z = $z - 5;
				$binary_to_add = ascii2binary("ETX");
			
			} else if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] . $string_array[$a+4] . $string_array[$a+5] . $string_array[$a+6] . $string_array[$a+7] == "<SPACE>") {
				$a = $a + 7;
				$z = $z - 7;
				$binary_to_add = ascii2binary("SPACE");
			}
			
		} else {
			$binary_to_add = ascii2binary($string_array[$a]);
			$a = $a + 1;
			$z = $z - 1;
		}
		
		
		$x = $binary_sum;
		logger3("binary_sum: x",$x);
		
		$y = $binary_to_add;
		logger3("binary_to_add: y",$y);
		
		$binary_sum = add_binaries($x,$y);
		logger3("binary_sum",$binary_sum);
	}
	
	test("FINAL: binary_sum",$binary_sum);
	
	//$hex = bin2hex($binary_sum);
	//logger3("hex",$hex);
	
	//$ascii = char($binary_sum);
	$results['hex'] = pack("C*",binary2hex_too($binary_sum));
	//logger3"hex",$hex);
	//return $hex;
	
	$results['ascii'] = $results['asc'] = binary2ascii($binary_sum);
	
	logger3("results",$results);
	
	return $results;

}


function make_LRC_2($payload,$stop_key=0) {
	
	$string = $payload;

	// set "$stop_key" to 0 to LRC the full string.
	// set "$stop_key" to 1 to skip the LAST value on the string (i.e., the incoming LRC value).
	
	//$string = "<STX>*1NS11022009001234566#00010827842588454143<FS>@01<FS>";
	//$string = "<STX>*1N<FS>A<FS>";
	
	//$exploded_string = explode(char2hex_too("<STX>"),$string);
	$exploded_string = explode(pack("C*",0x02),$string);
	
	//$exploded_string = ;
	$string_array = str_split($exploded_string[1]);
	
	
	### GET THE FIRST TWO:
	$first = ascii2binary($string_array[0]);
	logger3("first",$first);
	$second = ascii2binary($string_array[1]);
	logger3("second",$second);
	$binary_sum = add_binaries($first,$second);
	logger3("binary_sum",$binary_sum);
	
	### GET TEH REST:
	
	$z = count($string_array)-2;
	logger3("z",$z);
	$a = 2;
	while($z > $stop_key) {
		logger3("string_array[$a]",$string_array[$a]);
		
		if($string_array[$a] == pack("C*",0x1C)) {
			//test($a . "FS",$x);
			$binary_to_add = ascii2binary("FS");
		
		} else if($string_array[$a] == pack("C*",0x1F)) {
			$binary_to_add = ascii2binary("US");
		
		} else if($string_array[$a] == pack("C*",0x03)) {
			$binary_to_add = ascii2binary("ETX");
		
		} else if($string_array[$a] == pack("C*",0x20)) {
			$binary_to_add = ascii2binary("SPACE");
			
		} else {
			$binary_to_add = ascii2binary($string_array[$a]);
		}
		
		$a = $a + 1;
		$z = $z - 1;
			
		$x = $binary_sum;
		logger3("binary_sum: x",$x);
		
		$y = $binary_to_add;
		logger3("binary_to_add: y",$y);
		
		$binary_sum = add_binaries($x,$y);
		test("binary_sum",$binary_sum);
	}
	
	test("FINAL: binary_sum",$binary_sum);
	
	//$hex = bin2hex($binary_sum);
	//logger3("hex",$hex);
	
	//$ascii = char($binary_sum);
	$results['hex'] = pack("C*",binary2hex_too($binary_sum));
	//logger3"hex",$hex);
	//return $hex;
	
	$results['ascii'] = $results['asc'] = binary2ascii($binary_sum);
	
	logger3("results",$results);
	
	return $results;

}



function binary2ascii($binary) {
	if($binary == '00000000') return '<NUL>';
	if($binary == '00000001') return '<SOH>';
	if($binary == '00000010') return '<STX>';
	if($binary == '00000011') return '<ETX>';
	if($binary == '00000100') return '<EOT>';
	if($binary == '00000101') return '<ENQ>';
	if($binary == '00000110') return '<ACK>';
	if($binary == '00000111') return '<BEL>';
	if($binary == '00001000') return '<BS>';
	if($binary == '00001001') return '<HT>';
	if($binary == '00001010') return '<LF>';
	if($binary == '00001011') return '<VT>';
	if($binary == '00001100') return '<FF>';
	if($binary == '00001101') return '<CR>';
	if($binary == '00001110') return '<SO>';
	if($binary == '00001111') return '<SI>';
	if($binary == '00010000') return '<DLE>';
	if($binary == '00010001') return '<DC1>';
	if($binary == '00010010') return '<DC2>';
	if($binary == '00010011') return '<DC3>';
	if($binary == '00010100') return '<DC4>';
	if($binary == '00010101') return '<NAK>';
	if($binary == '00010110') return '<SYN>';
	if($binary == '00010111') return '<ETB>';
	if($binary == '00011000') return '<CAN>';
	if($binary == '00011001') return '<EM>';
	if($binary == '00011010') return '<SUB';
	if($binary == '00011011') return '<ESC>';
	if($binary == '00011100') return '<FS>';
	if($binary == '00011101') return '<GS>';
	if($binary == '00011110') return '<RS>';
	if($binary == '00011111') return '<US>';
	if($binary == '00100000') return '<SPACE>';
	if($binary == '00100001') return '!';
	if($binary == '00100010') return '"';
	if($binary == '00100011') return '#';
	if($binary == '00100100') return '$';
	if($binary == '00100101') return '%';
	if($binary == '00100110') return '&';
	if($binary == '00100111') return '\'';
	if($binary == '00101000') return '(';
	if($binary == '00101001') return ')';
	if($binary == '00101010') return '*';
	if($binary == '00101011') return '+';
	if($binary == '00101100') return ',';
	if($binary == '00101101') return '-';
	if($binary == '00101110') return '.';
	if($binary == '00101111') return '/';
	if($binary == '00110000') return '0';
	if($binary == '00110001') return '1';
	if($binary == '00110010') return '2';
	if($binary == '00110011') return '3';
	if($binary == '00110100') return '4';
	if($binary == '00110101') return '5';
	if($binary == '00110110') return '6';
	if($binary == '00110111') return '7';
	if($binary == '00111000') return '8';
	if($binary == '00111001') return '9';
	if($binary == '00111010') return ':';
	if($binary == '00111011') return ';';
	if($binary == '00111100') return '<';
	if($binary == '00111101') return '=';
	if($binary == '00111110') return '>';
	if($binary == '00111111') return '?';
	if($binary == '01000000') return '@';
	if($binary == '01000001') return 'A';
	if($binary == '01000010') return 'B';
	if($binary == '01000011') return 'C';
	if($binary == '01000100') return 'D';
	if($binary == '01000101') return 'E';
	if($binary == '01000110') return 'F';
	if($binary == '01000111') return 'G';
	if($binary == '01001000') return 'H';
	if($binary == '01001001') return 'I';
	if($binary == '01001010') return 'J';
	if($binary == '01001011') return 'K';
	if($binary == '01001100') return 'L';
	if($binary == '01001101') return 'M';
	if($binary == '01001110') return 'N';
	if($binary == '01001111') return 'O';
	if($binary == '01010000') return 'P';
	if($binary == '01010001') return 'Q';
	if($binary == '01010010') return 'R';
	if($binary == '01010011') return 'S';
	if($binary == '01010100') return 'T';
	if($binary == '01010101') return 'U';
	if($binary == '01010110') return 'V';
	if($binary == '01010111') return 'W';
	if($binary == '01011000') return 'X';
	if($binary == '01011001') return 'Y';
	if($binary == '01011010') return 'Z';
	if($binary == '01011011') return '[';
	if($binary == '01011100') return '\\';
	if($binary == '01011101') return ']';
	if($binary == '01011110') return '^';
	if($binary == '01011111') return '_';
	if($binary == '01100000') return '`';
	if($binary == '01100001') return 'a';
	if($binary == '01100010') return 'b';
	if($binary == '01100011') return 'c';
	if($binary == '01100100') return 'd';
	if($binary == '01100101') return 'e';
	if($binary == '01100110') return 'f';
	if($binary == '01100111') return 'g';
	if($binary == '01101000') return 'h';
	if($binary == '01101001') return 'i';
	if($binary == '01101010') return 'j';
	if($binary == '01101011') return 'k';
	if($binary == '01101100') return 'l';
	if($binary == '01101101') return 'm';
	if($binary == '01101110') return 'n';
	if($binary == '01101111') return 'o';
	if($binary == '01110000') return 'p';
	if($binary == '01110001') return 'q';
	if($binary == '01110010') return 'r';
	if($binary == '01110011') return 's';
	if($binary == '01110100') return 't';
	if($binary == '01110101') return 'u';
	if($binary == '01110110') return 'v';
	if($binary == '01110111') return 'w';
	if($binary == '01111000') return 'x';
	if($binary == '01111001') return 'y';
	if($binary == '01111010') return 'z';
	if($binary == '01111011') return '{';
	if($binary == '01111100') return '|';
	if($binary == '01111101') return '}';
	if($binary == '01111110') return '~';
	if($binary == '01111111') return '<DEL>';
}

function avs_address_extractor($address=NULL) {
	if(!$address) {
		$address = $SESSION['account']['streetaddress1'] . $SESSION['account']['streetaddress1'];
	}
	return preg_replace('/[^0-9.]+/', '', $address);
}

function avs_zip_extractor($zipcode=NULL) {
	if(!$zipcode) {
		$zipcode = $SESSION['account']['postalcode'];
	}
	return preg_replace('/[^0-9.]+/', '', $zipcode);
}

function numbers_only($string,$display_style=1) {
	if($display_style == 1) {
		return preg_replace('/[^0-9.]+/', '', $string);
	} else {
		return preg_replace("/[^0-9]/","", $string); 
	} 
}

function payload2hex($payload_string) {
	$tmp_replace = char2hex_too("<STX>");
	$payload_string = str_replace("<STX>", $tmp_replace, $payload_string);
	//$results['hex'] = pack("C*",binary2hex($binary_sum));
	
	$tmp_replace = char2hex_too("<ETX>");
	$payload_string = str_replace("<ETX>", $tmp_replace, $payload_string);
	
	$tmp_replace = char2hex_too("<FS>");
	$payload_string = str_replace("<FS>", $tmp_replace, $payload_string);
	
	$tmp_replace = char2hex_too("<US>");
	$payload_string = str_replace("<US>", $tmp_replace, $payload_string);
	
	$tmp_replace = char2hex_too("<SPACE>");
	$payload_string = str_replace(" ", $tmp_replace, $payload_string);

	return $payload_string;
}



function payload_packer($payload) {
	
	//$string = $payload;

	//$string = "<STX>*1NS11022009001234566#00010827842588454143<FS>@01<FS>";
	//$string = "<STX>*1N<FS>A<FS>";
	
	//$exploded_string = explode("<STX>",$payload);
	$string_array = str_split($payload);
	
	
	### GET THE FIRST TWO:
	//$first = ascii2binary($string_array[0]);
	//logger3("first",$first);
	//$second = ascii2binary($string_array[1]);
	//logger3("second",$second);
	//$binary_sum = add_binaries($first,$second);
	//logger3("binary_sum",$binary_sum);
	
	### GET TEH REST:
	
	$z = count($string_array);
	logger3("z",$z);
	$a =0;
	while($z > 0) {
		logger3("string_array[$a]",$string_array[$a]);
		if($string_array[$a] == "<") {
			
			if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] == "<FS>") {
				$a = $a + 4;
				$z = $z - 4;
				$binary_to_add = ascii2binary("FS");
			} else if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] == "<US>") {
				$a = $a + 4;
				$z = $z - 4;
				$binary_to_add = ascii2binary("US");
			} else if($string_array[$a] . $string_array[$a+1] . $string_array[$a+2] . $string_array[$a+3] . $string_array[$a+4] == "<ETX>") {
				$a = $a + 5;
				$z = $z - 5;
				$binary_to_add = ascii2binary("ETX");
			
			}
		} else {
			$binary_to_add = ascii2binary($string_array[$a]);
			$a = $a + 1;
			$z = $z - 1;
		}
		
		
		$x = $binary_sum;
		logger3("binary_sum: x",$x);
		
		$y = $binary_to_add;
		logger3("binary_to_add: y",$y);
		
		$binary_sum = add_binaries($x,$y);
		logger3("binary_sum",$binary_sum);
	}
	
	logger3("FINAL: binary_sum",$binary_sum);
	
	//$hex = bin2hex($binary_sum);
	//logger3("hex",$hex);
	
	//$ascii = char($binary_sum);
	$results['hex'] = binary2hex($binary_sum);
	//logger3"hex",$hex);
	//return $hex;
	
	$results['ascii'] = $results['asc'] = binary2ascii($binary_sum);
	
	logger3("results",$results);
	
	return $results;

}

function asc2bin($in)#syntax - asc2bin("text to convert");
{
 $out = '';
 for ($i = 0, $len = strlen($in); $i < $len; $i++)
 {
$out .= sprintf("%08b",ord($in{$i}));
 }
 return $out;
}


function bin2asc($in)#syntax - bin2asc("binary to convert");
{
 $out = '';
 for ($i = 0, $len = strlen($in); $i < $len; $i += 8)
 {
$out .= chr(bindec(substr($in,$i,8)));
 }
 return $out; 
}


function firstdataGetNewBatchNumber() {

	$tmp_sql = "SELECT batch_number FROM FIRSTDATA_COUNTERS;";
	//logger3("tmp_sql",$tmp_sql);
	$tmp_current_batch_number = number_format(getTHECASHIER($tmp_sql));
	//test("tmp_current_batch_number",$tmp_current_batch_number);
	
	if(
	($tmp_current_batch_number == "9")
	) {
	  $new_batch_number = "0";
	} else {
	  $new_batch_number = $tmp_current_batch_number + "1";
	}
	
	//$new_batch_number = $tmp_current_batch_number + 1;
	//test("new_batch_number",$new_batch_number);
	$tmp_sql = "UPDATE FIRSTDATA_COUNTERS SET batch_number = '" . $new_batch_number . "';";
	//logger3("tmp_sql",$tmp_sql);
	$update_result = updateTHECASHIER($tmp_sql);
	//test("update_result",$update_result);
	//test("new_batch_number",$new_batch_number);
	
	### SET BATCH_HASH
	$_SESSION['BATCH_HASH'] = hash_me();
	
	return $new_batch_number;	
}

function firstdataGetCurrentClientRefTransactionID_ORIGINAL_DB() {

	$tmp_sql = "SELECT clientref_transactionid FROM FIRSTDATA_COUNTERS;";
	//logger3("tmp_sql",$tmp_sql);
	$tmp_current_clientref_transactionid = number_format(getTHECASHIER($tmp_sql));
	//test("tmp_current_clientref_transactionid",$tmp_current_clientref_transactionid);
	return $tmp_current_clientref_transactionid;	
	
}

function firstdataGetNewClientRefTransactionID_ORIGINAL_DB() {

	$tmp_sql = "SELECT clientref_transactionid FROM FIRSTDATA_COUNTERS;";
	//logger3("tmp_sql",$tmp_sql);
	$tmp_current_clientref_transactionid = number_format(getTHECASHIER($tmp_sql));
	//test("tmp_current_clientref_transactionid",$tmp_current_clientref_transactionid);
 
	if(
	($tmp_current_clientref_transactionid == "9999999") 
	) {
		$new_clientref_transactionid = "1";
	} else {
		$new_clientref_transactionid = $tmp_current_clientref_transactionid + "1";
	}
	
	//$new_clientref_transactionid = $tmp_current_clientref_transactionid + 1;
	//test("new_clientref_transactionid",$new_clientref_transactionid);
	$tmp_sql = "UPDATE FIRSTDATA_COUNTERS SET clientref_transactionid = '" . $new_clientref_transactionid . "';";
	//logger3("tmp_sql",$tmp_sql);
	$update_result = updateTHECASHIER($tmp_sql);
	//test("update_result",$update_result);
	//test("new_clientref_transactionid",$new_clientref_transactionid);
	return $new_clientref_transactionid;	
	
}



function firstdataGetCurrentClientRefTransactionID() {
	
	$tmp_sql = "SELECT item_number FROM FIRSTDATA_TPSP_merchants WHERE 
		accountid = '" . $_SESSION['FIRSTDATA']['accountid'] . "' AND
		MID = '".$_SESSION['FIRSTDATA']['MID']."' AND
		DEVICE_ID = '".$_SESSION['FIRSTDATA']['DEVICE_ID']."';";
	
	$_SESSION['FIRSTDATA']['ITEM_NUMBER'] = getTHECASHIER($tmp_sql);
	
	logger3("tmp_sql",$tmp_sql);
	test("_SESSION['FIRSTDATA']['ITEM_NUMBER']",$_SESSION['FIRSTDATA']['ITEM_NUMBER']);

	return $_SESSION['FIRSTDATA']['ITEM_NUMBER'];	
	
}

function firstdataGetNewClientRefTransactionID() {

	//if($ITEM_NUMBER != NULL) $_SESSION['FIRSTDATA']['ITEM_NUMBER'] = $ITEM_NUMBER;
	
	if(
	(!$_SESSION['FIRSTDATA']['ITEM_NUMBER']) ||
	($_SESSION['FIRSTDATA']['ITEM_NUMBER'] == "999")
	) {
		$_SESSION['FIRSTDATA']['ITEM_NUMBER'] = "1";
	} else {
		$_SESSION['FIRSTDATA']['ITEM_NUMBER'] = $_SESSION['FIRSTDATA']['ITEM_NUMBER'] + "1";
	}

	$tmp_sql = "UPDATE FIRSTDATA_TPSP_merchants 
				SET item_number = '".$_SESSION['FIRSTDATA']['ITEM_NUMBER']."' WHERE 
				accountid = '" . $_SESSION['FIRSTDATA']['accountid'] . "' AND
				MID = '".$_SESSION['FIRSTDATA']['MID']."' AND
				DEVICE_ID = '".$_SESSION['FIRSTDATA']['DEVICE_ID']."';";
	$tmp_results = updateTHECASHIER($tmp_sql);

	logger3("tmp_sql",$tmp_sql);
	logger3("tmp_results",$tmp_results);
	logger3("_SESSION['FIRSTDATA']['ITEM_NUMBER']",$_SESSION['FIRSTDATA']['ITEM_NUMBER']);
	
	return $_SESSION['FIRSTDATA']['ITEM_NUMBER'];
	
}



function firstdataAddNewMerchant($accountid,$MID,$DEVICE_ID,$DATAWIRE_ID,$datetime=NULL) {

	//test("MID",$MID);
	
	//$tmp_merchant_exists = firstdataGetMerchantDID($accountid);

	//test("tmp_merchant_exists",$tmp_merchant_exists);
	
	//if($tmp_merchant_exists = FALSE) {

		//$tmp_sql = "UPDATE FIRSTDATA_TPSP_merchants SET 
		//$member_note = "Member UN-Suspended: $note";
		if(!$datetime) $tmp_datetime = datetime();
		$tmp_sql = "INSERT INTO FIRSTDATA_TPSP_merchants 
		(`firstdataid`,
		`accountid`,
		`MID`,
		`DEVICE_ID`,
		`DATAWIRE_ID`,
		`datetime_created`,
		`datetime_updated`)
			
		VALUES
			
		('$blank_firstdataid',
		'$accountid',
		'$MID',
		'$DEVICE_ID',
		'$DATAWIRE_ID',
		'$tmp_datetime',
		'$tmp_datetime')";
		$insert_response = insertTHECASHIER($tmp_sql);
		return $insert_response;
	//} else {
	//	return NULL;
	//}
	
}

function firstdataGetMerchantDID($accountid,$DEVICE_ID,$MID=NULL) {
	//if(!$accountid) $accountid = $_SESSION['account']['accountid'];
	
	if(
	($MID != NULL) &&
	($DEVICE_ID) && 
	($accountid)
	) {
		$tmp_sql = "SELECT * FROM FIRSTDATA_TPSP_merchants WHERE 
			MID = '" . $MID . "' AND
			accountid = '" . $accountid . "' AND 
			DEVICE_ID = '".$DEVICE_ID."';";
	
	} else if($DEVICE_ID) {
		$tmp_sql = "SELECT * FROM FIRSTDATA_TPSP_merchants WHERE accountid LIKE '" . $accountid . "' AND DEVICE_ID = '".$DEVICE_ID."';";
	
	} else {
		$tmp_sql = "SELECT * FROM FIRSTDATA_TPSP_merchants WHERE accountid LIKE '" . $accountid . "';";
	}
	logger3("tmp_sql",$tmp_sql);
	$tmp_results = object2array(readTHECASHIER($tmp_sql));
	logger3("tmp_results",$tmp_results);
	if($tmp_results['DATAWIRE_ID']) {
		return $tmp_results;
	} else {
		return NULL;
	}

}


function display_LOAD($display_account_disposit_LOAD,$transaction_details) {

	if(
	($display_account_disposit_LOAD == TRUE) ||
	(!stristr($transaction_details->description,"DEPOSIT"))
	) {
		//test("display_account_disposit_LOAD",$display_account_disposit_LOAD);
		//test("transaction_details",$transaction_details);
		return TRUE;
	} else {
		return FALSE;
	}
}


function random_char($desired_random_string_length) {
	return strtoupper(substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $desired_random_string_length)), 0, $desired_random_string_length));
}

function random_num($desired_random_string_length) {
	return strtoupper(substr(str_shuffle(str_repeat("0123456789", $desired_random_string_length)), 0, $desired_random_string_length));
}

function get_translog_FIRSTDATA($total_amount,$account_number,$transaction_code,$transaction_status="0") {

	if(trim($transaction_status) == "") $transaction_status = "0";

	$tmp_sql = "SELECT * FROM translog_FIRSTDATA WHERE
				TOTAL_AMOUNT = '".$total_amount."' AND
				TRANSACTION_CODE = '".$transaction_code."' AND
				ACCOUNT_NUMBER = '".$account_number."' AND
				RESPONSE_RESPONSE_CODE = '".$transaction_status."'
				ORDER BY datetime_created DESC LIMIT 1;";
	//logger3("tmp_sql",$tmp_sql);
	$results = object2array(readTHECASHIER($tmp_sql));
	//test("get_translog_FIRSTDATA(): results",$results);
	return $results;
}



function object_merge($object_1,$object_2) {
	foreach($object_2 as $key => $value) {
    	$object_1->$key = $value;
    }
    return $object_1;
}


function showSession() {
	//global $_GET['view'];
	$tmp_session = $_SESSION;
	if(!stristr($_GET['view'],"template")) $tmp_session['template'] = "<b>(NOTE: click <a href='".$_SERVER['SCRIPT_URL']."/?view=template'>".$_SERVER['SCRIPT_URL']."/?view=template</a> to view... template)</b>"; 
}




function system_level_user_maker($accountid=NULL) {

	global $master_config_auto_adduser_emailaccount_path_filename;
	
	//test("accountid",$accountid);
	
	// make sure there is an account id set.
	if(!empty($accountid)) {
	
		$tmp_account = account($accountid);
	
	} else if($_SESSION['account']['hash']) {
		
		$tmp_account = $_SESSION['account'];
	}
	
	
	
	// exit if there is nothing
	if(empty($tmp_account['hash'])) {
		return FALSE;
	}
	
	
	
	$tmp_account_name = $tmp_account['accountname'];
	$tmp_account_name = strtolower($tmp_account_name);
	
	$clean_account_name_full = preg_replace("/[^a-zA-Z0-9]+/", "", $tmp_account_name);
	//test("clean_account_name_full",$clean_account_name_full);
	
	$clean_account_name = substr($clean_account_name_full,0,32);
	
	$tmp_password = generate_random_password($length = 32);

	
	//test("tmp_password",$tmp_password);
	


	//exec("/BANGK\!/www/test/add_user.sh $clean_account_name $tmp_password");
	$ouput = exec("$master_config_auto_adduser_emailaccount_path_filename $clean_account_name $tmp_password");
	if(
	($ouput != TRUE) &&
	($ouput != 1)
	) {
		return FALSE;
	} // otherwise, continue....

	$tmp_datetime = datetime();

	$tmp_sql = "INSERT into email_accounts
	(
	`email_account_id`,
	`accountid`,
	`account_hash`,
	`username`,
	`password`,
	`status`,
	`datetime_created`,
	`datetime_updated`
	) VALUES (
	'".$email_account_id=NULL."',
	'".$tmp_account['accountid']."',
	'".$tmp_account['hash']."',
	'".$clean_account_name."',
	'".$tmp_password."',
	'ACTIVE',
	'".$tmp_datetime."',
	'".$tmp_datetime."'
	);";
	
	logger3("tmp_sql",$tmp_sql);
	$results = insertTHECASHIER($tmp_sql);
	//test("results",$results);
	


	### CREATE ACCOUNT
	/// UPDATE DB
	mysql_pconnect("localhost","root","bangk!20120710");
	mysql_select_db("roundcubemail");
	
		
	### FIRST: ### INSERT USERS:
	
	// $tmp_sql = "UPDATE users SET
	// mail_host = 'bangk.net',
	// preferences = '$tmp_preferences'
	// WHERE username = '".$emailaccount_username."';";
	
	$tmp_username = $clean_account_name;
	$tmp_mailhost = "localhost";
	$tmp_language = "en_US";

	$tmp_preferences = addslashes('a:4:{s:9:"junk_mbox";s:4:"SPAM";s:15:"default_folders";a:5:{i:0;s:5:"INBOX";i:1;s:6:"Drafts";i:2;s:4:"Sent";i:3;s:4:"SPAM";i:4;s:5:"Trash";}s:14:"draft_autosave";i:60;s:10:"reply_mode";i:1;}');

	$tmp_sql = "INSERT INTO `users`
	(`user_id`, 
	`username`, 
	`mail_host`, 
	`created`, 
	`last_login`, 
	`language`, 
	`preferences`
	) VALUES (
	'".$_blank_user_id."',
	'".$tmp_username."',
	'".$tmp_mailhost."',
	'".$_blank_created."',
	'".$_blank_last_login."',
	'".$tmp_language."',
	'".$tmp_preferences."'
	);";
	
	$emailaccount_user_id = mysql_query($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("emailaccount_user_id",$emailaccount_user_id);
	
### SECOND: ### INSERT IDENTITIES:
	$tmp_changed = datetime();
	$tmp_del = "0";
	$tmp_standard = "1";
	$tmp_name = $_SESSION['account']['accountname'];
	$tmp_organization = "";
	$tmp_email = $clean_account_name."@bangk.net";
	$tmp_reply_to = $clean_account_name."@bangk.net";
	
	$tmp_sql = "INSERT INTO `identities`
	(
	`identity_id`, 
	`user_id`, 
	`changed`,
	 `del`, 
	 `standard`, 
	 `name`, 
	 `organization`, 
	 `email`, 
	 `reply-to`, 
	 `bcc`, 
	 `signature`, 
	 `html_signature`
	 ) VALUES (
	 '".$_BLANK_identity_id."',
	 '".$emailaccount_user_id."',
	 '".$tmp_changed."',
	 '".$tmp_del."',
	 '".$tmp_standard."',
	 '".$tmp_name."',
	 '".$tmp_organization."',
	 '".$tmp_email."',
	 '".$tmp_reply_to."',
	 '".$_BLANK_bcc."',
	 '".$_BLANK_signature."',
	 '".$_BLANK_html_signature."'
	 );";
	 
	 $emailaccount_identity_id = mysql_query($tmp_sql);
	 logger3("tmp_sql",$tmp_sql);
	 logger3("emailaccount_identity_id",$emailaccount_identity_id);
	
	 mysql_close();
	 ###
	 
	 return $clean_account_name;

}





### START: RANDOM PASSWORD ###
function putValueIntoDb() {
      /* This dummy function SHOULD store a single value in the database */
      return 0;
}
function getValueFromDb() {
      /* This dummy function SHOULD return the last value stored by putValueIntoDb() */
      return 42;
}
function crc64() {
      /* This dummy function SHOULD return the crc64 checksum of the input */
      return 1;
}


function generate_random_password($length) {
      $localsecret = '0e7G33Rvq9';
      $from_db = getValueFromDb();
      $charset = str_shuffle('ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789.');
      if(empty($length)) $length = 20;
      $charsetSize = strlen( $charset ) - 1;
      $preseed = md5(microtime())
              . getmypid()
              . md5(implode(getrusage()))
              . md5(implode(stat(__FILE__)))
              . memory_get_usage()
              . disk_free_space('.')
              . $localsecret
              . $from_db;

      /* Determine architecture */
      $i = 9223372036854775806;
      if (!is_int($i)) {
              /* 32-bit system */
              $seed = crc32($preseed);
      } else {
              /* 64-bit system */
              $seed = crc64($preseed);
      }

      mt_srand($seed);

      $password = '';
      foreach (range(1, $length) as $_)
      $password .= $charset{mt_rand(0, $charsetSize)};

      /* Save a large integer for next time the function is called */
      $save = mt_rand(0, (PHP_INT_MAX));
      putValueIntoDb($save);

      return $password;

}
### END: RANDOM PASSWORD ###




function business_line_extension_maker($accountid=null,$DID_to_check=null) {

    ### SET VARS:
    if($accountid) {
    	$tmp_account_details = account($accountid);
    } else if($_SESSION['account']['accountid']) {
	    $tmp_account_details = $_SESSION['account'];
    } else {
	    return FALSE;
    }
    if($DID_to_check==null) $DID_to_check = "61281034138"; // AUS base number
    if(!$DID_to_check) $DID_to_check = "61281034138"; // AUS base number
    

    
    $tmp_sql = "SELECT extension FROM business_lines WHERE DID_number = '".$DID_to_check."';";
    //logger3("tmp_sql",$tmp_sql);
    $extenion_array = arrayTHECASHIER($tmp_sql);
    //logger3("extenion_array",$extenion_array);
    
    
    ### LIMIT TO 10,000
    $number_of_extensions = count($extenion_array);
    if($number_of_extensions >= 10000) {
	    return FALSE;
    }
    
    if($number_of_extensions > 9000) {
    	//test("got to mailer",$number_of_extensions);
	  
	  global $master_config_admin_emailaddress;
	  
    	$to = $master_config_admin_emailaddress; // $master_config_accounting_emailaddress;
    	$subject = "SYSTEM ALERT! (DID EXTENSIONS RUNNING LOW: " . $number_of_extensions . " / 10,000)";
    	$message = "DID IN USE: +" . $DID_to_check . "<br>
    	<br>
    	NUMBERS OF EXTENSIONS REMAINING FOR THIS DID: " . (10000 - $number_of_extensions) . "<br>
    	<br>
    	";
	    quick_mailer($to,$subject,$message,$alert=null);
    }
    
    
    
    $from = 1000;
    $to = 9999;
    sort($extenion_array); // lets us use break; in the foreach reliably
    $new_extension_number = rand($from, $to - count($extenion_array)); // or mt_rand()
    foreach ($extenion_array as $exception) {
        if ($new_extension_number >= $exception) {
            $new_extension_number++; // make up for the gap
        } else /*if ($number < $exception)*/ {
            break;
        }
    }
    //return $number;

	### ADD TO DB:
	
	$tmp_sql = "INSERT INTO business_lines 
	(`business_line_id`,
	`accountid`,
	`account_hash`,
	`DID_number`,
	`extension`)
		
	VALUES
		
	('".$blank_business_line_id."',
	'".$tmp_account_details['accountid']."',
	'".$tmp_account_details['hash']."',
	'".$DID_to_check."',
	'".$new_extension_number."');
	";
	logger3("tmp_sql",$tmp_sql);
	
	$results = insertTHECASHIER($tmp_sql);
	logger3("results",$results);
	
	
	if($results == TRUE) {
		return $new_extension_number;
	} else {
		return FALSE;
	}
}


function get_business_lines($accountid) {
	
	$tmp_sql = "SELECT extension FROM business_lines WHERE accountid LIKE '". $accountid ."';";
	$extension = getTHECASHIER($tmp_sql);
	
	$business_lines['usa']['number'] = "1 646 655 0714";
	$business_lines['gbr']['number'] = "44 20 3608 7473";
	$business_lines['aus']['number'] = "61 2 8103 4138";
	$business_lines['extension'] = $extension;
	return $business_lines;
}


function get_email_account_details($accountid=null) {

	if(!$accountid) return FALSE;
	
	$tmp_sql = "SELECT * FROM email_accounts WHERE accountid LIKE '". $accountid ."';";
    logger3("tmp_sql",$tmp_sql);
    $email_account_details = object2array(readTHECASHIER($tmp_sql));
    //test("email_account_details",$email_account_details);
    return $email_account_details;
}


function process_refund(
$set_deposit_translogid=null,
$set_deposit_transactionid=null,
$set_reason_code=null,
$set_refund_reason=null,
$set_administrative_message=null,
$set_merchant_rating_action=null,
$set_processing_gateway_action=null
) {

	//global $_SESSION;

	logger3("000. set_deposit_translogid",$set_deposit_translogid);
	logger3("000. set_deposit_transactionid",$set_deposit_transactionid);
	logger3("000. set_reason_code",$set_reason_code);
	logger3("000. set_refund_reason",$set_refund_reason);
	logger3("000. set_administrative_message",$set_administrative_message);
	logger3("000. set_merchant_rating_action",$set_merchant_rating_action);
	logger3("000. set_processing_gateway_action",$set_processing_gateway_action);
	
	// if(stristr($set_reason_code,"CHARGEBACK")) $set_reason_code = "11";
	// if(stristr($set_reason_code,"CANCELED")) $set_reason_code = "12";
	// if(stristr($set_reason_code,"FRAUD")) $set_reason_code = "12";
	// if(stristr($set_reason_code,"REFUND")) $set_reason_code = "14";
	// if(stristr($set_reason_code,"REVERSED")) $set_reason_code = "15";
	

	if(
	(
	(empty($set_deposit_translogid)) &&
	(empty($set_deposit_transactionid))
	) ||
	(empty($set_reason_code))
	) {
		return "ERR: NOT ENOUGH PARAMETERS";
		//exit;
	} else {
		logger3("PASSED",$x);
	}
	//$set_reason_code = ""; // (GSP = 11 = CHARGEBACK; 12 = REFUND;)
	//$set_deposit_translogid
	//$set_deposit_transactionid
	
	######
	# API:
	# $set_reason_note
	# $set_reason_code
	# $set_deposit_translogid
	# $set_deposit_transactionid
	# $set_merchant_rating_action
	include($_SESSION['template']['company']['file_path'] . "shared/process_chargeback.shared");
	######
	
	logger3("process_chargeback",$process_chargeback);
	
	if($process_chargeback == "COMPLETE") {
		return "COMPLETE";
		exit;
	
	} else if(stristr($process_chargeback,"DUPLICATE")) {
		return "Already REFUNDED";
		exit;
		
	} else {
		return "ERR: FAILED TO UPDATE in process_refund();";
		exit;
	}
}


function find_transaction_to_refund($business_account_id=null,$last4=null,$brand=null,$cvv=null) {

	$tmp_sql = "SELECT translogid FROM translog WHERE";
	
	/// BUSINESS_ACCOUNTID
	if(!empty($business_account_id)) {
		$tmp_sql .= " business_accountid = '".$business_account_id."'";
		$add_and = " AND";
	}

	/// LAST4
	if(!empty($last4)) {
		$tmp_sql .= $add_and . " number LIKE '%" . $last4 . "'";
		//$tmp_sql .= $add_and . "RIGHT('number',4) = '" . $last4 . "' ";
		$add_and = " AND";
	}
	
	/// BRAND
	if(!empty($brand)) {
		$tmp_sql .= $add_and . " type = '".$brand."'";
		$add_and = " AND";
	}

	/// CVV
	if(!empty($cvv)) {
		$tmp_sql .= $add_and . " cvv2 = '".$cvv."'";
		$add_and = " AND";
	}
	
	$tmp_sql .= ";";
	
	logger3("0. tmp_sql",$tmp_sql);
	logger3("0. add_and",$add_and);
	
	if(empty($add_and)) {
		return "FAIL"; 
		exit;
	}
	
	$translog_lookup_array = arrayTHECASHIER($tmp_sql);
	
	logger3("0. translog_lookup_array",$translog_lookup_array);
	
	if(empty($translog_lookup_array[0])) {
		return "NONE";
		exit;
	}
	
	if(
	(!empty($translog_lookup_array[1]))
	) {
		return "MULTIPLE";
		exit;
	
	/// ONLY ONE
	} else {
		return $translog_lookup_array[0];
		exit;
	}

}



function echo_platform_old() {
	global $master_config_platform_emulation;
	
	if(!empty($master_config_platform_emulation)) {
		return $master_config_platform_emulation; 
	} else if(stristr($_SESSION['template']['company']['text_name'],"VOCASIGN")) {
		return $_SESSION['template']['company']['name'];
	} else {
		return $_SESSION['template']['company']['host_www']; 
	}
}

function echo_platform() {

	global $master_config_platform_emulation;
	
	logger3("master_config_platform_emulation",$master_config_platform_emulation);
	//default value from session

	//global $_SESSION;
	
	if(!empty($master_config_platform_emulation)) {
	    $platform_to_use = $master_config_platform_emulation;           
	} else if(stristr($_SESSION['template']['company']['text_name'],"VOCASIGN")) {
		return $_SESSION['template']['company']['name'];
	} else {
	
		$platform_to_use = $_SESSION['template']['company']['domain'];
	
		if(empty($platform_to_use)) $platform_to_use = "BANGK.com"; // weerd fix... because something is logging "NSDB.com" to the transactions platform fieeld?!  2014.03.14
	
		//if(stristr($platform_to_use,"NSDB.com")) $platform_to_use = "BANGK.com"; // weerd fix... because something is logging "NSDB.com" to the transactions platform fieeld?!  2014.03.14
	}
	
	logger3("echo_platform(): platform_to_use",$platform_to_use);
	return $platform_to_use;
}

	
function get_active_system_email_account($accountid) {

	
	$tmp_sql = "SELECT * FROM email_accounts WHERE 
	    accountid LIKE '" . $accountid . "'
	    AND status = 'ACTIVE';";
	    
	$tmp_email_account_details = object2array(readTHECASHIER($tmp_sql));
	
	logger3("tmp_sql",$tmp_sql);
	logger3("tmp_account_address_details",$tmp_email_account_details);
	
	## add system email account:
	$tmp_email_account_details['address'] = strtoupper($tmp_email_account_details['username']) . "@" . strtolower($tmp_email_account_details['host']);
	//$tmp_email_account['password'] = $tmp_email_account_details['password'];
	return $tmp_email_account_details;

}



function CountUnreadMails($host, $login, $passwd) {
      $mbox = imap_open("{{$host}/imap:143/novalidate-cert}INBOX", $login, $passwd);
      $count = 0;
      if (!$mbox) {
           //echo "Error";
      } else {          
           $headers = imap_headers($mbox);           
           foreach ($headers as $mail) {
                $flags = substr($mail, 0, 4);
                $isunr = (strpos($flags, "U") !== false);
                if ($isunr)
                $count++;
           }
      }

    imap_close($mbox);
    return $count;
}

function CountUnreadEmails($email_address, $hostname = 'nsdb'){
    $count = 0;
    if(preg_match('/^(.*)@(.*)/', $email_address, $matches)) {
        
        $username = $matches[1];
        $domain = $matches[2];
        
        $path = '/home/vmail/'.$domain.'/'.$username.'/cur/';
        
        $output = shell_exec("/BANGK\!/mail/count_unread.sh $path");
        //echo    $output;    
        //1382518650.M943509P25555.nsdb,S=3694,W=3783:2, 
        if(preg_match_all('/(?P<word1>\w+).'.$hostname.',S=(?P<word2>\d+),W=(?P<word3>\d+):2,(?P<word4>[^P|R|S|T|D|F])/', $output, $matches2)){
            //echo '<pre>'; print_r($matches2); echo '</pre>';  
            if(count($matches2[0])) $count = count($matches2[0]);
        }
        
    }
    return $count;
}

function ip2locationCONVERTER($IPaddr) {
    if ($IPaddr == "") {
        return 0;
    } else {
        $ips = split ("\.", "$IPaddr");
        return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);
    }
}




### BLINGK

# function get_blingk_bar_member($blingk_member_id) {
# 	$tmp_sql = "SELECT m.memberid, m.firstname, m.lastname, m.emailaddress, b.account_balance, a.accountid, a.accountname, b.blingk_credit, 'links' as blingk_links FROM members AS m INNER JOIN accounts AS a ON m.emailaddress = a.emailaddress AND m.memberid = '$blingk_member_id' AND a.accounttype = 'Personal' INNER JOIN balances AS b ON a.accountid = b.accountid";
# 	$blingk_member = readTHECASHIER($tmp_sql);
# 	logger("tmp_sql: " . $tmp_sql);
# 
# 	$tmp_sql = "SELECT message FROM translog WHERE service = 'BLINGK' AND memberid = '$blingk_member_id'";
# 	$blingk_member->blingk_links = arrayTHECASHIER($tmp_sql);
# 	logger("tmp_sql: " . $tmp_sql);
# 	
# 	return $blingk_member;
# }





function bangk_email_user_maker($accountid=NULL) {

		
	$tmp_account = account($accountid);
	logger3("tmp_account",$tmp_account);
	
	// exit if there is nothing
	if(empty($tmp_account['hash'])) {
		return FALSE;
	}
	
	
	$tmp_account_name = $tmp_account['accountname'];
	$tmp_account_name = trim($tmp_account_name);
	$tmp_account_name = strtolower($tmp_account_name);
	$tmp_account_name = str_replace(".", "-", $tmp_account_name); // take out periods and add a space
	$tmp_account_name = str_replace(" ", "-", $tmp_account_name); // take double spaces
	logger3("tmp_account_name",$tmp_account_name);
	
	### same for type
	$tmp_account_type = str_replace(" ", "", $tmp_account['business_type']); 	
	
	
	# //$tmp_account_name = str_replace(" com ", " dot com ", $tmp_account_name);
	# //$tmp_account_name = str_replace(" net ", " dot com ", $tmp_account_name);
	# //$tmp_account_name = str_replace(" co uk ", " dot co dot uk ", $tmp_account_name);
	# 
	# $tmp_account_name = str_replace(" private limited", ".privatelimited", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" pvt ltd", ".pvtltd", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" pty ltd", ".ptyltd", $tmp_account_name); // take double spaces
	# 
	# $tmp_account_name = str_replace(" limited company", ".limitedcompany", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" limited", ".limited", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" ltd", ".ltd", $tmp_account_name); // take double spaces
	# 
	# $tmp_account_name = str_replace(" llc", ".llc", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" limited liability company", ".llc", $tmp_account_name); // dork
	# 
	# 
	# $tmp_account_name = str_replace(" corp", ".corp", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" corporation", ".corp", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" inc", ".inc", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" incorporated", ".incorporated", $tmp_account_name); // take double spaces
	# $tmp_account_name = str_replace(" group", ".group", $tmp_account_name); // take double spaces
	# 
	# $tmp_account_name = str_replace(" dba", ".dba", $tmp_account_name); // take double spaces
	# 
	# 
	# $tmp_account_name = str_replace(" ibc", ".ibc", $tmp_account_name); // take double spaces
	# 
	# 
	# if(!stristr($tmp_account_name,".")) {
	# 	$tmp_account_name = trim($tmp_account_name).".pdba";
	# }
	# 
	# 
	# 
	# $tmp_account_name = str_replace(" com ", "dot com ", $tmp_account_name);
	# 
	# $tmp_account_name = str_replace(" ", "-", $tmp_account_name);
	
	
	//$clean_account_name_full = preg_replace("/[^a-zA-Z0-9!#$%&'*+-\/=?^_`{}|~]+/", "", $tmp_account_name);
	$clean_account_name_full = preg_replace("/[^a-zA-Z0-9#$%&'*+-\/=?^_`{}|~]+/", "", $tmp_account_name);  // without !
	
	
	
	//$clean_account_name_full_exploded = explode(".",$clean_account_name_full);
	//$clean_account_name = substr($clean_account_name_full_exploded[0],0,44).".".$clean_account_name_full_exploded[1]; // allow 20 chars for ."proprietarylimited" as "max xoroprate identifier
	$clean_account_name = substr($clean_account_name_full,0,44); // .".".$clean_account_name_full_exploded[1]; // allow 20 chars for ."proprietarylimited" as "max xoroprate identifier
	
	logger3("clean_account_name",$clean_account_name);

	//$tmp_sql = "UPDATE email_accounts SET username = '".$clean_account_name."' WHERE accountid LIKE '".$tmp_account['accountid']."';";
	
	//logger3("tmp_sql",$tmp_sql);
	//$results = updateTHECASHIER($tmp_sql);
	//test("results",$results);

	return $clean_account_name . "." . strtolower($tmp_account_type);

}





function add_postfix_email_account($personal_name,$username,$host,$password) {

	$postfix_email_account_username = $username."@".$host;
	$postfix_email_account_password = $password;
	$postfix_email_account_name = $personal_name;
	$postfix_email_account_maildir = $host."/".$username."/";
	$postfix_email_account_quota = "1024000000";
	$postfix_email_account_local_part = $username;
	$postfix_email_account_domain = $host;
	$postfix_email_account_created = datetime();
	$postfix_email_account_modified = datetime();
	$postfix_email_account_active = "1";
	
	$tmp_sql = "INSERT INTO `mailbox`(
	    			`username`, 
	    			`password`, 
	    			`name`, 
	    			`maildir`, 
	    			`quota`, 
	    			`local_part`, 
	    			`domain`, 
	    			`created`, 
	    			`modified`, 
	    			`active`
	    		) VALUES (
	    			'".addslashes($postfix_email_account_username)."',
	    			'".addslashes($postfix_email_account_password)."',
	    			'".addslashes($postfix_email_account_name)."',
	    			'".addslashes($postfix_email_account_maildir)."',
	    			'".$postfix_email_account_quota."',
	    			'".addslashes($postfix_email_account_local_part)."',
	    			'".addslashes($postfix_email_account_domain)."',
	    			'".$postfix_email_account_created."',
	    			'".$postfix_email_account_modified."',
	    			'".$postfix_email_account_active."'
	    		);";
	 //test("tmp_sql",$tmp_sql);
	 return insertTHECASHIER($tmp_sql,$database_to_use="postfixadmin");

}



function make_a_new_business_email_account($business_accountid) {
	
	if(empty($business_accountid)) {
		return FALSE;
	} else {
		$tmp_account_details = account($business_accountid);
	}
	
	
	//if(!empty($exists)) $tmp_host = "97e.bangk.net";
	
	$tmp_email_account_id = "";
	$tmp_accountid = $tmp_account_details['accountid'];
	$tmp_account_hash = $tmp_account_details['hash'];
	$tmp_username = bangk_email_user_maker($accountid=$tmp_account_details['accountid']);
	
	$tmp_host = what_bangknet_host_to_use();
	
	$tmp_password = generate_random_password($length = 32);
	$tmp_status = "ACTIVE";
	$tmp_datetime_created = datetime();
	$tmp_datetime_updated = datetime();
	
	$tmp_sql = "INSERT INTO `email_accounts`(
	`email_account_id`, 
	`accountid`, 
	`account_hash`, 
	`username`, 
	`host`, 
	`password`, 
	`status`, 
	`datetime_created`, 
	`datetime_updated`
	) VALUES (
	'".$tmp_email_account_id."',
	'".$tmp_accountid."',
	'".$tmp_account_hash."',
	'".$tmp_username."',
	'".$tmp_host."',
	'".$tmp_password."',
	'".$tmp_status."',
	'".$tmp_datetime_created."',
	'".$tmp_datetime_updated."'
	)";
	
	$email_account_id = insertTHECASHIER($tmp_sql);
	logger3("tmp_sql",$tmp_sql);
	logger3("email_account_id",$email_account_id);
	
	$add_results = add_postfix_email_account($personal_name=$tmp_account_details['accountname'],$username=$tmp_username,$host=$tmp_host,$password=$tmp_password);
	logger3("add_results",$add_results);
	
	if(empty($email_account_id)) {
		return FALSE;
	} else {
		return $email_account_id;
	}
}




function what_bangknet_host_to_use($accountid) {

	$tmp_username = bangk_email_user_maker($accountid);

	$tmp_host = "xe6.bangk.net";
	
	$tmp_sql = "SELECT email_account_id FROM email_accounts WHERE username = '".$tmp_username."' AND host = '".$tmp_host."';";
	logger3("tmp_sql",$tmp_sql);
	
	$exists = getTHECASHIER($tmp_sql);
	logger3("exists",$exists);
	
	if(!empty($exists)) {
		$tmp_host = "97e.bangk.net";
	}
	
	logger3("$tmp_host",$tmp_host);
	return $tmp_host;
}


function update_bangknet_email_account($accountid) {

	## GET ORIGINAL EMAIL ACCOUNt DETAILS:
	$tmp_sql = "SELECT * FROM email_accounts WHERE accountid = '". $accountid ."';";
	logger3("tmp_sql",$tmp_sql);
	$original_account_details = readTHECASHIER($tmp_sql);
	logger3("original_account_details",$original_account_details);
	
	### GENERAL
	$tmp_datetime = datetime();
	$account_details = account($accountid);
	$datetime_updated = datetime();
	$clean_account_name = bangk_email_user_maker($accountid);
	$host_name = what_bangknet_host_to_use($accountid);


	$new_username = $clean_account_name;
	$new_host = $host_name;
	//$datetime_updated
	## UPDATE EMAIL_ACCCOUNTS
	$tmp_sql = "UPDATE email_accounts
	SET 
	username = '". $new_username ."'
	,host = '". $new_host ."'
	,datetime_updated = '". $datetime_updated ."'
	WHERE 
	accountid = '". $accountid ."';";
	logger3("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	logger3("update_results",$update_results);
	
	
	### POSTIFX
	$domain = $host_name;
	$username = $clean_account_name . "@" . $domain;
	$name = $account_details['accountname'];
	$maildir = $domain."/".$clean_account_name;
	$local_part = $clean_account_name;
	$modified = $tmp_datetime;

	$tmp_sql = "UPDATE mailbox SET 
	username = '". $username ."',
	name = '". $name ."',
	maildir = '". $maildir ."',
	local_part = '". $local_part ."',
	domain = '". $domain ."',
	modified = '". $modified ."'
	WHERE
	local_part = '". $original_account_details->username ."';
	";
	
	logger3("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql,$database_to_use="postfixadmin");
	logger3("update_results",$update_results);
	
	### MOVE LOCAL FILES:
	//chmod -R 773 /home/vmail
	$execute_status = "";
	$tmp_exec = "mv /home/vmail/". $original_account_details->host ."/". $original_account_details->username ." /home/vmail/". $new_host ."/". $new_username;
	//$tmp_exec = "mv /home/vmail/xe6.bangk.net/abc.corp3 /home/vmail/xe6.bangk.net/abc.corp4";
	logger3("tmp_exec",$tmp_exec);
	$execute_status = exec($tmp_exec);
	logger3("execute_status",$execute_status);
	
	//chmod -R 773 /var/www/html/mail/autoresponsemessage
	$execute_status = "";
	$tmp_exec = "mv /var/www/html/mail/autoresponsemessage/".$original_account_details->username."@".$original_account_details->host."-dovecot.sieve /var/www/html/mail/autoresponsemessage/".$new_username."@".$new_host."-dovecot.sieve";
	logger3("tmp_exec",$tmp_exec);
	$execute_status = system($tmp_exec);
	logger3("execute_status",$execute_status);
	
	return "done.";
		
}


function send_sms($country_code,$mobile_number,$sms_message) {

	//$sms_message = str_replace(" ", "%20", $sms_message);
	//
	//$curl_url = "https://www.onverify.com/sms.php";
	//$curl_data = "userid=5822&";
	//$curl_data .= "apipass=5597&";
	//$curl_data .= "msg=BLINGK!%20Security%20PIN:%20%s&";
	//$curl_data .= "number=" . $mobile_number . "&";
	//$curl_data .= "pin=random";
	//
	////function postDATA($curl_url,$curl_data);
	//simpleCURLER($curl_url,$curl_data);

	##########################################################
	### TWILIO
	
	global $master_config_root_path;
	require_once($master_config_root_path . "shared/twilio-php/Services/Twilio.php");
		
	// set your AccountSid and AuthToken from www.twilio.com/user/account
	$AccountSid = "AC6759779db19651223a700c633e613021";
	$AuthToken = "20a52a3b8dccdbc33d4a7df45b5368bf";
		 
	$client = new Services_Twilio($AccountSid, $AuthToken);
		
		
		
		 
	$sms = $client->account->sms_messages->create(
		"+16464309136", // From this number
		"+".$country_code.$mobile_number,
		$sms_message);
	##########################################################
	
}


function refund_to_gateway($transactionid,$comments='Refund comments or detail') {
    
    //test("transactionid",$transactionid);
    
    global $master_config_root_path;
    //global $master_config_GSP_gateway;
    //global $master_config_GSP_gateway;
    
    $the_three_associated_transactions = get_the_three_transactions($transactionid);
    //test("the_three_associated_transactions",$the_three_associated_transactions);
    
    ///$transaction_details = transaction($transaction_id);
    $translog_details = translog($the_three_associated_transactions['deposit']['translogid']);
    //test("refund_to_gateway(): translog_details",$translog_details);
    //exit;
    
    /* AVAILABLE VARS FROM TRANSLOG TABLE:
    $translog_details['translogid']
    $translog_details['platform']      ////("BANGK.com")
    $translog_details['hash']
    $translog_details['business_accountid']
    $translog_details['business_account_number']
    $translog_details['memberid']
    $translog_details['accountid']
    $translog_details['acquirer']
    $translog_details['amount']
    $translog_details['type']         //// mastercard/visa
    $translog_details['credit_card_number']
	$translog_details['expdate']
	$translog_details['expiration_month']
	$translog_details['expiration_year']
	$translog_details['customer_emailaddress']
	$translog_details['transactionid_from_gateway']   /// often used as reference number for refunding
    */

    ####################################################
    ### START: GSP
    ####################################################
    ### if(stristr($translog_details['acquirer'],"GSP")) {
	###     
	###     
    ### 	require_once($master_config_root_path . "shared/nusoap-0.9.5/lib/nusoap.php");
    ### 	
    ### 	$return = false;
    ### 	        
    ### 	// Create the client instance
    ### 	//$client = new nusoap_client('https://gwsys1.globalsecureprocessing.com/webservice/server.php?wsdl', true);
    ### 	$client = new nusoap_client($master_config_GSP_gateway, true);
    ### 	// Check for an error
    ### 	$err = $client->getError();
    ### 	if ($err) {
    ### 	    //$return['error'] = $err;        
    ### 	}else{
    ### 	    $merchant_id = '62';
    ### 	    $merchant_token = 'MID-62f8cot8gp93';
    ### 	    
    ### 	    $hash = md5($merchant_id.$merchant_token.$transaction_id);
    ### 	    
    ### 	    // Call the SOAP method
    ### 	    $result = $client->call('refund', array('data' => array('merchant_id' => $merchant_id, 'merchant_token' => $merchant_token, 'hashkey' => $hash, 'transaction_id' => $transaction_id, 'comments'=>$comments, 'amount'=>$amount)));
    ### 	    
    ### 	   #  echo '<pre>'; print_r($result); echo '</pre>';
    ### 	   #  if($result['result_code'] == '0'){
    ### 	   #      $return =  $result['refund_id'];
    ### 	   #  }
    ### 	   //$return = $result;
    ### 	}
	###  
	###  ### FINAL RETURN SETTING:
	###  if($result['result_code'] == 0) {
	###  	$return = "COMPLETED";
	###  } else {
	###  	$return = "FAILED";
	###  }   
    ### }
    ####################################################
    ### END: GSP
    ####################################################

	
	test("translog_details['acquirer']",$translog_details['acquirer']);


    ####################################################
    ### START: ECOREPAY (ECP)
    ####################################################
    if(stristr($translog_details['acquirer'],"ECP")) {
	    
	    
                require_once($master_config_root_path . "shared/process_ecorepay_classes.shared"); 
                $result = ecorepay_refund($translog_details['transactionid_from_gateway'], $translog_details['amount']);	    	    
	    		
		### FINAL RETURN SETTING:
		if($result['success'] == 1 || $result['success'] == true) {
			$return = "COMPLETED";
		} else {
			$return = "FAILED";
		}   
    }
    ####################################################
    ### END: ECOREPAY (ECP)
    ####################################################




    ####################################################
    ### START: PMD (paymentdepot)
    ####################################################
    if(stristr($translog_details['acquirer'],"PMD")) {
        
        require_once($master_config_root_path . "shared/process_PMD_classes.shared");      
        
        $result = PMD_refund($translog_details['transactionid_from_gateway'], $translog_details['amount'], $translog_details['credit_card_number'], $translog_details['expiration_month'], $translog_details['expiration_year']);
		    
        logger3('PMD_refund', $result);	    	    		
        ### FINAL RETURN SETTING:
        if($result['success'] == 1 || $result['success'] == true) {
                $return = "COMPLETED";
        } else {
                $return = "FAILED";
        }     
    }
    ####################################################
    ### END: PMD (paymentdepot)
    ####################################################





    return $return;
}



function select_country($name_of_country_field,$session_value='',$css_class='',$id_to_update='') {
	//test("name_of_country_field",$name_of_country_field);
	//test("session_value",$session_value);
	//test("css_class",$css_class);
	//test("id_to_update",$id_to_update);
	//test("",);
	//test("1. id_to_update",$id_to_update);
	return outputSelectCountry($name_of_country_field,$session_value,$css_class,$id_to_update);
	
}


function outputSelectCountry($name_of_country_field,$session_value='',$css_class='',$id_to_update='') {

	//test("session_value",$session_value);
	
	//test("1. id_to_update",$id_to_update);
	
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	
	//test("country_name",$country_name);


	if(empty($css_class)) $css_class = "default_select_style";


	$html_output = "<span class='".$css_class."'>";
	
	if(empty($id_to_update)) {
		$html_output .= "<select id='".$name_of_country_field."' name='".$name_of_country_field."' onChange='validateSelect(this);');'>";
	} else {
		$html_output .= "<select id='".$name_of_country_field."' name='".$name_of_country_field."' onChange='validateSelect(this); updateDISPLAY(this,\"". $id_to_update ."\");'>";
	}
	

	
	if(empty($session_value)) { 
		$html_output .= "<option value=''>Please select one...</option>";
	} else {
		if($country_iso3) {
			$html_output .= "<option value='" . $country_iso3 . "'>" . geo_data($country_iso3,"iso3","printable_name") . "</option>";
		} else {
			$html_output .= "<option value='" . geo_data($country_name,"name","iso3") . "'>" . $country_name . "</option>";
		}
		
	}
	
	$html_output .= "<option value=''></option>";

	$tmp_sql = "SELECT geodataid FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL;";
	$geodataid_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($geodataid_array as $key => $geodataid) {
		$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $geodata_row_details->iso3 . "'>" . $geodata_row_details->printable_name . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</span>";
	return $html_output;

}


function outputSelectCountryWIZARD($name_of_country_field,$session_value='',$css_class='',$id_to_update='') {

	//test("session_value",$session_value);
	
	//test("1. id_to_update",$id_to_update);
	
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	
	//test("country_name",$country_name);


	if(empty($css_class)) $css_class = "default_select_style";


	$html_output = "<span class='".$css_class."'>";
	
	if(empty($id_to_update)) {
		$html_output .= "<select id='".$name_of_country_field."' name='".$name_of_country_field."' onChange='validateSelect(this);'); updatePHPsession(this,'account_identity_manager_". $name_of_country_field ."');'>";
	} else {
		$html_output .= "<select id='".$name_of_country_field."' name='".$name_of_country_field."' onChange='validateSelect(this); updateDISPLAY(this,\"". $id_to_update ."\"); updatePHPsession(this,'account_identity_manager_". $name_of_country_field ."');'>";
	}
	

	
	if(empty($session_value)) { 
		$html_output .= "<option value=''>Please select one...</option>";
	} else {
		if($country_iso3) {
			$html_output .= "<option value='" . $country_iso3 . "'>" . geo_data($country_iso3,"iso3","printable_name") . "</option>";
		} else {
			$html_output .= "<option value='" . geo_data($country_name,"name","iso3") . "'>" . $country_name . "</option>";
		}
		
	}
	
	$html_output .= "<option value=''></option>";

	$tmp_sql = "SELECT geodataid FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL;";
	$geodataid_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($geodataid_array as $key => $geodataid) {
		$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $geodata_row_details->iso3 . "'>" . $geodata_row_details->printable_name . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</span>";
	return $html_output;

}





function get_list_of_countries() {
	
	$tmp_sql = "SELECT * FROM geo_data
				WHERE iso2 != ''
				AND iso2 IS NOT NULL
				AND iso3 != ''
				AND iso3 IS NOT NULL
				AND timezone != ''
				AND timezone IS NOT NULL
				ORDER BY name ASC
				;";
	//test("tmp_sql",$tmp_sql);
	return readarrayTHECASHIER($tmp_sql);
}

function outputSelectCountryAVT($name_of_field,$session_value=null,$css_class=null) {
        
	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	} else {
		$country_name = strtoupper($session_value);
	}
	
	
	//test("country_name",$country_name);


	if(empty($css_class)) $css_class = "default_select_style";


	$html_output = "<span class='".$css_class."'>";
	$html_output .= "<select id='".$name_of_field."' name='".$name_of_field."' onChange='onChangeCountryAVT(this);'>";

	
	if(empty($session_value)) { 
		$html_output .= "<option value=''>Click here to select the COUNTRY to call...</option>";
	} else {
		if($country_iso3) {
			$html_output .= "<option value='" . $country_iso3 . "'>" . geo_data($country_iso3,"iso3","printable_name") . "</option>";
		} else {
			$html_output .= "<option value='" . geo_data($country_name,"name","iso3") . "'>" . $country_name . "</option>";
		}
		
	}
	
	$html_output .= "<option value=''></option>";
	$html_output .= "<option value='AUS'>Australia</option>";
	$html_output .= "<option value='CAN'>Canada</option>";
	$html_output .= "<option value='GBR'>Great Britain</option>";
	$html_output .= "<option value='IRL'>Ireland</option>";
	$html_output .= "<option value='NZD'>New Zealand</option>";
	$html_output .= "<option value='USA'>United States</option>";
	$html_output .= "<option value=''></option>";

	$tmp_sql = "SELECT geodataid FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL;";
	$geodataid_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($geodataid_array as $key => $geodataid) {
		$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $geodata_row_details->iso3 . "'>" . $geodata_row_details->printable_name . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</span>";
	return $html_output;

}





function outputSelectDOB($session_value_year=null,$session_value_month=null,$session_value_day=null,$css_class=null,$session_to_update='',$update_innerHTML='') {

  if(empty($css_class)) $css_class = "default_select_style";
  $html_output = "<span class='".$css_class."'>";
  
  
  if(!empty($update_innerHTML)) $add_update_innerHTML = "displayUpdatedBirthdate(this,'". $update_innerHTML ."_birth_year');";
  if(!empty($session_to_update)) $add_session_parameter = "updateSESSION(this,'". $session_to_update ."_birth_year');";
  $html_output .= "<select id='birth_year' name='birth_year' onChange=\"validateSelectDOB(this); $add_session_parameter $add_update_innerHTML\" onFocus=\"validateSelectDOB(this);\">";
  $add_session_parameter = "";
  $id_to_update = "";
  
  if(isset($session_value_year)) { 
    $html_output .= "<option value='" . $session_value_year . "'>" . $session_value_year . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Year:</option>
    <option value='1900'>1900</option>
    <option value='1901'>1901</option>
    <option value='1902'>1902</option>
    <option value='1903'>1903</option>
    <option value='1904'>1904</option>
    <option value='1905'>1905</option>
    <option value='1906'>1906</option>
    <option value='1907'>1907</option>
    <option value='1908'>1908</option>
    <option value='1909'>1909</option>
    <option value='1910'>1910</option>
    <option value='1911'>1911</option>
    <option value='1912'>1912</option>
    <option value='1913'>1913</option>
    <option value='1914'>1914</option>
    <option value='1915'>1915</option>
    <option value='1916'>1916</option>
    <option value='1917'>1917</option>
    <option value='1918'>1918</option>
    <option value='1919'>1919</option>
    <option value='1920'>1920</option>
    <option value='1921'>1921</option>
    <option value='1922'>1922</option>
    <option value='1923'>1923</option>
    <option value='1924'>1924</option>
    <option value='1925'>1925</option>
    <option value='1926'>1926</option>
    <option value='1927'>1927</option>
    <option value='1928'>1928</option>
    <option value='1929'>1929</option>
    <option value='1930'>1930</option>
    <option value='1931'>1931</option>
    <option value='1932'>1932</option>
    <option value='1933'>1933</option>
    <option value='1934'>1934</option>
    <option value='1935'>1935</option>
    <option value='1936'>1936</option>
    <option value='1937'>1937</option>
    <option value='1938'>1938</option>
    <option value='1939'>1939</option>
    <option value='1940'>1940</option>
    <option value='1941'>1941</option>
    <option value='1942'>1942</option>
    <option value='1943'>1943</option>
    <option value='1944'>1944</option>
    <option value='1945'>1945</option>
    <option value='1946'>1946</option>
    <option value='1947'>1947</option>
    <option value='1948'>1948</option>
    <option value='1949'>1949</option>
    <option value='1950'>1950</option>
    <option value='1951'>1951</option>
    <option value='1952'>1952</option>
    <option value='1953'>1953</option>
    <option value='1954'>1954</option>
    <option value='1955'>1955</option>
    <option value='1956'>1956</option>
    <option value='1957'>1957</option>
    <option value='1958'>1958</option>
    <option value='1959'>1959</option>
    <option value='1960'>1960</option>
    <option value='1961'>1961</option>
    <option value='1962'>1962</option>
    <option value='1963'>1963</option>
    <option value='1964'>1964</option>
    <option value='1965'>1965</option>
    <option value='1966'>1966</option>
    <option value='1967'>1967</option>
    <option value='1968'>1968</option>
    <option value='1969'>1969</option>
    <option value='1970'>1970</option>
    <option value='1971'>1971</option>
    <option value='1972'>1972</option>
    <option value='1973'>1973</option>
    <option value='1974'>1974</option>
    <option value='1975'>1975</option>
    <option value='1976'>1976</option>
    <option value='1977'>1977</option>
    <option value='1978'>1978</option>
    <option value='1979'>1979</option>
    <option value='1980'>1980</option>
    <option value='1981'>1981</option>
    <option value='1982'>1982</option>
    <option value='1983'>1983</option>
    <option value='1984'>1984</option>
    <option value='1985'>1985</option>
    <option value='1986'>1986</option>
    <option value='1987'>1987</option>
    <option value='1988'>1988</option>
    <option value='1989'>1989</option>
    <option value='1990'>1990</option>
    <option value='1991'>1991</option>
    <option value='1992'>1992</option>
    <option value='1993'>1993</option>
    <option value='1994'>1994</option>
    <option value='1995'>1995</option>
    <option value='1996'>1996</option>
    <option value='1997'>1997</option>
    <option value='1998'>1998</option>
    <option value='1999'>1999</option>
    <option value='2000'>2000</option>
    </select>&nbsp;";
  
  // birth_month
  if(!empty($update_innerHTML)) $add_update_innerHTML = "displayUpdatedBirthdate(this,'". $update_innerHTML ."_birth_month');";
  if(!empty($session_to_update)) $add_session_parameter = "updateSESSION(this,'". $session_to_update ."_birth_month');";
  $html_output .= "<select id='birth_month' name='birth_month' onChange=\"validateSelectDOB(this); $add_session_parameter $add_update_innerHTML\">";
  $add_update_innerHTML = "";
  $add_session_parameter = "";
  
  if(isset($session_value_month)) { 
    $html_output .= "<option value='" . $session_value_month . "'>" . $session_value_month . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Month:</option>
    <option value='01'>01 (Jan)</option>
    <option value='02'>02 (Feb)</option>
    <option value='03'>03 (Mar)</option>
    <option value='04'>04 (Apr)</option>
    <option value='05'>05 (May)</option>
    <option value='06'>06 (Jun)</option>
    <option value='07'>07 (Jul)</option>
    <option value='08'>08 (Aug)</option>
    <option value='09'>09 (Sep)</option>
    <option value='10'>10 (Oct)</option>
    <option value='11'>11 (Nov)</option>
    <option value='12'>12 (Dec)</option>
    </select>&nbsp;"; 
  
  // birth_day
   if(!empty($update_innerHTML)) $add_update_innerHTML = "displayUpdatedBirthdate(this,'". $update_innerHTML ."_birth_day');";
  if(!empty($session_to_update)) $add_session_parameter = "updateSESSION(this,'". $session_to_update ."_birth_day');";
  $html_output .= "<select id='birth_day' name='birth_day' onChange=\"validateSelectDOB(this); $add_session_parameter $add_update_innerHTML\">";
  $add_update_innerHTML = "";
  $add_session_parameter = "";
  
  
  
  if(isset($session_value_day)) { 
    $html_output .= "<option value='" . $session_value_day . "'>" . $session_value_day . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Day:</option>
    <option value='01'>01</option>
    <option value='02'>02</option>
    <option value='03'>03</option>
    <option value='04'>04</option>
    <option value='05'>05</option>
    <option value='06'>06</option>
    <option value='07'>07</option>
    <option value='08'>08</option>
    <option value='09'>09</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
    <option value='12'>12</option>
    <option value='13'>13</option>
    <option value='14'>14</option>
    <option value='15'>15</option>
    <option value='16'>16</option>
    <option value='17'>17</option>
    <option value='18'>18</option>
    <option value='19'>19</option>
    <option value='20'>20</option>
    <option value='21'>21</option>
    <option value='22'>22</option>
    <option value='23'>23</option>
    <option value='24'>24</option>
    <option value='25'>25</option>
    <option value='26'>26</option>
    <option value='27'>27</option>
    <option value='28'>28</option>
    <option value='29'>29</option>
    <option value='30'>30</option>
    <option value='31'>(31)</option>
    </select>";
  $html_output .= "</span>";
  
  return $html_output;
  
}

## DATE OF INCORPORATION
function outputSelectDOI($session_value_year=null,$session_value_month=null,$session_value_day=null,$css_class=null) {


  if(empty($css_class)) $css_class = "default_select_style";
  $html_output = "<span class='".$css_class."'>";
  $html_output .= "<select id='birth_year' name='birth_year' onFocus='validateSelectDOB(this);' onChange='validateSelectDOB(this);'>";
  
  if(!empty($session_value_year)) { 
    $html_output .= "<option value='" . $session_value_year . "'>" . $session_value_year . "</option>
    <option value=''></option>";
  }
  $year = date("Y");
  $html_output .= "<option value=''>Year:</option>";
  
  while($year >= "1900") {
	  $html_output .= "<option value='$year'>$year</option>";
	  $year = $year - "1";
  }
  
  $html_output .= "</select>";
  $html_output .= "&nbsp;";
  
  // birth_month
  $html_output .= "<select id='birth_month' name='birth_month' onChange='validateSelectDOB(this);'>";
    
  if(!empty($session_value_month)) { 
    $html_output .= "<option value='" . $session_value_month . "'>" . $session_value_month . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Month:</option>
    <option value='01'>01 (Jan)</option>
    <option value='02'>02 (Feb)</option>
    <option value='03'>03 (Mar)</option>
    <option value='04'>04 (Apr)</option>
    <option value='05'>05 (May)</option>
    <option value='06'>06 (Jun)</option>
    <option value='07'>07 (Jul)</option>
    <option value='08'>08 (Aug)</option>
    <option value='09'>09 (Sep)</option>
    <option value='10'>10 (Oct)</option>
    <option value='11'>11 (Nov)</option>
    <option value='12'>12 (Dec)</option>
    </select>&nbsp;"; 
  
  $html_output .= "<select id='birth_day' name='birth_day' onChange='validateSelectDOB(this);'>";
  
  if(!empty($session_value_day)) { 
    $html_output .= "<option value='" . $session_value_day . "'>" . $session_value_day . "</option>
    <option value=''></option>";
  } 
  $html_output .= "
    <option value=''>Day:</option>
    <option value='01'>01</option>
    <option value='02'>02</option>
    <option value='03'>03</option>
    <option value='04'>04</option>
    <option value='05'>05</option>
    <option value='06'>06</option>
    <option value='07'>07</option>
    <option value='08'>08</option>
    <option value='09'>09</option>
    <option value='10'>10</option>
    <option value='11'>11</option>
    <option value='12'>12</option>
    <option value='13'>13</option>
    <option value='14'>14</option>
    <option value='15'>15</option>
    <option value='16'>16</option>
    <option value='17'>17</option>
    <option value='18'>18</option>
    <option value='19'>19</option>
    <option value='20'>20</option>
    <option value='21'>21</option>
    <option value='22'>22</option>
    <option value='23'>23</option>
    <option value='24'>24</option>
    <option value='25'>25</option>
    <option value='26'>26</option>
    <option value='27'>27</option>
    <option value='28'>28</option>
    <option value='29'>29</option>
    <option value='30'>30</option>
    <option value='31'>(31)</option>
    </select>";
  $html_output .= "</span>";
  
  return $html_output;
  
}



function outputSelectCallingCode($name_of_field,$session_value=null,$css_class=null) {

	if(strlen($session_value) == 3) {
		$country_iso3 = $session_value;
	}
	
	
	//test("country_name",$country_name);


	if(empty($css_class)) $css_class = "default_select_style";


	$html_output = "<span class='".$css_class."'>";
	$html_output .= "<select id='".$name_of_field."' name='".$name_of_field."' onChange='onChangeCountryCode(this);'>";

	
	if(empty($session_value)) { 
		$html_output .= "<option value=''>Select Calling Code...</option>";
	} else {
		$html_output .= "<option value='" . $session_value . "'>+" . $session_value . "</option>";
	}
	
	$html_output .= "<option value=''></option>";

	$tmp_sql = "SELECT distinct(calling_code) FROM geo_data WHERE calling_code != '' AND  calling_code IS NOT NULL ORDER BY calling_code ASC;";
	$calling_code_array = arrayTHECASHIER($tmp_sql);
	//test("geodataid_array",$geodataid_array);
	foreach($calling_code_array as $key => $calling_code) {
		//$tmp_sql = "SELECT * FROM geo_data WHERE geodataid LIKE '".$geodataid."';";
		//$geodata_row_details = readTHECASHIER($tmp_sql);
		$html_output .= "<option value='" . $calling_code . "'>+" . $calling_code . "</option>";
	
	}
	$html_output .= "</select>";
	$html_output .= "</span>";
	return $html_output;

}









function translog($translogid) {
	$tmp_sql = "SELECT * FROM translog WHERE translogid = '".$translogid."';";
	return object2array(readTHECASHIER($tmp_sql));
}


function get_dynamic_fee_for_this_account($business_accountid) {
	
	if(empty($business_accountid)) $business_accountid = $_SESSION['account']['accountid'];
	
	//test("_SESSION['account']['accountid']",$_SESSION['account']['accountid']);
	
	$rating = get_merchant_rating($business_accountid);
	
	//test("rating",$rating);
	
	$fee = get_dynamic_fee($rating['satisfied']/100,$acount_sponsor_accountid='',$business_accountid);
	
	//test("fee",$fee);
	
	return $fee;
}

function get_dynamic_fee($rating,$acount_sponsor_accountid='',$business_accountid='') {


	if(!empty($business_accountid)) {
		
		$gateway_prfoile = getTHECASHIER("SELECT gateway_profile FROM accounts WHERE accountid = '". $business_accountid ."';");


	} else {
		
		
	
		$sponsor_accountid = getTHECASHIER("SELECT sponsor_accountid FROM accounts WHERE accountid = '". $accountid ."';");
		//test("sponsor_accountid",$sponsor_accountid);
		
		/// check the payme business
		if(!empty($acount_sponsor_accountid)) {
			
			$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $acount_sponsor_accountid ."';");
			//test("1: gateway_profile",$gateway_profile);
		
		} else if(
		(empty($acount_sponsor_accountid)) &&
		(is_array($_SESSION['payme'])) 
		){
			//test("_SESSION['payme']",$_SESSION['payme']);
			$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $_SESSION['payme']['business']['account']['sponsor_accountid'] ."';");
			//test("2: gateway_profile",$gateway_profile);
		
		/// check the 
		} else 	if(
		(empty($acount_sponor_accountid)) &&
		(!stristr($_SERVER['SCRIPT_URI'],".admin")) &&
		(is_array($_SESSION['account'])) 
		){
			//test("_SERVER['REQUEST_URI']",$_SERVER['REQUEST_URI']);
			//test("_SERVER['SCRIPT_URI']",$_SERVER['SCRIPT_URI']);
			$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $_SESSION['account']['sponsor_accountid'] ."';");
			//test("3: gateway_profile",$gateway_profile);
		
		}
		
		
	}




	
	//test("gateway_profile",$gateway_profile);
	
	if(stristr($gateway_profile,"ECP")) {
		if($rating < 0.90) return 0.250;
		if($rating < 0.91) return 0.189;
		if($rating < 0.92) return 0.179;
		if($rating < 0.93) return 0.169;
		if($rating < 0.94) return 0.159;
		if($rating < 0.95) return 0.149;
		if($rating < 0.96) return 0.139;
		if($rating < 0.97) return 0.129;
		if($rating < 0.08) return 0.129;
		if($rating < 0.99) return 0.129;
		if($rating <= 01.00) return 0.129;
	} 
	
	### DEFAULT:
	if($rating < 0.90) return 0.250;
	if($rating < 0.91) return 0.189;
	if($rating < 0.92) return 0.179;
	if($rating < 0.93) return 0.169;
	if($rating < 0.94) return 0.159;
	if($rating < 0.95) return 0.149;
	if($rating < 0.96) return 0.139;
	if($rating < 0.97) return 0.129;
	if($rating < 0.08) return 0.119;
	if($rating < 0.99) return 0.109;
	if($rating <= 01.00) return 0.099;	
}

function get_dynamic_DTR($accountid='',$rating='') {

	//test("get_dynamic_DTR(): accountid",$accountid);
	//test("get_dynamic_DTR(): rating",$rating);
	
	if(!empty($accountid)) {

		//test("0. rating",$$rating);
		
		if(empty($rating)) {
			$rating_details = get_merchant_rating($accountid);
			//test("get_dynamic_DTR($accountid): rating_details",$rating_details);
			$rating = $rating_details['decimal'];
		}
		
		
		### GATEWAY EXCEPTIONS:
		/// ECP:
		$sponsor_accountid = getTHECASHIER("SELECT sponsor_accountid FROM accounts WHERE accountid = '". $accountid ."';");
		$gateway_profile = getTHECASHIER("SELECT associated_gateway FROM affiliates WHERE hash = '". $sponsor_accountid ."';");
		//if(stristr($sponsor_accountid,"b7e9aac09c099d4bfe5cfc85917df9e3")) return 20;	
		if(empty($gateway_profile))  {
			$gateway_profile = getTHECASHIER("SELECT gateway_profile FROM accounts WHERE accountid = '". $accountid ."';");
		}
		

		### ECP PROFILE
		if(
		(stristr($gateway_profile,"NEW")) ||
		(stristr($gateway_profile,"ECP"))
		) {
			
			if($rating < 0.90) return 90; // days
			if($rating < 0.91) return 60;
			if($rating < 0.92) return 55;
			if($rating < 0.93) return 50;
			if($rating < 0.94) return 45;
			if($rating < 0.95) return 40;
			if($rating < 0.96) return 35;
			if($rating < 0.97) return 30;
			if($rating < 0.08) return 30;
			if($rating < 0.99) return 30;
			if($rating <= 01.00) return 30;
		}
		
		### DEFAULT PROFILE	
		if($rating < 0.90) return 90; // days
		if($rating < 0.91) return 60;
		if($rating < 0.92) return 55;
		if($rating < 0.93) return 50;
		if($rating < 0.94) return 45;
		if($rating < 0.95) return 40;
		if($rating < 0.96) return 35;
		if($rating < 0.97) return 30;
		if($rating < 0.08) return 25;
		if($rating < 0.99) return 20;
		if($rating <= 01.00) return 15;
		
		
		
		
		### GET MERCHANT RATING
		//$rating_details = get_merchant_rating($accountid);
		//$rating = $rating_details['decimal'];
	
	} else {
		
		return "";
	}
	
}


function translate_gateway_profile_to_gateway($gateway_profile) {
	
	if($gateway_profile == "NEW") return "ECP";
	if($gateway_profile == "PROVEN") return "ECP";
	
}


function get_merchant_rating($business_accountid,$start_date='',$limit_date='',$display_logging='') {
	$accountid = $business_accountid;
	$version = "2";
	$personal_or_business = getTHECASHIER("SELECT accounttype WHERE accountid = '". $accountid ."';");
	if(stristr($personal_or_business,"PERSONAL")) return FALSE;

	//logger3("get_merchant_rating(business_accountid=$business_accountid): ",$x);
		

	if(empty($display_logging)) $display_logging = ""; // for algorithm testing
	if(empty($limit_days_ago)) $limit_days_ago = "30";

	### get most recent transaction to establish startdate
	$tmp_sql = "SELECT requested_datetime FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	ORDER BY updated_datetime DESC
	LIMIT 1";
	//logger3("tmp_sql",$tmp_sql);
	$most_recent_transaction_datetime = getTHECASHIER($tmp_sql);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	
	//logger3("dynamic_processing_profile($accountid)",$dynamic_processing_profile);
	
	### if(stristr($dynamic_processing_profile['profile_name'],"PMD")) {
	### 
	### 	global $master_config_gateway_PMD_startdate;
	### 	//logger3("master_config_gateway_PMD_startdate",$master_config_gateway_PMD_startdate);
	### 	
	### 	if($most_recent_transaction_datetime > $master_config_gateway_PMD_startdate) {
	### 		$forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $master_config_gateway_PMD_startdate ."'";
	### 	}
	### 
	### } else {
	### 	
	### 	$forget_about_old_chargebacks_for_businesses_moving_forward = "";
	### 
	### }
	
	//logger3("$accountid: forget_about_old_chargebacks_for_businesses_moving_forward",$forget_about_old_chargebacks_for_businesses_moving_forward);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	logger3("account_details['status_payments']",$account_details['status_payments']);
	
	if(stristr($account_details['status_payments'],"ON")) {
	    //global $master_config_gateway_ECP_startdate
	    global $master_config_gateway_ECP_startdate;
	    global $master_config_gateway_PMD_startdate;

	    $dynamic_processing_profile = get_dynamic_processing_profile($accountid);
	    
	    logger3("dynamic_processing_profile['profile_name'] ",$dynamic_processing_profile['profile_name']);
	    
	
	    $account_gateway_startdate = "master_config_gateway_". $dynamic_processing_profile['profile_name'] ."_startdate";
	    
	    logger3("account_gateway_startdate",$account_gateway_startdate);
	    
	    logger3("$ account_gateway_startdate",$$account_gateway_startdate);
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $$account_gateway_startdate ."'";
	
	} else {
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "";
	}
	
	

	
	
	/// make the PMD exception for new/old clients:
	    	//logger3("most_recent_transaction_datetime",$most_recent_transaction_datetime);
	
	if(empty($start_date)) $start_date = $most_recent_transaction_datetime;
	//test("1start_date",$start_date);
	
	if(!empty($start_date)) {
		
		
		$limit_date = date("Y-m-d H:i:s",strtotime($start_date . " -$limit_days_ago days"));
		//test("1limit_date",$limit_date);
	}
	
	if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	//test("2start_date",$start_date);
	
	if(empty($limit_date)) $limit_date = date("Y-m-d H:i:s",strtotime("-$limit_days_ago days"));
	//test("2limit_date",$limit_date);
	
	//logger3("limit_date",$limit_date);
	### $datetime_limit_days = strtotime("-". $limit_days ." days");
	### logger3("datetime_limit_days",$datetime_limit_days);
	### $datetime_limit_days = date("Y-m-d H:i:s",$datetime_limit_days);
	### logger3("datetime_limit_days",$datetime_limit_days);
	### 
	### 
	### ### SET INCOMING:
	### if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	
	
	//exit;
	
	
	
	## GRACE PERIOD:
	$grace_days = "0";
	$datetime_grace = strtotime("-". $grace_days ." days");
	//logger3("datetime_limit_days",$datetime_limit_days);
	$datetime_grace = date("Y-m-d H:i:s",$datetime_grace);
	//logger3("datetime_limit_days",$datetime_limit_days);


	
	// clear previous loop vars:
	$VOLUME_discount_added = "";
	//logger3("accountid",$accountid);
	$accountid = $business_accountid;

	### TRANSACTION SUM
	// $tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	logger3("tmp_sql",$tmp_sql);
	
	$total_volume_for_business = getTHECASHIER($tmp_sql);
	logger3("total_volume_for_business",$total_volume_for_business);
	
	### TRANSACTION COUNT
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	logger3("tmp_sql",$tmp_sql);
	
	$total_transactions_for_business = getTHECASHIER($tmp_sql);
	logger3("total_transactions_for_business",$total_transactions_for_business);

	    
	### CHARGEBACKS FOR BUSINESS:
	### $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	### WHERE accountid = '". $accountid ."'
	### AND description = 'INCOMING' 
	### AND (status='CHARGEBACK' OR return_reason LIKE '%CHARGEBACK%')
	### AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	### AND requested_datetime >= '". $datetime_limit_days ."'
	### ;";
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status = 'CHARGEBACK' OR return_reason LIKE '%BANK-ISSUED CHARGEBACK%')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status = 'CHARGEBACK' OR return_reason LIKE '%BANK-ISSUED CHARGEBACK%')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//test("tmp_sql",$tmp_sql);
	$total_CHARGEBACK_for_business = getTHECASHIER($tmp_sql);
	//test("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	//$total_CHARGEBACK_for_business = $total_CHARGEBACK_for_business + 0;
	
	### REFUNDED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND status='REFUNDED'
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND status='REFUNDED'
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//logger3("tmp_sql",$tmp_sql);
	$total_REFUNDED_for_business = getTHECASHIER($tmp_sql);
	
	
	### REVERSED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE platform = 'BANGK.com'
	// AND accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status = 'REVERSED' AND return_reason NOT LIKE '%BANK-ISSUED CHARGEBACK%')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status = 'REVERSED' AND return_reason NOT LIKE '%BANK-ISSUED CHARGEBACK%')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//logger3("tmp_sql",$tmp_sql);
	$total_REVERSED_for_business = getTHECASHIER($tmp_sql);
	//logger3("total_REVERSED_for_business",$total_REVERSED_for_business);


	### CANCELED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE platform = 'BANGK.com'
	// AND accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND (status LIKE 'CANCELED')
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	// AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	// $forget_about_old_chargebacks_for_businesses_moving_forward
	// ;";

	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status LIKE 'CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	;";
	
	//logger3("tmp_sql",$tmp_sql);
	$total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	//logger3("$accountid total_CANCELED_for_business",$total_CANCELED_for_business);

	
	    
	// ### CANCELED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND status='CANCELED'
	// AND return_reason NOT LIKE '%CHARGEBACK%'
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND requested_datetime >= '". $datetime_limit_days ."'
	// ;";
	// //logger3("tmp_sql",$tmp_sql);
	// $total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	
	
	
	$total_everthing = $total_CANCELED_for_business + $total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CHARGEBACK_for_business;
	
	if(stristr($display_logging,"YES")) echo "total everything: $total_everthing vs. total transactions: $total_transactions_for_business = ". number_format($total_everthing/$total_transactions_for_business*100) ."%";
	
	if(stristr($display_logging,"YES")) {
	    $tmp_account_details = account($accountid);
	} else {
	    $tmp_account_details['accountname'] = getTHECASHIER("SELECT accountname FROM accounts WHERE accountid = '". $accountid ."';");
	}
	    	
	    	
	    	//$display_logging = "YES";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "<hr>";
	if(stristr($display_logging,"YES")) echo "<b>BUSINESS NAME</b>: ". "<u><b>".$tmp_account_details['accountname']."</b></u> (". $tmp_account_details['accountid'] .")";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "TOTAL TRANSACTIONS: ". $total_transactions_for_business;
	if(stristr($display_logging,"YES")) echo "<br>";
	$percentage_of_network_volume = $total_transactions_for_business / $total_transactions_for_network;
	$percentage_of_network_volume_ii = number_format(100*$percentage_of_network_volume,1);
	if(stristr($display_logging,"YES")) echo "% of B! TRANSACTIONS: <b>". $percentage_of_network_volume_ii."%</b>";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CHARGEBACK: ". number_format($total_CHARGEBACK_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REFUNDED: ". number_format($total_REFUNDED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REVERSED: ". number_format($total_REVERSED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CANCELED: ". number_format($total_CANCELED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	## CB%
	$pCHAREBACK = $total_CHARGEBACK_for_business / $total_transactions_for_business;
	$pCHAREBACK_ii = number_format(100*$total_CHARGEBACK_for_business / $total_transactions_for_business,1);
	
	$chargeback_color = "#009900";
	if($pCHAREBACK_ii > "3.0") $chargeback_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $chargeback_color. ";'><b><u>CHARGEBACK RATE</u>: ". $pCHAREBACK_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	## RF%
	$pREFUNDED = ($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business;
	$pREFUNDED_ii = number_format(100*($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business,1);
	
	$refund_color = "#009900";
	if($pREFUNDED_ii > "3.0") $refund_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $refund_color . ";'><b><u>REFUND RATE</u>: ". $pREFUNDED_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	### APPLY DISCOUNTS:
	$final_REVERSED_for_business = $total_REVERSED_for_business;
	$final_CANCELED_for_business = $total_CANCELED_for_business;
	$final_REFUNDED_for_business = $total_REFUNDED_for_business;
	$final_CHARGEBACK_for_business = $total_CHARGEBACK_for_business;
	# this merges customer cancels and administrative reversals into 1.
	# $final_REVERSED_for_business = $final_REVERSED_for_business + $final_CANCELED_for_business;
	
	### VOLUME_multiplier
	// if($total_transactions_for_business <= "30") {
	// 	logger3("1A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// 	$VOLUME_multiplier = 1.30;
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_multiplier;
	// 	logger3("1B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// }
	
	### VOLUME_discount
	// LESS TO MORE:
	
	//test("total_transactions_for_business",$total_transactions_for_business);

	if($total_transactions_for_business <= "2") {
	    $VOLUME_discount_added = "YES";
	    //test("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.10;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount; // make mot effect cancels
	    //test("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "4") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.20;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    
	} else if($total_transactions_for_business <= "6") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.30;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount0;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    
	} else if($total_transactions_for_business <= "8") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.40;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "10") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.50;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	   
	         
	} else if($total_transactions_for_business <= "12") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.60;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "15") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.70;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
      
	} else if($total_transactions_for_business <= "30") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.80;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	} else if($total_transactions_for_business <= "60") {
	    $VOLUME_discount_added = "YES";
	    //test("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 0.90;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	
	
	
	
	} else if($total_transactions_for_business < "100") {
	    $VOLUME_discount_added = "YES";
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $VOLUME_discount = 1.0;
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	}
	
	
	

	
	
	//$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	
	### CHARGEBACK_discount
	//logger3("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	$raw_chargeback_rate = $final_CHARGEBACK_for_business / $total_transactions_for_business;
	$chargeback_threshhold = "0.05";
	
	if($raw_chargeback_rate <= $chargeback_threshhold) {
	    $CHARGEBACK_discount = 0.66;
	    //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_discount;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_discount;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_discount;
	    //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	}
	
	
	### CHARGEBACK_multiplier
	//logger3("raw_chargeback_rate",$raw_chargeback_rate);
	//logger3("VOLUME_discount_added",$VOLUME_discount_added);
	if(
	(empty($VOLUME_discount_added)) &&
	($raw_chargeback_rate > $chargeback_threshhold)
	) {
	
	    //logger3("3A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	    $CHARGEBACK_multiplier = 5;
	    
	    $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	    $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	    $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	    $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_multiplier;
	    //logger3("3B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	}
	
	// ### 60 DAY GRACE
	// if(strtotime($tmp_account_details['created']) < strtotime($datetime_grace)) {
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	// 	
	// }
	
	// test("9. $accountid final_CANCELED_for_business",$final_CANCELED_for_business);
	// test("9. $accountid final_REVERSED_for_business",$final_REVERSED_for_business);
	// test("9. $accountid final_REFUNDED_for_business",$final_REFUNDED_for_business);
	// test("9. $accountid final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// test("9. $accountid total_transactions_for_business",$total_transactions_for_business);
	
	# $SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_REFUNDED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	# logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	### 2014.05: removed "refunded" -- company policy to NOT have refunds effect the rating in any way.
	$SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	# test("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	
	
	### CHECK REFUND RATE:
	### $SUB_true_refund_rate = ($total_CANCELED_for_business + $total_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_true_refund_rate",$SUB_true_refund_rate);
	### 
	### $SUB_true_refund_rating = number_format(100*(1 - $SUB_true_refund_rate),1);
	### //logger3("888. SUB_true_refund_rating",$SUB_true_refund_rating);
	### $SUB_true_refund_fee = get_dynamic_fee($SUB_true_refund_rating/100);
	### //logger3("888. SUB_true_refund_fee",$SUB_true_refund_fee);
	### 
	### $SUB_final_refund_rate = ($final_CANCELED_for_business + $final_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	### 
	### $SUB_final_refund_rating = number_format(100*(1 - $SUB_final_refund_rate),1);
	### //logger3("888. SUB_final_refund_rating",$SUB_final_refund_rating);
	### $SUB_final_refund_fee = get_dynamic_fee($SUB_final_refund_rating/100);
	### //logger3("888. SUB_finale_refund_fee",$SUB_final_refund_fee);
	

	$final_merchant_rating = number_format(100*(1 - $SUB_final_merchant_rating),1);
	
	//logger3("999. final_merchant_rating",$final_merchant_rating);
	
	$rating_color = "#CC0000";
	if($final_merchant_rating >= "90.00") $rating_color = "#009900";
	//echo "<span style='color:". $rating_color . ";'><b>B! MERCHANT RATING: ". $final_merchant_rating . "% </b></span>";
	//echo "<br>";
	
	$results['merchant_accountid'] = $accountid;
	$results['merchant_name'] = $tmp_account_details['accountname'];
	$results['decimal'] = 1 - number_format($SUB_final_merchant_rating,6);
	$results['percentage'] = $results['satisfied'] = $final_merchant_rating;
	$results['refunded'] = number_format(100 - $final_merchant_rating,1);
	//$results['refund_percentage'] = number_format(100 - $final_merchant_rating,1);
	$results['volume'] = $total_volume_for_business;
	
	$results['total_transactions_count'] = $total_transactions_for_business;
	$results['total_chargebacks_count'] = $total_CHARGEBACK_for_business;
	
	//logger3("ZZZ. accountid $accountid results",$results);
	return $results;
		
}

function get_merchant_rating_2($business_accountid,$start_date='',$limit_date='',$display_logging='') {
	$accountid = $business_accountid;
	$version = "2";
	$personal_or_business = getTHECASHIER("SELECT accounttype WHERE accountid = '". $accountid ."';");
	if(stristr($personal_or_business,"PERSONAL")) return FALSE;

	//logger3("get_merchant_rating(business_accountid=$business_accountid): ",$x);
		

	if(empty($display_logging)) $display_logging = ""; // for algorithm testing
	if(empty($limit_days_ago)) $limit_days_ago = "30";

	### get most recent transaction to establish startdate
	$tmp_sql = "SELECT updated_datetime FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	ORDER BY updated_datetime DESC
	LIMIT 1";
	//logger3("tmp_sql",$tmp_sql);
	$most_recent_transaction_datetime = getTHECASHIER($tmp_sql);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	
	//logger3("dynamic_processing_profile($accountid)",$dynamic_processing_profile);
	
	### if(stristr($dynamic_processing_profile['profile_name'],"PMD")) {
	### 
	### 	global $master_config_gateway_PMD_startdate;
	### 	//logger3("master_config_gateway_PMD_startdate",$master_config_gateway_PMD_startdate);
	### 	
	### 	if($most_recent_transaction_datetime > $master_config_gateway_PMD_startdate) {
	### 		$forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $master_config_gateway_PMD_startdate ."'";
	### 	}
	### 
	### } else {
	### 	
	### 	$forget_about_old_chargebacks_for_businesses_moving_forward = "";
	### 
	### }
	
	//logger3("$accountid: forget_about_old_chargebacks_for_businesses_moving_forward",$forget_about_old_chargebacks_for_businesses_moving_forward);
	
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	logger3("account_details['status_payments']",$account_details['status_payments']);
	
	if(stristr($account_details['status_payments'],"ON")) {
	    //global $master_config_gateway_ECP_startdate
	    global $master_config_gateway_ECP_startdate;
	    global $master_config_gateway_PMD_startdate;

	    $dynamic_processing_profile = get_dynamic_processing_profile($accountid);
	    
	    logger3("dynamic_processing_profile['profile_name'] ",$dynamic_processing_profile['profile_name']);
	    
	
	    $account_gateway_startdate = "master_config_gateway_". $dynamic_processing_profile['profile_name'] ."_startdate";
	    
	    logger3("account_gateway_startdate",$account_gateway_startdate);
	    
	    logger3("$ account_gateway_startdate",$$account_gateway_startdate);
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "AND requested_datetime > '". $$account_gateway_startdate ."'";
	
	} else {
	    
	    $forget_about_old_chargebacks_for_businesses_moving_forward = "";
	}
	
	

	
	
	/// make the PMD exception for new/old clients:
	    	//logger3("most_recent_transaction_datetime",$most_recent_transaction_datetime);
	
	if(empty($start_date)) $start_date = $most_recent_transaction_datetime;
	if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	//logger3("start_date",$start_date);
	if(empty($limit_date)) $limit_date = date("Y-m-d H:i:s",strtotime("-$limit_days_ago days"));
	//logger3("limit_date",$limit_date);
	### $datetime_limit_days = strtotime("-". $limit_days ." days");
	### logger3("datetime_limit_days",$datetime_limit_days);
	### $datetime_limit_days = date("Y-m-d H:i:s",$datetime_limit_days);
	### logger3("datetime_limit_days",$datetime_limit_days);
	### 
	### 
	### ### SET INCOMING:
	### if(empty($start_date)) $start_date = date("Y-m-d H:i:s",time());
	
	
	//exit;
	
	
	
	## GRACE PERIOD:
	$grace_days = "0";
	$datetime_grace = strtotime("-". $grace_days ." days");
	//logger3("datetime_limit_days",$datetime_limit_days);
	$datetime_grace = date("Y-m-d H:i:s",$datetime_grace);
	//logger3("datetime_limit_days",$datetime_limit_days);


	
	// clear previous loop vars:
	$VOLUME_discount_added = "";
	//logger3("accountid",$accountid);
	$accountid = $business_accountid;

	### TRANSACTION SUM
	$tmp_sql = "SELECT SUM(transaction_gross_value) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	logger3("tmp_sql",$tmp_sql);
	
	$total_volume_for_business = getTHECASHIER($tmp_sql);
	logger3("total_volume_for_business",$total_volume_for_business);
	
	### TRANSACTION COUNT
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='APPROVED' OR status='COMPLETED' OR status='REVERSED' OR status='CHARGEBACK' OR status='REFUNDED' OR status='CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	logger3("tmp_sql",$tmp_sql);
	
	$total_transactions_for_business = getTHECASHIER($tmp_sql);
	logger3("total_transactions_for_business",$total_transactions_for_business);

	    
	### CHARGEBACKS FOR BUSINESS:
	### $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	### WHERE accountid = '". $accountid ."'
	### AND description = 'INCOMING' 
	### AND (status='CHARGEBACK' OR return_reason LIKE '%CHARGEBACK%')
	### AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	### AND requested_datetime >= '". $datetime_limit_days ."'
	### ;";
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status='CHARGEBACK')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_CHARGEBACK_for_business = getTHECASHIER($tmp_sql);
	//logger3("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	//$total_CHARGEBACK_for_business = $total_CHARGEBACK_for_business + 0;
	
	### REFUNDED FOR BUSINESS:
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND status='REFUNDED'
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_REFUNDED_for_business = getTHECASHIER($tmp_sql);
	
	
	### REVERSED FOR BUSINESS:
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status LIKE 'REVERSED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_REVERSED_for_business = getTHECASHIER($tmp_sql);
	//logger3("total_REVERSED_for_business",$total_REVERSED_for_business);


	### CANCELED FOR BUSINESS:
	$tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	WHERE platform = 'BANGK.com'
	AND accountid = '". $accountid ."'
	AND description = 'INCOMING' 
	AND (status LIKE 'CANCELED')
	AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	AND (requested_datetime >= '". $limit_date ."' OR return_datetime >= '". $limit_date ."')
	AND (requested_datetime <= '". $start_date ."' OR return_datetime <= '". $start_date ."')
	$forget_about_old_chargebacks_for_businesses_moving_forward
	;";
	//logger3("tmp_sql",$tmp_sql);
	$total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	//logger3("$accountid total_CANCELED_for_business",$total_CANCELED_for_business);

	
	    
	// ### CANCELED FOR BUSINESS:
	// $tmp_sql = "SELECT COUNT(transactionid) FROM transactions
	// WHERE accountid = '". $accountid ."'
	// AND description = 'INCOMING' 
	// AND status='CANCELED'
	// AND return_reason NOT LIKE '%CHARGEBACK%'
	// AND (return_effects_merchant_rating = '' OR return_effects_merchant_rating IS NULL)
	// AND requested_datetime >= '". $datetime_limit_days ."'
	// ;";
	// //logger3("tmp_sql",$tmp_sql);
	// $total_CANCELED_for_business = getTHECASHIER($tmp_sql);
	
	
	
	$total_everthing = $total_CANCELED_for_business + $total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CHARGEBACK_for_business;
	
	if(stristr($display_logging,"YES")) echo "total everything: $total_everthing vs. total transactions: $total_transactions_for_business = ". number_format($total_everthing/$total_transactions_for_business*100) ."%";
	
	if(stristr($display_logging,"YES")) {
	    $tmp_account_details = account($accountid);
	} else {
	    $tmp_account_details['accountname'] = getTHECASHIER("SELECT accountname FROM accounts WHERE accountid = '". $accountid ."';");
	}
	    	
	    	
	    	
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "<hr>";
	if(stristr($display_logging,"YES")) echo "<b>BUSINESS NAME</b>: ". "<u><b>".$tmp_account_details['accountname']."</b></u> (". $tmp_account_details['accountid'] .")";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "TOTAL TRANSACTIONS: ". $total_transactions_for_business;
	if(stristr($display_logging,"YES")) echo "<br>";
	$percentage_of_network_volume = $total_transactions_for_business / $total_transactions_for_network;
	$percentage_of_network_volume_ii = number_format(100*$percentage_of_network_volume,1);
	if(stristr($display_logging,"YES")) echo "% of B! TRANSACTIONS: <b>". $percentage_of_network_volume_ii."%</b>";
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CHARGEBACK: ". number_format($total_CHARGEBACK_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REFUNDED: ". number_format($total_REFUNDED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# REVERSED: ". number_format($total_REVERSED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	if(stristr($display_logging,"YES")) echo "# CANCELED: ". number_format($total_CANCELED_for_business);
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	## CB%
	$pCHAREBACK = $total_CHARGEBACK_for_business / $total_transactions_for_business;
	$pCHAREBACK_ii = number_format(100*$total_CHARGEBACK_for_business / $total_transactions_for_business,1);
	
	$chargeback_color = "#009900";
	if($pCHAREBACK_ii > "3.0") $chargeback_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $chargeback_color. ";'><b><u>CHARGEBACK RATE</u>: ". $pCHAREBACK_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	## RF%
	$pREFUNDED = ($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business;
	$pREFUNDED_ii = number_format(100*($total_REVERSED_for_business + $total_REFUNDED_for_business + $total_CANCELED_for_business) / $total_transactions_for_business,1);
	
	$refund_color = "#009900";
	if($pREFUNDED_ii > "3.0") $refund_color = "#CC0000";
	
	if(stristr($display_logging,"YES")) echo "<span style='color:". $refund_color . ";'><b><u>REFUND RATE</u>: ". $pREFUNDED_ii."% </b></span>";
	if(stristr($display_logging,"YES")) echo "<br>";
	
	
	### APPLY DISCOUNTS:
	$final_REVERSED_for_business = $total_REVERSED_for_business;
	$final_CANCELED_for_business = $total_CANCELED_for_business;
	$final_REFUNDED_for_business = $total_REFUNDED_for_business;
	$final_CHARGEBACK_for_business = $total_CHARGEBACK_for_business;
	# this merges customer cancels and administrative reversals into 1.
	# $final_REVERSED_for_business = $final_REVERSED_for_business + $final_CANCELED_for_business;
	
	### VOLUME_multiplier
	// if($total_transactions_for_business <= "30") {
	// 	logger3("1A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// 	$VOLUME_multiplier = 1.30;
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_multiplier;
	// 	logger3("1B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	// }
	
	### VOLUME_discount
	// LESS TO MORE:
	
	//test("total_transactions_for_business",$total_transactions_for_business);

	### if($total_transactions_for_business <= "2") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.15;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * $VOLUME_discount;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * $VOLUME_discount; // make mot effect cancels
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "4") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.25;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.25;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     
	### } else if($total_transactions_for_business <= "6") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.25;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.25;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     
	### } else if($total_transactions_for_business <= "8") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.35;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.35;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "10") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.25;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.45;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.45;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###    
	###          
	### } else if($total_transactions_for_business <= "12") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.55;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.55;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "15") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.65;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.65;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
    ###   
	### } else if($total_transactions_for_business <= "30") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.75;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.75;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### } else if($total_transactions_for_business <= "60") {
	###     $VOLUME_discount_added = "YES";
	###     //test("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.50;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 0.90;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 0.90;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### 
	### 
	### 
	### 
	### } else if($total_transactions_for_business < "100") {
	###     $VOLUME_discount_added = "YES";
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $VOLUME_discount = 0.80;
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $VOLUME_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $VOLUME_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * 1.0;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * 1.0;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### }
	
	
	

	
	
	//$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	
	### ### CHARGEBACK_discount
	### //logger3("total_CHARGEBACK_for_business",$total_CHARGEBACK_for_business);
	### $raw_chargeback_rate = $final_CHARGEBACK_for_business / $total_transactions_for_business;
	### $chargeback_threshhold = "0.05";
	### 
	### if($raw_chargeback_rate <= $chargeback_threshhold) {
	###     $CHARGEBACK_discount = 0.66;
	###     //logger3("2A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_discount;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_discount;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_discount;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_discount;
	###     //logger3("2B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### }
	
	
	### ### CHARGEBACK_multiplier
	### //logger3("raw_chargeback_rate",$raw_chargeback_rate);
	### //logger3("VOLUME_discount_added",$VOLUME_discount_added);
	### if(
	### (empty($VOLUME_discount_added)) &&
	### ($raw_chargeback_rate > $chargeback_threshhold)
	### ) {
	### 
	###     //logger3("3A. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	###     $CHARGEBACK_multiplier = 5;
	###     
	###     $final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	###     $final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	###     $final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	###     $final_CANCELED_for_business = $final_CANCELED_for_business * $CHARGEBACK_multiplier;
	###     //logger3("3B. final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	### }
	
	// ### 60 DAY GRACE
	// if(strtotime($tmp_account_details['created']) < strtotime($datetime_grace)) {
	// 	$final_CHARGEBACK_for_business = $final_CHARGEBACK_for_business * $CHARGEBACK_multiplier;
	// 	$final_REFUNDED_for_business = $final_REFUNDED_for_business * $CHARGEBACK_multiplier;
	// 	$final_REVERSED_for_business = $final_REVERSED_for_business * $CHARGEBACK_multiplier;
	// 	
	// }
	
	logger3("9. $accountid final_CANCELED_for_business",$final_CANCELED_for_business);
	logger3("9. $accountid final_REVERSED_for_business",$final_REVERSED_for_business);
	logger3("9. $accountid final_REFUNDED_for_business",$final_REFUNDED_for_business);
	logger3("9. $accountid final_CHARGEBACK_for_business",$final_CHARGEBACK_for_business);
	logger3("9. $accountid total_transactions_for_business",$total_transactions_for_business);
	
	# $SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_REFUNDED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	# logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	### 2014.05: removed "refunded" -- company policy to NOT have refunds effect the rating in any way.
	$SUB_final_merchant_rating = ($final_CANCELED_for_business + $final_REVERSED_for_business + $final_CHARGEBACK_for_business) / $total_transactions_for_business;
	logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	
	
	
	### CHECK REFUND RATE:
	### $SUB_true_refund_rate = ($total_CANCELED_for_business + $total_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_true_refund_rate",$SUB_true_refund_rate);
	### 
	### $SUB_true_refund_rating = number_format(100*(1 - $SUB_true_refund_rate),1);
	### //logger3("888. SUB_true_refund_rating",$SUB_true_refund_rating);
	### $SUB_true_refund_fee = get_dynamic_fee($SUB_true_refund_rating/100);
	### //logger3("888. SUB_true_refund_fee",$SUB_true_refund_fee);
	### 
	### $SUB_final_refund_rate = ($final_CANCELED_for_business + $final_REVERSED_for_business) / $total_transactions_for_business;
	### //logger3("888. SUB_final_merchant_rating",$SUB_final_merchant_rating);
	### 
	### $SUB_final_refund_rating = number_format(100*(1 - $SUB_final_refund_rate),1);
	### //logger3("888. SUB_final_refund_rating",$SUB_final_refund_rating);
	### $SUB_final_refund_fee = get_dynamic_fee($SUB_final_refund_rating/100);
	### //logger3("888. SUB_finale_refund_fee",$SUB_final_refund_fee);
	

	$final_merchant_rating = number_format(100*(1 - $SUB_final_merchant_rating),1);
	
	//logger3("999. final_merchant_rating",$final_merchant_rating);
	
	$rating_color = "#CC0000";
	if($final_merchant_rating >= "90.00") $rating_color = "#009900";
	//echo "<span style='color:". $rating_color . ";'><b>B! MERCHANT RATING: ". $final_merchant_rating . "% </b></span>";
	//echo "<br>";
	
	$results['merchant_accountid'] = $accountid;
	$results['merchant_name'] = $tmp_account_details['accountname'];
	$results['decimal'] = 1 - number_format($SUB_final_merchant_rating,6);
	$results['percentage'] = $results['satisfied'] = $final_merchant_rating;
	$results['refunded'] = number_format(100 - $final_merchant_rating,1);
	//$results['refund_percentage'] = number_format(100 - $final_merchant_rating,1);
	$results['volume'] = $total_volume_for_business;
	
	$results['total_transactions_count'] = $total_transactions_for_business;
	$results['total_chargebacks_count'] = $total_CHARGEBACK_for_business;
	
	//logger3("ZZZ. accountid $accountid results",$results);
	return $results;
		
}



function format_phone_number($phone_number) {

	if(empty($phone_number)) return FALSE;
	
	$tmp_return = explode("/",$phone_number);
	
	if(empty($tmp_return[1])) return FALSE;
	
	
	$return['calling_code'] = $tmp_return[0];
	$return['local_number'] = $tmp_return[1];
	
	$split_local_number = str_split($tmp_return[1]);
	
	if($split_local_number[0] == "0"){
		$final_local_number = substr($tmp_return[1],1);
	} else {
		$final_local_number = $tmp_return[1];
	}
	
	$return['local_number'] = $final_local_number;
	$return['phone_number'] = $tmp_return[0] . $final_local_number;
	
	$return[0] = $return['calling_code'];
	$return[1] = $final_local_number;
	$return[2] = $tmp_return[0] . $final_local_number;

	
	return $return;
}

function luhn_check($number) {

  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
  $number=preg_replace('/\D/', '', $number);

  // Set the string length and parity
  $number_length=strlen($number);
  $parity=$number_length % 2;

  // Loop through each digit and do the maths
  $total=0;
  for ($i=0; $i<$number_length; $i++) {
    $digit=$number[$i];
    // Multiply alternate digits by two
    if ($i % 2 == $parity) {
      $digit*=2;
      // If the sum is two digits, add them together (in effect)
      if ($digit > 9) {
        $digit-=9;
      }
    }
    // Total up the digits
    $total+=$digit;
  }

  // If the total mod 10 equals 0, the number is valid
  return ($total % 10 == 0) ? TRUE : FALSE;

}


function get_business_type_extensions() {
	
	$results = "";
	$results = array();
	$tmp_sql = "SELECT extensionid FROM business_type_extensions;";
	$extensionid_array = arrayTHECASHIER($tmp_sql);
	//test("extensionid_array",$extensionid_array);
	
	foreach($extensionid_array as $key => $extensionid) {
		$tmp_sql = "SELECT * FROM business_type_extensions WHERE extensionid = '".$extensionid."';";
		$results[$key] = object2array(readTHECASHIER($tmp_sql));
	}
	return $results;
}




function getPendingIdentityClaims($accountid=null) {

	if(!empty($accountid)) $possible_accountid_specification = "AND accountid = '". $accountid ."';";

	### RESET COUNTER PER FUNCTION:
	$results = "";
	$results['pending_counter'] = "";
	$x = 0;
	$y = 0;



	########################################################
	### PERSONAL IDENTITY
	########################################################
	
	
	# $tmp_sql = "SELECT a.*
	# FROM ids_personal a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_personal
	# WHERE 
	# (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
	# AND 
	# (proof_of_residence_filename = '' OR proof_of_residence_filename IS NULL)
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";
	# logger3("tmp_sql",$tmp_sql);
	
	// $tmp_sql = "SELECT * FROM ids_personal
	// 			WHERE (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			ORDER BY datetime_updated ASC
	// 			;";
	


	$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_personal
				WHERE (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
	//test("tmp_sql",$tmp_sql);
	
	
	
	$results['pending_personal_identity'] = object2array(readarrayTHECASHIER($tmp_sql));
	//test("results['pending_personal_identity']",$results['pending_personal_identity']);
	//exit;
	
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_personal_identity']));
	
	//$x = 0;
	foreach($results['pending_personal_identity'] as $key => $id) {
		$results['array'][$y] = $results['pending_personal_identity'][$key];
		if(!empty($results['array'][$y])) $y++;
		
	}
	
	
	
	########################################################
	### PERSONAL LOCATION
	########################################################
	
	
	# $tmp_sql = "SELECT a.*
	# FROM ids_personal a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_personal
	# WHERE 
	# (photo_id_filename = '' OR photo_id_filename IS NULL)
	# AND 
	# (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";

	// $tmp_sql = "SELECT * FROM ids_personal
	// 			WHERE (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			ORDER BY datetime_updated ASC
	// 			;";
	

	
	$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_personal
				WHERE (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
				
	//test("tmp_sql",$tmp_sql);
	
	$results['pending_personal_location'] = object2array(readarrayTHECASHIER($tmp_sql));
	//test("results['pending_personal_location']",$results['pending_personal_location']);
	
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_personal_location']));

	//$x = 0;
	foreach($results['pending_personal_location'] as $key => $id) {
		$results['array'][$y] = $results['pending_personal_location'][$key];
		if(!empty($results['array'][$y])) $y++;
	}
	
	
	########################################################
	### BUSINESS IDENTITY
	########################################################
	# $tmp_sql = "SELECT a.*
	# FROM ids_business a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_business
	# WHERE 
	# 
	# (
	# (
	# (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
	# AND 
	# (proof_of_business_location_filename = '' OR proof_of_business_location_filename IS NULL)
	# )
	# OR business_legal_extension = 'PDBA'
	# )
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";
	//test("tmp_sql",$tmp_sql);

	// $tmp_sql = "SELECT * FROM ids_business
	// 			WHERE (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			ORDER BY datetime_updated ASC
	// 			;";
	
	$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_business
				WHERE (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				
				AND business_legal_extension NOT LIKE '%DBA'
				AND business_legal_extension != 'GROUP'
				
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
	
	//test("tmp_sql",$tmp_sql);
	
	
	$results['pending_business_identity'] = object2array(readarrayTHECASHIER($tmp_sql));
	
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_business_identity']));
	
	
	//test("results['pending_business_identity']",$results['pending_business_identity']);
	
	## CHECK TO MAKE SURE PERSONAL IDS ARE VERIFIED BEFORE PDBA's CAN BE COUNTED-IN
	# $x = 0;
	# $force_show = 1;
	# 
	# if(!empty($force_show)) {
	# 	$new_pending_business_identity_array = "";
	# 	foreach($results['pending_business_identity'] as $key => $business_id_details) {
	# 		
	# 		//test("business_id_details",$business_id_details);
	# 		
	# 		//$tmp_claim_details = object2array(readTHECASHIER("SELECT * FROM ids_business WHERE idid = '". $business_id_details['idid'] ."';"));
	# 		$member_owener_details = member($business_id_details['memberid']);
	# 		//test("member_owener_details['verified']",$member_owener_details['verified']);
	# 		
	# 		if(
	# 		(!empty($member_owener_details['verified']['identity']['hash'])) &&
	# 		(!empty($member_owener_details['verified']['location']['hash']))
	# 		) {
	# 		   //test("member_owener_details['verified']['location']['hash']",$member_owener_details['verified']['location']['hash']);
	# 		   
	# 		   $new_pending_business_identity_array[$x] = $tmp_claim_details;
	# 		   if(!empty($results['array'][$x])) $x++;
	# 		}
	# 		
	# 		//$new_pending_business_identity_array[$x] = $tmp_claim_details;
	# 		//if(!empty($results['array'][$x])) $x++;
	# 	}
	# 	
	# 	$results['pending_business_identity'] = "";
	# 	$results['pending_business_identity'] = $new_pending_business_identity_array;
	# }
	# 
	# $results['pending_counter'] = $results['pending_counter'] + count($results['pending_business_identity']);
	# 
	# //test("results['pending_business_identity']",$results['pending_business_identity']);
	
	
	
	
	
	foreach($results['pending_business_identity'] as $key => $id) {
		$results['array'][$y] = $results['pending_business_identity'][$key];
		if(!empty($results['array'][$y])) $y++;
	}
	
	
	########################################################
	### BUSINESS LOCATION
	########################################################
	# $tmp_sql = "SELECT a.*
	# FROM ids_business a
	# INNER JOIN
	# (
	# SELECT *, MAX(datetime_created) maxDateCreated
	# FROM ids_business
	# WHERE 
	# (business_certificate_filename = '' OR business_certificate_filename IS NULL)
	# AND 
	# (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
	# AND
	# (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	# GROUP BY memberid
	# ) b ON 
	# a.memberid = b.memberid AND
    # a.datetime_created = b.maxDateCreated
	# ;
	# ";
	
	
	// $tmp_sql = "SELECT * FROM ids_business
	// 			WHERE (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 			AND (business_legal_extension NOT LIKE '%DBA%' AND business_legal_extension != 'GROUP') 
	// 			ORDER BY datetime_updated ASC
	// 			;";

	// $tmp_sql = "SELECT * FROM (
	// 			SELECT * FROM ids_business
	// 			WHERE (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
	// 			AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
	// 
	// 			AND business_legal_extension NOT LIKE '%DBA'
	// 			AND business_legal_extension != 'GROUP'
	// 			
	// 			ORDER BY datetime_updated DESC
	// 			) AS t
	// 			GROUP BY t.memberid
	// 			ORDER BY datetime_updated ASC";
$tmp_sql = "SELECT * FROM (
				SELECT * FROM ids_business
				WHERE (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
				AND (status LIKE '%HOLD%' OR status = 'SUBMITTED')
				
				AND business_legal_extension != 'PDBA'
				AND business_legal_extension != 'CDBA'
				AND business_legal_extension != 'GROUP'
				
				ORDER BY datetime_updated DESC
				) AS t
				GROUP BY t.memberid
				ORDER BY datetime_updated ASC";
				
	//test("tmp_sql",$tmp_sql);
	
	$results['pending_business_location'] = object2array(readarrayTHECASHIER($tmp_sql));
	
	//test("results['pending_business_location']",$results['pending_business_location']);
	
	//if(empty($force_show)) {
	$results['pending_counter'] = $results['pending_counter'] + count(array_keys($results['pending_business_location']));



	foreach($results['pending_business_location'] as $key => $id) {
		$results['array'][$y] = $results['pending_business_location'][$key];
		if(!empty($results['array'][$y])) $y++;
	}
	
	
	### POSSIBLE PDBA CLAIM
	// $tmp_sql = "SELECT a.*
	// FROM ids_business a
	// INNER JOIN
	// (
	// SELECT *, MAX(datetime_created) maxDateCreated
	// FROM ids_business
	// WHERE 
	// (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
	// AND 
	// (proof_of_business_location_filename = '' OR proof_of_business_location_filename IS NULL)
	// AND
	// (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	// GROUP BY memberid
	// ) b ON 
	// a.memberid = b.memberid AND
    // a.datetime_created = b.maxDateCreated
	// ;
	// ";
	// $tmp_sql = "SELECT * FROM ids_business
	//     		WHERE (status = 'SUBMITTED' OR status LIKE '%HOLD%')
	//     		AND business_legal_extension = 'PDBA'
	//     		";
	//     		
	// //test("tmp_sql",$tmp_sql);
	// $results['pending_business_identity'] = object2array(readarrayTHECASHIER($tmp_sql));
	// $results['pending_counter'] = $results['pending_counter'] + count($results['pending_business_identity']);
	// //test("results",$results);
	// 
	// foreach($results['pending_business_identity'] as $key => $id) {
	//     $results['array'][$x] = $results['pending_business_identity'][$key];
	//     $x++;
	// }
	
	
	
	
	
	
	//test("results['array']",$results['array']);
	
	$results['pending_counter'] = $results['pending_counter'];
	if($results['pending_counter'] < 1) $results['pending_counter'] = "0";
	
	return $results;
	
}


function get_cdba_parent($accountid) {

	
	$verified_business_details = "";
	
	//$account_details = account($accountid);
	$account_details = object2array(readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';"));
	
	## VERIFIED:
	
	# $tmp_sql = "SELECT * FROM ids_business 
	# WHERE
	# accountid = '". $account_details['accountid'] ."'
	# AND business_name = '". $account_details['accountname'] ."' 
	# AND business_legal_extension = '".$account_details['business_type']."' 
	# AND status = 'VERIFIED'
	# ORDER BY datetime_created DESC;
	# ";

	$tmp_sql = "SELECT * FROM ids_business 
	WHERE
	accountid = '". $account_details['accountid'] ."'
	AND business_legal_extension = '".$account_details['business_type']."' 
	AND status = 'VERIFIED'
	ORDER BY datetime_created DESC;
	";
	logger3("tmp_sql",$tmp_sql);
	
	$verified_business_details = readTHECASHIER($tmp_sql);
	logger3("verified_business_id",$verified_business_id);
	
	
	if(empty($verified_business_details)) {
	
	
		### PENDING:
		//$tmp_sql = "SELECT * FROM ids_business 
		//WHERE
		//accountid = '".$account_details['accountid']."'
		//AND business_name = '".$account_details['accountname']."' 
		//AND business_legal_extension = '".$account_details['business_type']."' 
		//AND (status = 'SUBMITTED' OR status LIKE '%HOLD%')
		//ORDER BY datetime_created DESC;
		//";

		$tmp_sql = "SELECT * FROM ids_business 
		WHERE
		accountid = '".$account_details['accountid']."'
		AND business_legal_extension = '".$account_details['business_type']."' 
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%')
		ORDER BY datetime_created DESC;
		";
		logger3("tmp_sql",$tmp_sql);
		
		$verified_business_details = readTHECASHIER($tmp_sql);
		logger3("verified_business_details",$verified_business_details);
	}
	
	return $verified_business_details->parent_account_hash;

}


function get_list_of_valid_bank_account_claims() {
	
	$tmp_sql = "SELECT * FROM wallets 
				WHERE type = 'SWIFT' 
				AND (status = 'SUBMITTED' OR status LIKE '%HOLD%')
				ORDER BY datetime_updated ASC
				;";
	//test("tmp_sql",$tmp_sql);
	//$walletid_array = object2array(arrayTHECASHIER($tmp_sql));
	//test("walletid_array",$walletid_array);
	$wallet_array_details = readarrayTHECASHIER($tmp_sql);
	
	
	
	$valid_counter = 0;
	foreach($wallet_array_details as $key => $row) {
	
		// $tmp_sql = "SELECT * FROM wallets WHERE walletid = '".$walletid."';";
		// //test("tmp_sql",$tmp_sql);
		// $wallet_details = object2array(readTHECASHIER($tmp_sql));
		// //test("wallet_details",$wallet_details);
		
		
		//$parent_account_details = object2array(readTHECASHIER("SELECT * FROM account WHERE hash = '". $row['banking_account_owner_account_hash'] ."';"));
		// account($row['banking_account_owner_account_hash']);
		//test("parent_account_details",$parent_account_details);
		
		
		//$parent_member_details = member($row['memberid']);
		//test("parent_member_details",$parent_account_details);
		
		
		
		$business_type = getTHECASHIER("SELECT business_type FROM accounts WHERE accountid = '". $row['accountid'] ."';");
		//if($row['accountid'] == 5889) test("business_type",$business_type);
		
		$ids_personal = get_ids_personal($memberid=$row['memberid'],$accountid='');
		//if($row['accountid'] == 5889) test("ids_personal",$ids_personal);
		
		if(!stristr($business_type,"PDBA")) {
			$ids_business = get_ids_business($memberid='',$accountid=$row['accountid']);
		} else {
			$ids_business = $ids_personal;
		}
		//if($row['accountid'] == 5889) test("ids_business",$ids_business);
		
		if(
		
		(stristr($ids_personal['current']['identity']['status'],"VERIFIED")) &&
		(stristr($ids_personal['current']['location']['status'],"VERIFIED")) &&
		
		(stristr($ids_business['current']['identity']['status'],"VERIFIED")) &&
		(stristr($ids_business['current']['location']['status'],"VERIFIED"))
		
		) {
			
			$valid_claim_array[$valid_counter] = $row;
			$valid_counter++;
		
		}
	}
	
	$return['count'] = $valid_counter;
	$return['array_details'] = $valid_claim_array;
	//test("return['array_details']",$return['array_details']);
	return $return;
}




function get_account_DTR($accountid) {
	
	
	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	if(empty($accountid)) return FALSE;
	## 
	## $tmp_sql = "SELECT * FROM accounts WHERE accountid = '". $accountid ."';";
	## $tmp_acocunt_details = object2array(readTHECASHIER($tmp_sql));
	## 
	## //test("tmp_acocunt_details",$tmp_acocunt_details);
	## 
	## /// ECP
	## if(
	## (stristr($tmp_acocunt_details['sponsor_accountid'],"b7e9aac09c099d4bfe5cfc85917df9e3")) ||
	## (stristr($tmp_acocunt_details['fee_and_schedule_profile']['cc_gateway'],"ECP"))
	## ) {
	## 	
	## 	return "20";
	## 
	## } else {
	## 	
	## 	return "30";	
	## 	
	## }
	
	return get_dynamic_DTR($accountid);
	
	
	
	
}

function get_list_of_withdrawal_requests($show='') {
	
	# $results = "";
	# $results = array();
	# 
	# $tmp_sql = "SELECT transactionid FROM transactions WHERE description = 'WITHDRAWAL' AND (status = 'APPROVED' OR status LIKE '%HOLD%') ORDER BY updated_datetime ASC;";
	# //test("tmp_sql",$tmp_sql);
	# 
	# $pending_withdrawal_transactionid_array = arrayTHECASHIER($tmp_sql);
	# //test("pending_withdrawal_transactionid_array",$pending_withdrawal_transactionid_array);
	# 
	# $x = 0;
	# foreach($pending_withdrawal_transactionid_array as $key => $transactionid) {
	# 	
	# 	$verified_walletid = "";
	# 	$transaction_details = transaction($transactionid);
	# 	
	# 	
	# 	$tmp_sql = "SELECT walletid FROM wallets 
	# 	WHERE 
	# 	walletid = '".$transaction_details['walletid']."'
	# 	AND status = 'VERIFIED'
	# 	;";
	# 	//test("tmp_sql",$tmp_sql);
	# 	$verified_walletid = getTHECASHIER($tmp_sql);
	# 	//test("verified_walletid",$verified_walletid);
	# 	
	# 	if(!empty($verified_walletid)) { // DISPLAY A FINAL TOTAL VALUE TO CASHOUT
	# 	
	# 		$results['transactionid_array'][$x] = $transactionid;
	# 	
	# 		//$results[$x] = $transaction_details;
	# 		$results['gross_total'] = currency_format($results['gross_total'] + $transaction_details['transaction_gross_value']);
	# 		$x++;
	# 		
	# 	}
	# 	
	# 	
	# }
	# 
	# if(count($results) > 0) {
	# 	$results['count'] = count($results)-1; // subtract one for gross total of actual records.
	# } else {
	# 	$results['count'] = "0";
	# }
	# 
	# return $results;
	
	
	

	if($show == "gsp") { // shows pending withdrawals form GSP meltdown
		$tmp_sql = "SELECT * FROM transactions 
				WHERE description = 'WITHDRAWAL'
				AND (status = 'APPROVED' OR status LIKE '%HOLD%')
				AND requested_datetime > '2014-03-10 01:00:00'
				ORDER BY updated_datetime ASC;";
	} else {
		$tmp_sql = "SELECT * FROM transactions 
				WHERE description = 'WITHDRAWAL'
				AND (status = 'APPROVED' OR status LIKE '%HOLD%')
				AND requested_datetime > '2014-03-10 01:00:00'
				AND requested_datetime NOT LIKE '%2014-05-20%'
				ORDER BY updated_datetime ASC;";
	}

	//test("tmp_sql",$tmp_sql);
	$transaction_list_array = readarrayTHECASHIER($tmp_sql);
	
	
	//test("transaction_list_array",$transaction_list_array); 
	//exit;
	
	//$get_list_of_withdrawal_requests = get_list_of_withdrawal_requests();
	//$transactionids_array =  $get_list_of_withdrawal_requests$transactionids_array;
	

	$results = "";
	$results = array();
	$results['sum_total'] = "0.00";
	
	
	$x = 0;
	foreach($transaction_list_array as $key => $transaction_details) {
		

		//test("transaction_details",$transaction_details);
		//exit;
		
		
			
		//$transaction_details = transaction($trasnactionid);

		//test("transaction_details ($key)",$transaction_details);
		//test("transaction_details['transaction_gross_value']",$transaction_details['transaction_gross_value']);
		
		//test("transaction_details['accountid']",$transaction_details['accountid']);
		
		$ids_business_details = get_ids_business($memberid='',$accountid=$transaction_details['accountid']); // ($transaction_details['accountid']);
		//test("ids_business_details",$ids_business_details);
		//exit;
		
		
		//test("account_details",$account_details);
		//test("account_details['verified']",$account_details['verified']);
		
		//$parent_details = get_parent_details($transaction_details['accountid']);
		//test("parent_details",$parent_details);
		
		$ids_personal_details = get_ids_personal($memberid=$transaction_details['memberid'],$accountid='');
		//test("ids_personal_details",$ids_personal_details);
		//exit;
		
		# 
		# $tmp_sql = "SELECT walletid FROM wallets WHERE memberid = '".$transaction_details['memberid']."' AND accountid = '".$transaction_details['accountid']."' AND status = 'VERIFIED' AND type = 'SWIFT';";
		# #test("tmp_sql",$tmp_sql);
		# $walletid = getTHECASHIER($tmp_sql);
		# 
		# $walletid = $transaction_details['walletid'];
		
		
		// walletid = "";
		// $tmp_sql = "SELECT * FROM wallets 
		// 			WHERE walletid = '".$transaction_details['walletid']."'
		// 			AND status = 'VERIFIED'
		// ;";
		// //test("tmp_sql",$tmp_sql);
		// $wallet_details = readTHECASHIER($tmp_sql);
		// //test("wallet_details",$wallet_details);
		
		$wallet_details = wallet($transaction_details['walletid']);
		//test("wallet_details",$wallet_details);
				
		// if(stristr($verified_wallet_details['status'],"VERIFIED")) {
		// 
		// 	$walletid = $verified_wallet_details['hash'];
		// 	
		// } else {
		//     
		//     // $tmp_sql = "SELECT hash FROM wallets
		//     // WHERE accountid = '". $account_details['accountid'] ."'
		//     // AND type = 'SWIFT'
		//     // AND status = 'VERIFIED'
		//     // ORDER BY datetime_updated DESC
		//     // LIMIT 1
		//     // ;";
		//    /// / test("tmp_sql",$tmp_sql);
		//     // $walletid = getTHECASHIER($tmp_sql);
		//    /// / test("walletid",$walletid);
		//    
		//    
		//    $verified_wallet_details = get_bank_account($account_details['accountid']);
		//    //test("verified_wallet_details",$verified_wallet_details);
		//    
		//    $walletid = $verified_wallet_details['verified']['hash'];
		//     
		// }
		
		
			
		//test("walletid",$walletid);
		//test("member_details['verified']['identity']['hash']",$member_details['verified']['identity']['hash']);
		//test("member_details['verified']['location']['hash']",$member_details['verified']['location']['hash']);
		//test("acocunt_details['verified']['identity']['hash']",$account_details['verified']['identity']['hash']);
		//test("account_details['verified']['location']['hash']",$account_details['verified']['location']['hash']);
		
		
		if($show != "gsp") {
		
			if(
			(stristr($ids_personal_details['current']['identity']['status'],"VERIFIED")) &&
			(stristr($ids_personal_details['current']['location']['status'],"VERIFIED")) &&
			
			(stristr($ids_business_details['current']['identity']['status'],"VERIFIED")) &&
			(stristr($ids_business_details['current']['location']['status'],"VERIFIED")) &&
			
			(stristr($wallet_details['status'],"VERIFIED"))
			
			) { 
				//test("tmp_sql",$walletid);
				//test("yay!",$trasnactionid);
				
				//test("$x : transaction_details",$transaction_details);
				
				//$transaction_details = transaction($trasnactionid);
				$clean_transaction_list_array[$x] = $transaction_details;
				$results['sum_total'] = currency_format($results['sum_total'] + $transaction_details['transaction_net_value']);
				$transaction_details = "";
				$x++;	
				
				
			}
		} else {
			
			$clean_transaction_list_array[$x] = $transaction_details;
			$results['sum_total'] = currency_format($results['sum_total'] + $transaction_details['transaction_net_value']);
			$transaction_details = "";
			$x++;	
				
		}
		
		
	}

	//exit; // foreach();
	
	
	
	
	$results['count']  = count($clean_transaction_list_array);
	if(empty($results['count'])) $results['count'] = "0";
	$results['clean_transaction_list_array'] = $clean_transaction_list_array;
	
	/// legacy
	$results['gross_total'] = $results['sum_total']; 
	//$results['transactionid_array'] = $results['transactionids'];
	
	
	//exit;
	
	//test("results",$results);
	
	return $results;
	
	
}





function wallet($wallet_id) {

	if(strlen($wallet_id) > 30) {
	
		$tmp_sql = "SELECT * FROM wallets WHERE hash LIKE '". $wallet_id ."';";
	
	} else {
	
		$tmp_sql = "SELECT * FROM wallets WHERE walletid = '".$wallet_id."';";
	
	}

	$wallet_details = object2array(readTHECASHIER($tmp_sql));

	return $wallet_details;

}




function getFeeScheduleProfileDetails($profile_name) {
	$tmp_sql = "SELECT  * FROM fee_and_schedule_profiles WHERE profile_name = '".$profile_name."';";
	return object2array(readTHECASHIER($tmp_sql));
}


function getActiveSWIFT($accountid='',$memberid='') {
	
	if( !empty($memberid) && !empty($accountid) ) {
		$tmp_sql = "SELECT * FROM wallets WHERE accountid = '". $accountid ."' AND memberid = '".$memberid."' AND type = 'SWIFT' AND (status = 'VERIFIED' OR status = 'SUBMITTED' OR status LIKE '%HOLD%') ORDER BY datetime_updated DESC LIMIT 1;";
	} else if( !empty($accountid) ) {
		$tmp_sql = "SELECT * FROM wallets WHERE accountid = '". $accountid ."' AND type = 'SWIFT' AND (status = 'VERIFIED' OR status = 'SUBMITTED' OR status LIKE '%HOLD%') ORDER BY datetime_updated DESC LIMIT 1;";
	} else {
		return FALSE;
	}
	
	
	
	//test("tmp_sql",$tmp_sql);
	$swift_details = object2array(readTHECASHIER($tmp_sql));
	
	$swift_details['account_number_LAST4_digits'] = substr($swift_details['banking_account_number'],4);
	
	return $swift_details;
	
}


function get_personal_identity($accountid='',$memberid='') {

	//if(empty($accountid)) $_SESSION['member']['memberid']
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	
	### CHECK VIA ACCOUNT LOOK-UP:
	
	$tmp_sql = "SELECT accountid FROM accounts 
				WHERE creator_memberid = '". $_SESSION['member']['memberid'] . "' 
				AND accounttype = 'PERSONAL'
				;";
	if(empty($accountid)) $accountid = getTHECASHIER($tmp_sql);
	
	//test("accountid",$accountid);
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				AND (status = 'SUBMITTED' OR status = 'VERIFIED' or status LIKE '%HOLD%')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);

	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['status_details']",$results['status_details']);
	
	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['current'])) {
		
		
		
		
		$tmp_sql = "SELECT * FROM ids_personal 
					WHERE memberid = '". $memberid . "' 
					AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
					AND (status = 'SUBMITTED' OR status = 'VERIFIED' or status LIKE '%HOLD%')
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['current'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['current']",$results['current']);


		$tmp_sql = "SELECT * FROM ids_personal 
		    		WHERE accountid = '". $accountid . "' 
		    		AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
		    		ORDER BY datetime_updated DESC
		    		LIMIT 1
		    		;";
		//test("tmp_sql",$tmp_sql);
		$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['status_details']",$results['status_details']);
	
	}
	
	
	### CHECK VIA ACCOUNT LOOK-UP:
	$tmp_sql = "SELECT * FROM ids_personal
				WHERE accountid = '". $accountid . "' 
				AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);

	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['verified'])) {
	
		### CHECK VIA ACCOUNT LOOK-UP:
		$tmp_sql = "SELECT * FROM ids_personal
					WHERE memberid = '". $memberid . "' 
					AND (photo_id_filename != '' AND photo_id_filename IS NOT NULL)
					AND (status = 'VERIFIED')
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['verified'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
	
	}
	
	//test("get_personal_identity() results",$results);
	return $results;
	
}

function get_personal_location($accountid='',$memberid='') {

	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];

	$tmp_sql = "SELECT accountid FROM accounts 
				WHERE creator_memberid = '". $_SESSION['member']['memberid'] . "' 
				AND accounttype = 'PERSONAL'
				;";
	if(empty($accountid)) $accountid = getTHECASHIER($tmp_sql);
	
	//$tmp_account_details = account($accountid);
	//$tmp_member_details = member($tmp_account_details['creator_memberid']);
	
	############################################
	### CURRENT: 
	############################################
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);
	
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['status_details']",$results['status_details']);
	
	
	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['current'])) {
	
	
		$tmp_sql = "SELECT * FROM ids_personal 
					WHERE memberid = '". $memberid . "' 
					AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['current'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['current']",$results['current']);

		$tmp_sql = "SELECT * FROM ids_personal 
		    		WHERE memberid = '". $memberid . "' 
		    		AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
		    		ORDER BY datetime_updated DESC
		    		LIMIT 1
		    		;";
		//test("tmp_sql",$tmp_sql);
		$results['status_details'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['status_details']",$results['status_details']);
	
	}
	
	
	
	############################################
	### VERIFIED:
	############################################
	
	$tmp_sql = "SELECT * FROM ids_personal 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);

	### THEN CHECK MEMBER DIRECTLY:
	
	if(empty($results['verified'])) {
	
		$tmp_sql = "SELECT * FROM ids_personal 
					WHERE memberid = '". $memberid . "' 
					AND (proof_of_residence_filename != '' AND proof_of_residence_filename IS NOT NULL)
					AND (status = 'VERIFIED')
					ORDER BY datetime_updated DESC
					LIMIT 1
					;";
		//test("tmp_sql",$tmp_sql);
		$results['verified'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
	
	}
	
	//test("get_personal_location(): results",$results);
	return $results;
	
	
}


function get_business_identity($accountid='',$memberid='') {
	
	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	//test("accountid",$accountid);
	$tmp_account_details = account($accountid);
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	//test("memberid",$memberid);
	$tmp_member_details = member($memberid);
	

	
	$tmp_sql = "SELECT * FROM ids_business 
				WHERE accountid = '". $accountid . "' 
				AND (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);
	
	$tmp_sql = "SELECT * FROM ids_business
				WHERE accountid = '". $accountid . "' 
				AND (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);
	
	
	//test("results['current']['business_legal_extension']",$esults['current']['business_legal_extension']);
	
	//test("_SESSION['account']",$_SESSION['account']);
	### IF IT"S A DBA/GROUP = check the member
	if(
	(stristr($tmp_account_details['business_type'],"DBA")) ||
	(stristr($tmp_account_details['business_type'],"GROUP"))
	) {


		### VERIFIED IDENTITY
		$tmp_sql = "SELECT * FROM ids_business
		WHERE accountid = '". $accountid . "' 
		AND (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		AND business_name = '". $tmp_account_details['accountname'] ."'
		ORDER BY datetime_updated DESC
		LIMIT 1
		;";
		//test("tmp_sql",$tmp_sql);
		$results['verified'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
		$results['verified']['status'] = $tmp_member_details['current']['identity']['status'];



		### CURRENT IDENTITY
		$tmp_sql = "SELECT * FROM ids_business
		WHERE accountid = '". $accountid . "' 
		AND (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
		ORDER BY datetime_updated DESC
		LIMIT 1
		;";
		//test("tmp_sql",$tmp_sql);
		$results['current'] = object2array(readTHECASHIER($tmp_sql));
		//test("results['verified']",$results['verified']);
		$results['current']['status'] = $tmp_member_details['current']['identity']['status'];
		
	}
	
	//test("results",$results);
	return $results;
	
	
}

function get_business_location($accountid='',$memberid='') {



	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	//test("accountid",$accountid);
	$tmp_account_details = account($accountid);
	//test("tmp_account_details",$tmp_account_details);
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	//test("memberid",$memberid);
	$tmp_member_details = member($memberid);

	
	$tmp_sql = "SELECT * FROM ids_business 
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
				AND (status = 'SUBMITTED' OR status = 'VERIFIED' or status LIKE '%HOLD%')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['current']",$results['current']);
	
	$tmp_sql = "SELECT * FROM ids_business
				WHERE accountid = '". $accountid . "' 
				AND (proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL)
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	//test("results['verified']",$results['verified']);


	if(
	(stristr($tmp_account_details['business_type'],"DBA")) ||
	(stristr($tmp_account_details['business_type'],"GROUP"))
	) {
		
		if(
		(stristr($tmp_member_details['current']['location']['status'],"VERIFIED"))
		) {
			
			$results['verified']['idid'] = $tmp_member_details['current']['location']['idid'];
			$results['verified']['status'] = $tmp_member_details['current']['location']['status'];
			
			$results['verified']['proof_of_business_location_filename'] = $tmp_member_details['current']['location']['proof_of_residence_filename'];
			$results['verified']['business_address_1'] = $tmp_member_details['current']['location']['residential_address_1'];
			$results['verified']['business_address_2'] = $tmp_member_details['current']['location']['residential_address_2'];
			$results['verified']['business_address_3'] = $tmp_member_details['current']['location']['residential_address_3'];
			$results['verified']['business_country_iso3'] = $tmp_member_details['current']['location']['residential_country_iso3'];
			$results['verified']['datetime_updated'] = $tmp_member_details['current']['location']['datetime_updated'];
			
			
		} 
		
		$results['current']['idid'] = $tmp_member_details['current']['location']['idid'];
		
		$results['current']['status'] = $tmp_member_details['current']['location']['status'];
		
		$results['current']['proof_of_business_location_filename'] = $tmp_member_details['current']['location']['proof_of_residence_filename'];
		$results['current']['business_address_1'] = $tmp_member_details['current']['location']['residential_address_1'];
		$results['current']['business_address_2'] = $tmp_member_details['current']['location']['residential_address_2'];
		$results['current']['business_address_3'] = $tmp_member_details['current']['location']['residential_address_3'];
		$results['current']['business_country_iso3'] = $tmp_member_details['current']['location']['residential_country_iso3'];
		$results['current']['datetime_updated'] = $tmp_member_details['current']['location']['datetime_updated'];
		
					
			
		
				
	}
	
	
	
	
	
	
	//test("results",$results);
	return $results;
	
	
}


function confirm_plus($number) {
	if(!stristr($number,"+")) $number = "+".$number;
	return $number;
}

function get_current_verified_swift_account($memberid,$accountid,$status='') {

	if(empty($status)) {
		$status = "
		AND status = 'VERIFIED'";
	} else if(stristr($status,"ALL")) {
		$status = "";
	}
	
	if( !empty($memberid) && !empty($accountid) ) {
	
		$tmp_sql = "SELECT walletid FROM wallets
		WHERE memberid = '". $memberid ."'
		AND accountid = '". $accountid ."'
		$status
		AND type = 'SWIFT'
		ORDER BY datetime_created DESC
		LIMIT 1
		;";
		//test("tmp_sql",$tmp_sql);
		$current_swift_account_details = getTHECASHIER($tmp_sql);
		//test("current_swift_account_details",$current_swift_account_details);
		return $current_swift_account_details;
	}
}


function get_parent_details($accountid) {

	$account_details = account($accountid);
	
	//test("account_details",$account_details);
	
	if(stristr($account_details['accounttype'],"BUSINESS")) {
	
	
	
	
		if(
		(stristr($account_details['business_type'],"GROUP")) ||
		(stristr($account_details['business_type'],"PDBA"))
		) {
		
			//test("this is a registered company",$account_details['business_type']);
			###
			$tmp_creator_member_details = member($account_details['creator_memberid']);
			//test("tmp_creator_member_details",$tmp_creator_member_details);

			$return['name'] = "";
			if(!empty($tmp_creator_member_details['current']['identity']['firstname'])) $return['name'] .= $tmp_creator_member_details['current']['identity']['firstname'];
			if(!empty($tmp_creator_member_details['current']['identity']['firstname'])) $return['name'] .= " ";
			if(!empty($tmp_creator_member_details['current']['identity']['middlename'])) $return['name'] .= $tmp_creator_member_details['current']['identity']['middlename'];
			if(!empty($tmp_creator_member_details['current']['identity']['middlename'])) $return['name'] .= " ";
			if(!empty($tmp_creator_member_details['current']['identity']['lastname'])) $return['name'] .= $tmp_creator_member_details['current']['identity']['lastname'];
			
			###
			
			$return['street_1'] = $tmp_creator_member_details['current']['location']['residential_address_1'];
			
			$return['street_2'] = $tmp_creator_member_details['current']['location']['residential_address_2'];
			
			if(!empty($tmp_creator_member_details['current']['location']['residential_address_3'])) {
				$return['street_2'] .= "; ". $tmp_creator_member_details['current']['location']['residential_address_3'];
			}
			
			$personal_account_hash = 			
			$return['city'] = "";
			$return['state'] = "";
			$return['region'] = "";
			$return['country_iso3'] = $tmp_creator_member_details['current']['location']['residential_country_iso3'];
			$return['account_hash'] = getTHECASHIER("SELECT hash FROM accounts WHERE accountid = '". $tmp_creator_member_details['accounts']['personal'] ."';");
			$return['accountid'] = $tmp_creator_member_details['accounts']['personal'];
			
		} else if(
		(stristr($account_details['business_type'],"CDBA"))
		) {
			$tmp_sql = "SELECT * FROM ids_business 
			 									WHERE business_name = '". $account_details['accountname'] ."'
			 									AND business_legal_extension = 'CDBA'
			 									AND accountid = '". $account_details['accountid'] ."' 
			 									ORDER BY datetime_updated
			 									LIMIT 1
			 									;";
			//test("tmp_sql",$tmp_sql);
			 					
			$ids_business_details = object2array(readTHECASHIER($tmp_sql));
			//test("000ids_business_details",$ids_business_details);
			//test("ids_business_details['accountid']",$ids_business_details['accountid']);
			$tmp_parent_account = object2array(readTHECASHIER("SELECT * FROM accounts WHERE hash = '" . $ids_business_details['parent_account_hash'] . "';")); 
			//test("tmp_cdba_account_details",$tmp_cdba_account_details);
			
			//$tmp_parent_account = account($ids_business_details['parent_account_hash']);
			//test("ids_business_details['parent_account_hash']",$ids_business_details['parent_account_hash']);
			//$tmp_parent_account = object2array(readTHECASHIER("SELECT * FROM accounts WHERE hash = '" . $ids_business_details['parent_account_hash'] . "';")); 
			//test("tmp_parent_account",$$tmp_parent_account);
						
			$return['name'] = $tmp_parent_account['accountname'] . " " . $tmp_parent_account['business_type'];
			###
			$return['street_1'] = $tmp_parent_account['streetaddress1'];
			$return['street_2'] = $tmp_parent_account['streetaddress2'];
			$return['city'] = $tmp_parent_account['city'];
			$return['state'] = $tmp_parent_account['state'];
			$return['region'] = $tmp_parent_account['region'];
			$return['country_iso3'] = $tmp_parent_account['country_iso3'];
			$return['account_hash'] = $tmp_parent_account['hash'];
			$return['accountid'] = $tmp_parent_account['accountid'];
			
			
		} else {
			//test("this is a DBA",$account_details['business_type']);
			###
			$return['name'] = $account_details['accountname'] . " " . $account_details['business_type'];
			###
			$return['street_1'] = $account_details['streetaddress1'];
			$return['street_2'] = $account_details['streetaddress2'];
			$return['city'] = $account_details['city'];
			$return['state'] = $account_details['state'];
			$return['region'] = $account_details['region'];
			$return['country_iso3'] = $account_details['country_iso3'];
			$return['account_hash'] = $account_details['hash'];
			$return['accountid'] = $account_details['accountid'];
			
		}
	}
	
	return $return;
	
}




function update_personal_identities($memberid="",$accountid="") {


	$tmp_datetime = datetime();
	
	$tmp_ids_personal_array = arrayTHECASHIER("select idid FROM ids_personal WHERE status = 'VERIFIED';");
	
	foreach($tmp_ids_personal_array as $key => $personal_idid) {
	

		$tmp_sql = "SELECT * FROM ids_personal WHERE idid = '$personal_idid';";
		$personal_id_details = readTHECASHIER($tmp_sql);	

		### START: UPDATE PERSONAL IDENTITY
		if(!empty($personal_id_details->photo_id_filename)) {
		    
		   // test("HIT!",$HIT++);
		    $tmp_sql = "UPDATE members 
		    		SET firstname = '$personal_id_details->firstname'
		    		, middlename = '$personal_id_details->middlename'
		    		, lastname = '$personal_id_details->lastname'
		    		, updated = '$tmp_datetime'
		    		WHERE 
		    		memberid = '$personal_id_details->memberid'
		    		;";
		   // test("tmp_sql",$tmp_sql);
		    $updated_members = updateTHECASHIER($tmp_sql);
		    //test("updated_members",$updated_members);
		    
		    $account_name = "";
		    if(!empty($personal_id_details->firstname)) $account_name .= $personal_id_details->firstname;
		    if(
		    (!empty($personal_id_details->firstname)) &&
		    (!empty($personal_id_details->middlename))
		    ) {
			    $account_name .= " ";
		    }
		    if(!empty($personal_id_details->middlename)) $account_name .= $personal_id_details->middlename;
		    
		    if(
		    (
		    (!empty($personal_id_details->firstname)) ||
		    (!empty($personal_id_details->middlename))
		    ) &&
		    (!empty($personal_id_details->lastname))
		    ) {
			    $account_name .= " ";
		    }
		    if(!empty($personal_id_details->lastname)) $account_name .= $personal_id_details->lastname;
		    
		    $tmp_sql = "UPDATE accounts 
		        		SET accountname = '$account_name'
		        		, business_type = ''
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$personal_id_details->accountid'
		        		;";
		   // test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		    //test("updated_accounts",$updated_accounts);
		
		}
			### END: UPDATE PERSONAL IDENTITY
			
			
			
		### START: UPDATE PERSONAL LOCATION
		if(!empty($personal_id_details->proof_of_residence_filename)) {
		    
		    // test("HIT!",$HIT++);
		    // note missing formal state city region structure. should be added and change in the ids_personal table to accommodate said structure.
		    $tmp_sql = "UPDATE accounts 
		        		SET streetaddress1 = '$personal_id_details->residential_address_1'
		        		, streetaddress2 = '$personal_id_details->residential_address_2'
		    			, country_iso3 = '$personal_id_details->residential_country_iso3'
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$personal_id_details->accountid'
		        		;";
		   // test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		    //test("updated_accounts",$updated_accounts);
	
		}
		### END: UPDATE PERSONAL LOCATION	
	
	}

}


function update_business_identities($memberid="",$accountid="") {


	$tmp_datetime = datetime();
	
	$tmp_ids_business_array = arrayTHECASHIER("select idid FROM ids_business WHERE status = 'VERIFIED';");
	
	foreach($tmp_ids_business_array as $key => $business_idid) {
	
		$tmp_sql = "SELECT * FROM ids_business WHERE idid = '$business_idid';";
		$business_id_details = readTHECASHIER($tmp_sql);
		
	
	
		### START: UPDATE BUSINESS IDENTITY
		if(!empty($business_id_details->business_certificate_filename)) {
		    
		   // test("HIT!",$HIT++);
		  	//$account_name = "";
		    //if(!empty($business_id_details->firstname)) $account_name .= $business_id_details->firstname;
		    //if(!empty($account_name)) $account_name .= " ";
		    //if(!empty($business_id_details->middlename)) $account_name .= $business_id_details->middlename;
		    //if(!empty($account_name)) $account_name .= " ";
		    //if(!empty($business_id_details->lastname)) $account_name .= $business_id_details->lastname;
		    
		    $tmp_sql = "UPDATE accounts 
		        		SET accountname = '$business_id_details->business_name'
		        		, business_type = '$business_id_details->business_legal_extension'
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$business_id_details->accountid'
		        		;";
		   // test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		    //test("updated_accounts",$updated_accounts);
		
		}
			### END: UPDATE BUSINESS IDENTITY
			
			
			
		### START: UPDATE BUSINESS LOCATION
		if(!empty($personal_id_details->proof_of_business_location_filename)) {
		
			// test("HIT!",$HIT++);
		    
		    // note missing formal state city region structure. should be added and change in the ids_personal table to accommodate said structure.
		    $tmp_sql = "UPDATE accounts 
		        		SET streetaddress1 = '$business_id_details->business_address_1'
		        		, streetaddress2 = '$business_id_details->business_address_2'
		    			, country_iso3 = '$business_id_details->business_country_iso3'
		        		, updated = '$tmp_datetime'
		        		WHERE 
		        		accountid = '$business_id_details->accountid'
		        		;";
		   // test("tmp_sql",$tmp_sql);
		    $updated_accounts = updateTHECASHIER($tmp_sql);
		   // test("updated_accounts",$updated_accounts);
	
		}
		### END: UPDATE BUSINESS LOCATION	
	
	}

}




# function fix_account_sharing_issue(){
# 	
# 	$tmp_sql = "SELECT accountid FROM accounts WHERE accounttype = 'BUSINESS';";
# 	$account_ids = arrayTHECASHIER($tmp_sql);
# 	
# 	foreach($account_ids as $key => $accountid) {
# 	
# 		$account_details = account($accountid);
# 		$tmp_sql = "UPDATE accounts 
# 					SET transaction_fee_my = '". $account_details['transaction_fee_total'] ."' 
# 					WHERE accountid = '". $accountid ."';";
# 		
# 	}
# 	
# 	
# }


function get_account_telephone_support($accountid='') {

	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	if(empty($accountid)) return FALSE;
	
	$account_details = account($accountid);
	$authorization_details = authorization_number($account_details['creator_memberid']);
	$results = "";
	$results = array();
	if(empty($account_details['customer_support_phone_number_1'])) {
		$results['formatted_number'] = $authorization_details['formatted_number'];
		$results['calling_code'] = $authorization_details['calling_code'];
		$results['phone_number'] = $authorization_details['phone_number'];
	} else {
		
		$tmp_customer_support_number = explode("/",$account_details['customer_support_phone_number_1']);
		
		$results['formatted_number'] = $account_details['customer_support_phone_number_1'];
		$results['calling_code'] = $tmp_customer_support_number[0];
		$results['phone_number'] = $tmp_customer_support_number[1];
		
	}
	
	
	//test("results",$results);
	return $results;
}



function get_bank_account($accountid='') {

	//test("get_bank_account(): accountid",$accountid);
	
	if(empty($accountid)) $accountid = $_SESSION['account']['accountid'];
	if(empty($accountid)) return FALSE;
	
	$tmp_sql = "SELECT * FROM wallets
				WHERE accountid = '". $accountid ."'
				AND type = 'SWIFT'
				AND (status = 'SUBMITTED' OR status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['current'] = object2array(readTHECASHIER($tmp_sql));

	$tmp_sql = "SELECT * FROM wallets
				WHERE accountid = '". $accountid ."'
				AND type = 'SWIFT'
				AND (status = 'VERIFIED')
				ORDER BY datetime_updated DESC
				LIMIT 1
				;";
	//test("tmp_sql",$tmp_sql);
	$results['verified'] = object2array(readTHECASHIER($tmp_sql));
	
	//test("results",$results);
	return $results;
	
}


function get_CRM_count() {
	
	$day_to_search = date("Y-m-d",strtotime("-5 days"));
	$tmp_sql = "SELECT transactionid FROM transactions
			WHERE accountid = '". $_SESSION['account']['accountid'] . "'
			AND description = 'INCOMING'
			AND (status = 'APPROVED' OR status = 'COMPLETED')
			AND (CRM_CALLBACK_FOLLOWUP = '' OR CRM_CALLBACK_FOLLOWUP = 'CHECKED')
			AND CRM_CALLBACK_MESSAGE = ''
			AND CRM_CALLBACK_REFUNDED = ''
			AND CRM_CALLBACK_SATISFIED = ''
			AND requested_datetime LIKE '". $day_to_search ."%'
			;";
	
	$results = arrayTHECASHIER($tmp_sql);
	return count($results);
	
}


function in_array_MD($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if(
        ($strict ? $item === $needle : $item == $needle) || 
        (is_array($item) && in_array_MD($needle, $item, $strict))
        ) {
            return TRUE;
        }
    }

    return FALSE;
}



#### FROM FRREESWITCH.AUTH
function get_gateway($gateway_attempt) {


 # 0000
 # 1  = worlddialpoint
 # 2  = lax.teliax.net
 # 3  = nyc.teliax.net
 # 4  = den.teliax.net
 # 5  = atl.teliax.net
 # 6  = grnvoip - premium
 # 7  = grnvoip - standard
 # 8  = clickncallnow
 # 9  = flowroute
 # 10 = voiptraffic

### GATEWAY:

	if(empty($_SESSION['function']['gateway_attempt'])) {
		$_SESSION['function']['authorization_voip_gateway_attempt'] = 1;
	
	} else {
		$_SESSION['function']['authorization_voip_gateway_attempt'] = $_SESSION['function']['authorization_voip_gateway_attempt'] + 1;
		
		if($_SESSION['function']['authorization_voip_gateway_attempt'] > $number_of_gateways) {
			$_SESSION['function']['authorization_voip_gateway_attempt'] = $starting_gateway;
		}
		
	}
	
	$gateway_attempt = $_SESSION['function']['authorization_voip_gateway_attempt'];
	
	global $authorization;

	### NOTE:
		# leave a space (" ") after the IP/gateway (which will preceed the extension) - example: "@70.42.72.49 " or "lax.teliax.net "
	
	##############################################################################
	### BLANK ########################################################################
	
	if($gateway_attempt == "0000") {  /// just makes it easier to move-around/re-order the gateways below
		//$gateway_uri = "";



	##############################################################################
	### VOIPBUSTER ###################################################
	

	} else if($gateway_attempt == "xxxxxxxxxxx") { ## more reliable

		$gateway_uri = "sofia/gateway/voipbuster/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.voipbuster.com ";
		
		
		
	##############################################################################
	### WORLDDIALPOINT #####################################################
	
	} else if(

	($gateway_attempt == "xxxxxxxxxxx")

	) {

		if($_SESSION['authorization']['phone']['country_code'] == "61") { // australian calls
			
			if($_SESSION['authorization']['phone']['number'][0] == "2") { // sydney local landline
				$number_to_dial = $_SESSION['authorization']['phone']['number'][1] . $_SESSION['authorization']['phone']['number'][2] . $_SESSION['authorization']['phone']['number'][3] . $_SESSION['authorization']['phone']['number'][4] . $_SESSION['authorization']['phone']['number'][5] . $_SESSION['authorization']['phone']['number'][6] . $_SESSION['authorization']['phone']['number'][7] . $_SESSION['authorization']['phone']['number'][8];
				
			} else { // all other aussie numbers
				$number_to_dial = "0" . $_SESSION['authorization']['phone']['number'];
			}
		
		} else { // non-australian calls
			$number_to_dial = "0011" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'];
		}
		
		//$gateway_uri = "sofia/gateway/worlddialpoint/" . $number_to_dial . "@203.176.185.10 ";
		$gateway_uri = "sofia/gateway/worlddialpoint/" . $number_to_dial . "@sip.bbvoice.com.au ";
		
	
	##############################################################################
	### TELIAX/LAX #########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@lax.teliax.net ";

		
	##############################################################################
	### TELIAX/NYC #########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@nyc.teliax.net ";


	##############################################################################
	### TELIAX/DENVER ######################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@den.teliax.net ";
	
	
	##############################################################################
	### TELIAX/ATL #########################################################
	

	} else if($gateway_attempt == "xxxxxxxxxxx") {

		if($_SESSION['authorization']['phone']['country_code'] == "1") {
			$gateway_prefix = NULL;
		} else {
			$gateway_prefix = "011";
		}
		$gateway_uri = "sofia/gateway/teliax/" . $gateway_prefix . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@atl.teliax.net ";
		
	
	##############################################################################
	### GRNVOIP/PREMIUM ###################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") { ## more reliable
		$gateway_uri = "sofia/gateway/grnvoip/13024401" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@bangk.grnvoip.com ";

	
	##############################################################################
	### GRNVOIP/STANDARD ###################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") { ## more reliable
		$gateway_uri = "sofia/gateway/grnvoip/13024400" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@bangk.grnvoip.com ";

	
	##############################################################################
	### CLICKNCALLNOW ##########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		$gateway_uri = "sofia/gateway/clickncallnow/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.clickncallnow.com ";



		
	##############################################################################
	### VOIPTRAFFIC ##########################################################
	
	} else if($gateway_attempt == "xxxxxxxxxxx") {
		$gateway_uri = "sofia/gateway/voiptraffic/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.voiptraffic.net ";


	##############################################################################
	### TWILIO ##########################################################
	
	} else if($gateway_attempt == "2") {
		$gateway_uri = "sofia/gateway/Twilio-outbound/+" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@nsdb.pstn.twilio.com ";

	##############################################################################
	### FLOWROUTE ##########################################################
	
	} else if($gateway_attempt == "1") {
		$gateway_uri = "sofia/gateway/flowroute/" . $_SESSION['authorization']['phone']['country_code'] . $_SESSION['authorization']['phone']['number'] . "@sip.flowroute.com ";
		logger3(">>> gateway_uri",$gateway_uri);
		logger3(">>> _SESSION['authorization']",$_SESSION['authorization']);


	}
	
	
	
	
	
	
	logger3("gateway_uri",$gateway_uri);
	return $gateway_uri;
}



function cancel_withdrawal_request($transactionid,$request_updated_banking_documents,$reason,$send_email) {
	
	global $master_config_accounting_emailaddress;
	if(empty($request_updated_banking_documents)) $request_updated_banking_documents = "YES";
	if(empty($reason)) $reason = "Administrative Adjustment";
	if(empty($send_email)) $send_email = "YES";

	### UPDATE TRANSACTION:
	$tmp_datetime = datetime();
	$tmp_sql = "UPDATE transactions 
	SET
	status = 'Canceled',
	return_datetime = '".$tmp_datetime."',
	return_reason = '". $reason ."',
	updated_datetime = '". $tmp_datetime ."'
	WHERE
	transactionid = '". $transactionid ."';";
	//test("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	test("cancel_withdrawal_request(): $transactionid update_results",$update_results);
	
	## $tmp_transactionid = $_SESSION['admin']['withdrawal']['transaction_details']['transactionid'];
	## $_SESSION['admin']['withdrawal']['transaction_details']['transactionid'] = "";
	
	$transaction_details = transaction($transactionid);
	
	
	if(!empty($_SESSION['admin']['withdrawal']['transaction_details']['transactionid'])) {

		$_SESSION['admin']['withdrawal']['transaction_details']['transactionid'] = "";
		$_SESSION['admin']['withdrawal']['transaction_details'] = $transaction_details;
	}

	$current_balance = balance($transaction_details['accountid']);
	//test("current_balance",$current_balance);
	
	//test("_SESSION['admin']['withdrawal']['transaction_details']['transaction_gross_value']",$_SESSION['admin']['withdrawal']['transaction_details']['transaction_gross_value']);
	
	$new_account_balance = currency_format($current_balance['account_balance'] + $transaction_details['transaction_gross_value']);
	//test("new_account_balance",$new_account_balance);
	
	$new_available_balance = currency_format($current_balance['available'] + $transaction_details['transaction_gross_value']);
	//test("new_available_balance",$new_available_balance);
	
	
	### UPDATE BALANCES:
	$tmp_sql = "UPDATE balances SET 
				account_balance = '".$new_account_balance."',
				available = '".$new_available_balance."'
				WHERE 
				accountid = '". $transaction_details['accountid']."'
				;";
	//test("tmp_sql",$tmp_sql);
	$update_results = updateTHECASHIER($tmp_sql);
	//test("update_results",$update_results);

	### SEND BUSINESS UPDATE EMAIL:
	# $member_emailaddress = $email_member_details['emailaddress'];
	# $email_to = $email_member_details['emailaddress'];


	if(stristr($_POST['request_updated_banking_documents'],"YES")) {
		
		
		$tmp_sql = "UPDATE wallets
					SET status = 'INVALID'
					WHERE walletid = '". $transaction_details['walletid'] ."';";
		//test("tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql);
		//test("update_results",$update_results);
		
	}

	if(!stristr($send_email,"NO")) {
		
		$email_receipt = "canceled_withdrawal_to_swift_account";
		$email_receipt_cc = $master_config_accounting_emailaddress;
		include($_SESSION['template']['company']['file_path'] . "shared/email_receipts.shared");
		
		
		$_SESSION['SYSMSG'] = "
		<span style='line-height:35px;'>
		CANCELED...<br>
		Funds reverted back to the account.<br>
		Please continue...
		</span>
		";
	}
	
	return "OK";
	
	
}


################################################################################
### FS FUNCTIONS:
 
function event_socket_create($host, $port, $password) {
	
	logger3("got to event_socket_create()",$x);
	
	$fp = fsockopen($host, $port, $errno, $errdesc) or die("Connection to [" . $host . "] failed");
	
	logger3("0 event_socket_create() fp",$fp);
	
	if($fp == FALSE) logger3("1 event_socket_create() fp = FLASE",$x);
	
	if($fp != FALSE) logger3("2 event_socket_create() fp",$fp);
	
	socket_set_blocking($fp,false);
     
	if ($fp) {
		while (!feof($fp)) {
			$buffer = fgets($fp, 1024);
			usleep(100); //allow time for reponse
			if (trim($buffer) == "Content-Type: auth/request") {
				fputs($fp, "auth $password\n\n");
				break;
			}
		}
		return $fp;
	}	else {
		return false;
	}           
}
 



function event_socket_request($fp, $cmd) {
    
	if ($fp) {    
		fputs($fp, $cmd."\n\n");    
		usleep(1000); //allow time for reponse
         
		$response = "";
		$i = 0;
		$contentlength = 0;
		while (!feof($fp)) {
			$buffer = fgets($fp, 4096);
			if ($contentlength > 0) {
				$response .= $buffer;
			}
            
			if ($contentlength == 0) { //if contentlenght is already don't process again
				if (strlen(trim($buffer)) > 0) { //run only if buffer has content
					$temparray = split(":", trim($buffer));
					if ($temparray[0] == "Content-Length") {
						$contentlength = trim($temparray[1]);
					}
				}
			}
            
			usleep(1000); //allow time for reponse
            
			//optional because of script timeout //don't let while loop become endless
			if ($i > 10000) { break; } 
            
			if ($contentlength > 0) { //is contentlength set
				//stop reading if all content has been read.
				if (strlen($response) >= $contentlength) {  
					break;
				}
			}
			$i++;
		}
         
		return $response;
	
	}	else {
		echo "no handle";
	}
}


function process_dump($response) {

 	$order  = array("\r\n", "\n", "\r");
 	$replace = ",";
 	
 	$response = str_replace($order, $replace, $response);	
 	
 
 	$response_array = split(",", $response);
 	$new_array;
 	
 	foreach ($response_array as $item) {
 		$key = substr($item, 0, strpos($item, ":"));
 		$value = substr($item, strpos($item, " "), strlen($item)-1);
 		
 		$new_array[$key] = $value;
 	}
 	
 	return $new_array;
 
}




function process_withdrawal($memberid='',$accountid='',$withdrawal_amount='',$memo='') {


	global $master_config_platform_emulation;
	global $master_config_wire_to_bank_fee_USD;
	global $master_config_wire_to_bank_fee_EUR;
	
	test("process_withdrawal(): accountid",$accountid);
	
	###################################################
	### START: FIX EMPTY VARS:
	if(empty($_SESSION['authorization']['timestamp'])) $_SESSION['authorization']['timestamp'] = datetime();
	
	if(!empty($memberid)) {
		$tmp_admin_member = $_SESSION['member'];
		$_SESSION['member'] = "";
		$_SESSION['member'] = member($memberid);
	}
	
	if(!empty($accountid)) {
		$tmp_admin_account = $_SESSION['account'];
		$_SESSION['account'] = "";
		$_SESSION['account'] = account($accountid);
		
	}
	
	$_SESSION['withdrawal']['banking_account_owner_account_hash'] = $_SESSION['account']['hash'];
	if(!empty($withdrawal_amount)) $_SESSION['withdrawal']['amount'] = $withdrawal_amount;
	
	
	### END: FIX EMPTY VARS:
	###################################################
	


	##############################################################################
	### SET SOME VARS THAT WILL BE COMMON TO ALL TRANSACTION RESULTS:
	$_SESSION['transaction']['ratio'] = get_fx($_SESSION['template']['company']['currency1'],$_SESSION['account']['currency_code_1'],"1.00");
	logger3("_SESSION['transaction']['ratio']",$_SESSION['transaction']['ratio']);
	
	if(empty($_SESSION['authorization']['timestamp'])) $_SESSION['authorization']['timestamp'] = time();
	
	$_SESSION['transaction']['datetime_requested'] = date("Y-m-d H:i:s",$_SESSION['authorization']['timestamp']);
	$_SESSION['transaction']['datetime_updated'] = date("Y-m-d H:i:s",time());
	$_SESSION['transaction']['original_balance'] = balance($_SESSION['account']['accountid']);
	
	logger3("_SESSION['transaction']['original_balance']",$_SESSION['transaction']['original_balance']);
  
	# SET INITIATED BY:
	$_SESSION['transaction']['results'] = "INITIATED BY ACCOUNTID][" . $_SESSION['account']['accountid'] . "][accountname][" . $_SESSION['account']['accountname'] . "][emailaddress][" . $_SESSION['account']['emailaddress'] . "][";
  
	# SET ACCOUNT DETAILS:
	$_SESSION['account_details'] = "ACCOUNTID][" . $_SESSION['account']['accountid'] . "][accountname][" . $_SESSION['account']['accountname'] . "][emailaddress][" . $_SESSION['account']['emailaddress'] . "][";
	
	# SET FEES
	$tmp_transaction_fee = "master_config_wire_to_bank_fee_".$_SESSION['template']['company']['currency1'];
    $tmp_transaction_fee = $$tmp_transaction_fee; //"0.00";

  
	##############################################################################
	### SET AMOUNT_VALUES: (has o be set b4 therwsie valus wonlt display or something)
	#
	# USE VARS:
	$_SESSION['transaction']['requested_value'] = $_SESSION['withdrawal']['amount'];
	//$_SESSION['transaction']['gross_value'] = $_SESSION['withdrawal']['amount'];
	//$_SESSION['transaction']['net_value'] = $_SESSION['withdrawal']['amount'] - $tmp_transaction_fee;
	$_SESSION['transaction']['account_bonus_value'] = "0.00";
	$_SESSION['transaction']['fee_sponsor_value'] = "0.00";
	$_SESSION['transaction']['fee_bonus_value'] = "0.00";
	$_SESSION['transaction']['fee_network_value'] = $tmp_transaction_fee;
	# $_SESSION['transaction']['fee_total_value']
	#
	### UPDATE FOR BANK:
	# $_SESSION['withdrawal']['name_of_banking_institution'];
	# $_SESSION['withdrawal']['banking_routing_number'];
	# $_SESSION['withdrawal']['banking_account_number'];
	# $_SESSION['withdrawal']['banking_iban_swift'];
	# $_SESSION['withdrawal']['banking_telephone_number'];
	
	### GROSS:
	$_SESSION['transaction']['gross_value'] = $_SESSION['withdrawal']['amount']; // + $_SESSION['transaction']['fee_network_value'];
	
	
	    
	#
	### FEES:
	$_SESSION['transaction']['fee_total_value'] = $_SESSION['transaction']['fee_network_value'] + $_SESSION['transaction']['fee_bonus_value'] + $_SESSION['transaction']['fee_sponsor_value'];
	
	
	
	
	#  
	### NET:
	//$_SESSION['transaction']['net_value'] = currency_format($_SESSION['transaction']['requested_value'] * (1-$_SESSION['account']['transaction_fee_my']));
	$_SESSION['transaction']['net_value'] = currency_format($_SESSION['transaction']['gross_value'] - $_SESSION['transaction']['fee_total_value']);
	
	
	#
	### MAKE 'EM LOOK PRETTY:
	$_SESSION['transaction']['gross_value'] = number_format($_SESSION['transaction']['gross_value'],2,".","");
	$_SESSION['transaction']['fee_total_value'] = number_format($_SESSION['transaction']['fee_total_value'],2,".","");
	$_SESSION['transaction']['net_value'] = number_format($_SESSION['transaction']['net_value'],2,".","");

  
	logger3("_SESSION['transaction']['gross_value']",$_SESSION['transaction']['gross_value']);
	logger3("_SESSION['transaction']['fee_total_value']",$_SESSION['transaction']['fee_total_value']);
	logger3("_SESSION['transaction']['net_value']",$_SESSION['transaction']['net_value']);
  
  
	##############################################################################
	### THIS IS A WIRE SO WE HAVE TO SET THE MAIL TO ADDRESS AT THE ACCOUNT NUMBER:
	$banking_account_owner_account_details = account($_SESSION['withdrawal']['banking_account_owner_account_hash']);
	$_SESSION['transaction']['wire_instructions'] = "";
	$_SESSION['transaction']['wire_instructions'] .= "ACCOUNT_NAME][" . $banking_account_owner_account_details['accountname'] . " " . $banking_account_owner_account_details['business_type'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "BANK_NAME][" . $_SESSION['withdrawal']['name_of_banking_institution'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "ABA_NUMBER][" . $_SESSION['withdrawal']['banking_routing_number'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "ACCOUNT_NUMBER][" . $_SESSION['withdrawal']['banking_account_number'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "IBAN_SWIFT][" . $_SESSION['withdrawal']['banking_iban_swift'] . "][";
	$_SESSION['transaction']['wire_instructions'] .= "PHONE_NUMBER][" . $_SESSION['withdrawal']['banking_telephone_number'] . "][";

	logger3("_SESSION['transaction']['wire_instructions']",$_SESSION['transaction']['wire_instructions']);
  
  
	##############################################################################
	### CANCELED:
	logger3("_SESSION['transaction']['status']",$_SESSION['transaction']['status']);
	if($_SESSION['transaction']['status'] == "Canceled") {
  	
  		# do nothing special
  		
  		//logger3("transaction['status'] 2",$_SESSION['transaction']['status']);
  
  	
		


  	 ##############################################################################
  	### VERIFY SUFFICIENT BALANCE:
  	//} else if(($_SESSION['transaction']['requested_value'] + $_SESSION['transaction']['fee_network_value']) > $_SESSION['transaction']['original_balance']['available']) {
  	
  	} else if($_SESSION['transaction']['requested_value'] > $_SESSION['transaction']['original_balance']['available']) {
    	test("$accountid _SESSION['transaction']['requested_value'] > _SESSION['transaction']['original_balance']['available']", $_SESSION['transaction']['requested_value'] ." > ". $_SESSION['transaction']['original_balance']['available']);
    	$_SESSION['transaction']['status'] = "Rejected";
    	$_SESSION['transaction']['results'] = "Insufficient Funds";
   
   /* 	
    	$_SESSION['SYSMSG'] = "<font color='990000'>REJECTED! Your " . currency1($_SESSION['transaction']['requested_value'],$blank) . " withdrawal request is greater than your current Available Balance of " . currency1($_SESSION['transaction']['original_balance']['available'],$blank) . ".</font color><br>
<br>
<font color='000099'>Please review your transaction receipt below...</font color>";
*/


  	##############################################################################
  	} else { ### ALL GOOD NOW PROCESS TRANSACTION:
  
    	### SET COMMON VARS:
    	$_SESSION['transaction']['status'] = "Approved";
    	logger3("_SESSION['transaction']['status']",$_SESSION['transaction']['status']);
    	//logger3("transaction['status'] 3",$_SESSION['transaction']['status']);
   
   
    	##############################################################################
    	### UPDATE ACCOUNT BALANCE:
    	//$_SESSION['transaction']['new_balance']['available'] = $_SESSION['transaction']['original_balance']['available'] - $_SESSION['transaction']['requested_value'] - $_SESSION['transaction']['fee_total_value'];
    	$_SESSION['transaction']['new_balance']['available'] = $_SESSION['transaction']['original_balance']['available'] - $_SESSION['transaction']['requested_value'];
    	 
    	logger3("_SESSION['transaction']['new_balance']['available']",$_SESSION['transaction']['new_balance']['available']);
    	
    	//$_SESSION['transaction']['new_balance']['account'] = $_SESSION['transaction']['original_balance']['account'] - $_SESSION['transaction']['requested_value'] - $_SESSION['transaction']['fee_total_value'];
    	$_SESSION['transaction']['new_balance']['account'] = $_SESSION['transaction']['original_balance']['account'] - $_SESSION['transaction']['requested_value'];
    	
    	test("$accountid _SESSION['transaction']['new_balance']['account_balance']",$_SESSION['transaction']['new_balance']['account_balance']);
    	
    	if(!empty($master_config_platform_emulation)) {
    		$tmp_platform = $master_config_platform_emulation;
    	} else {
	    	$tmp_platform = $_SESSION['template']['company']['domain'];
    	}
    	$tmp_sql = "UPDATE balances 
    						SET 
    						available = '" . $_SESSION['transaction']['new_balance']['available'] . "' 
							WHERE 
							accountid = '" . $_SESSION['account']['accountid'] . "'
							AND platform = '".$tmp_platform."' 
							AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."'
							;";
		$tmp_results = updateTHECASHIER($tmp_sql);
		test("tmp_sql",$tmp_sql);
		test("tmp_results",$tmp_results);
    	
    	
    	$tmp_sql = "UPDATE balances 
    						SET 
    						account_balance = '" . $_SESSION['transaction']['new_balance']['account'] . "' 
    						WHERE
							accountid = '" . $_SESSION['account']['accountid'] . "'
							AND platform = '". $tmp_platform ."' 
							AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."'
							;";
		$tmp_results = updateTHECASHIER($tmp_sql);
		test("tmp_sql",$tmp_sql);
		test("tmp_results",$tmp_results);
    }
  
 
    //// SET SOME VARS FOR DB:
    $_SESSION['transaction']['hash'] = hash_me();
	$tmp_transaction_fee = "master_config_wire_to_bank_fee_".$_SESSION['template']['company']['currency1'];
    $_SESSION['withdrawal']['fee'] = $$tmp_transaction_fee; //"0.00";
 	$_SESSION['transaction']['currency_0_iso3'] = $_SESSION['template']['company']['currency1'];
	$_SESSION['transaction']['currency_0_request'] = currency_format($_SESSION['withdrawal']['amount']);
	$_SESSION['transaction']['currency_0_fee'] = currency_format($_SESSION['withdrawal']['fee']);
	$_SESSION['transaction']['currency_0_total'] = currency_format($_SESSION['withdrawal']['amount']);
	
	### new:
	$_SESSION['transaction']['net_value'] = currency_format($_SESSION['withdrawal']['amount'] - $_SESSION['withdrawal']['fee']);

		
		
    if($_SESSION['account']['currency_code_1']) {
		$_SESSION['transaction']['currency_1_iso3'] = $_SESSION['account']['currency_code_1'];
		$_SESSION['transaction']['currency_1_request'] = currency_format($_SESSION['withdrawal']['amount'] * $_SESSION['transaction']['ratio']);
		$_SESSION['transaction']['currency_1_total'] = currency_format($_SESSION['withdrawal']['amount'] * $_SESSION['transaction']['ratio']);
		$_SESSION['transaction']['currency_1_ratio'] = $_SESSION['transaction']['ratio'];
	}
	
	$_SESSION['transaction']['walletid'] = $_SESSION['withdrawal']['destination_banking_details']['walletid'];
    
    
    
   
    ##############################################################################
    ### ALWAYS RECORD ABOVE TRANSACTION: (ALWAYS SEND)
    $tmp_sql = "INSERT into transactions 
    (`transactionid`,
    `platform`,
    `hash`,
    `source`,
    `memberid`,
    `accountid`,
    `account_details`,
    `description`,
    `method`,
    `method_details`,
    `walletid`,
    `transaction_gross_value`,
    `fee_sponsor_value`,
    `fee_bonus_value`,
    `fee_network_value`,
    `fee_total_value`,
    `status`,
    `results`,
    `account_balance_before`,
    `available_balance_before`,
    `transaction_net_value`,
    `account_bonus_value`,
    `account_balance_after`,
    `available_balance_after`,
    `ratio`,
    `currency_0_iso3`,
    `currency_0_request`,
    `currency_0_fee`,
    `currency_0_total`,
    `currency_1_iso3`,
    `currency_1_request`,
    `currency_1_total`,
    `currency_1_ratio`,
    `memo`,
    `requested_datetime`,
    `updated_datetime`,
    `authorization`) 
    
    VALUES 
    
    ('" . $blank_id . "',
    '" . $tmp_platform . "',
    '" . $_SESSION['transaction']['hash'] . "',
    'WWW',
    '" . $_SESSION['member']['memberid'] . "',
    '" . $_SESSION['account']['accountid'] . "',
    '" . $_SESSION['accountdetails'] . "',
    'Withdrawal',
    'Bank Wire',
    '" . $_SESSION['transaction']['wire_instructions'] . "',
    '" . $_SESSION['transaction']['walletid'] . "',
    '" . $_SESSION['transaction']['gross_value'] . "',
    '" . $_SESSION['transaction']['fee_sponsor_value'] . "',
    '" . $_SESSION['transaction']['fee_bonus_value'] . "',
    '" . $_SESSION['transaction']['fee_network_value'] . "',
    '" . $_SESSION['transaction']['fee_total_value'] . "',
    '".  $_SESSION['transaction']['status'] . "',
    '" . $_SESSION['transaction']['results'] . "',
    '" . $_SESSION['transaction']['original_balance']['account'] . "',
    '" . $_SESSION['transaction']['original_balance']['available'] . "',
    '" . $_SESSION['transaction']['net_value'] . "',
    '" . $_SESSION['transaction']['account_bonus_value'] . "',
    '" . $_SESSION['transaction']['new_balance']['account'] . "',
    '" . $_SESSION['transaction']['new_balance']['available'] . "',
    '" . $_SESSION['transaction']['ratio'] . "',

    '" . $_SESSION['transaction']['currency_0_iso3'] . "',
    '" . $_SESSION['transaction']['currency_0_request'] . "',
    '" . $_SESSION['transaction']['currency_0_fee'] . "',
    '" . $_SESSION['transaction']['currency_0_total'] . "',
    
    '" . $_SESSION['transaction']['currency_1_iso3'] . "',
    '" . $_SESSION['transaction']['currency_1_request'] . "',
    '" . $_SESSION['transaction']['currency_1_total'] . "',
    '" . $_SESSION['transaction']['currency_1_ratio'] . "',
    '" . $memo . "',
    '" . $_SESSION['transaction']['datetime_requested'] . "',
    '" . $_SESSION['transaction']['datetime_updated'] . "',
    '" . $_SESSION['authorization']['voice_file'] . "');";
    
    test("tmp_sql",$tmp_sql);
    
    $_SESSION['transaction']['transactionid'] = insertTHECASHIER($tmp_sql);
    
    test("_SESSION['transaction']['transactionid']",$_SESSION['transaction']['transactionid']);
    
    ### $email_alert_message  = "WITHDRAWAL:
    ### ACCOUNTID: " . $_SESSION['account']['accountid'] . "
    ### AMOUNT: " . currency_format($_SESSION['transaction']['gross_value']);
    ### email_alert($email_alert_message,"accounting@nsdb.com");

	### SET TRANSACTION STATUS:
	$_SESSION['transaction']['status'] = "Approved";


	if( $send_email != "NO") {
		#############################################################################
		### SEND AN EMAIL RECEIPT TO THE ACCOUNT HOLDER: ############
		#$email_transaction = "approved pending deposit";
		#include($_SESSION['template']['company']['file_path'] . "shared/email_admin_receipts.shared");
		$email_receipt = "approved_withdrawal_to_swift_account";
		include($_SESSION['template']['company']['file_path'] . "shared/email_receipts.shared");
		############################################################
		
		
		    
		## SYSMSG:
		$_SESSION['SYSMSG'] = "<span style='line-height:35px;'>
		<b>SUCCESS!</b><br>
		Your " . displayCURRENCY1($_SESSION['transaction']['requested_value']) . " withdrawal has been APPROVED!<br>
		A withdrawal receipt has been emailed to: ". $_SESSION['account']['emailaddress'] ."<br>
		<b>ALSO PLEASE NOTE:</b> you will receive a FOLLOW-UP CONFIRMATION (<u>within 24 hours</u>) when funds have been SENT!
		</span>";

	}
	
	
	### RESET MY SESSION:
	
	$_SESSION['member'] = "";
	$_SESSION['member'] = $tmp_admin_member;
	
	
	$_SESSION['account'] = "";
	$_SESSION['account'] = $tmp_admin_account;
}



function check_credit_cards_per_member_limit($memberid='',$new_credit_card_number='') {

	global $master_config_basic_limits_per_member_number_of_registered_creditcards;
	
	if(empty($new_credit_card_number)) return FALSE;
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	if(empty($memberid)) return FALSE;

	$tmp_sql = "SELECT * FROM wallets 
				WHERE memberid = '". $memberid ."'
				AND type != 'SWIFT'
				AND number = '". $new_credit_card_number ."'
				;";
	$card_already_exists = readTHECASHIER($tmp_sql);
	if(!empty($card_already_exists->walletid)) return "OK";
	
	$tmp_sql = "SELECT distinct(number) FROM wallets 
				WHERE memberid = '". $memberid ."'
				AND type != 'SWIFT'
				;";
	$results = arrayTHECASHIER($tmp_sql);
	$number_of_cards = count($results);
	if($number_of_cards >= $master_config_basic_limits_per_member_number_of_registered_creditcards) {
		return "LIMIT REACHED";
	} else {
		return "OK";
	}
}	



function generateGUID() {
   return sprintf('%04x', mt_rand(0, 0xffff));
}

function generateUUID() {
   return (generateGUID().generateGUID()."-".generateGUID()."-".generateGUID()."-".generateGUID()."-".generateGUID().generateGUID().generateGUID());
}


function get_dynamic_processing_profile($accountid='') {

	
	
	//test("accountid",$accountid);
	
	global $master_config_default_gateway;

	if($_COOKIE['sponsor_accountid']) $sponsor_accountid = $_COOKIE['sponsor_accountid'];
	
	

    
    if(is_array($_SESSION['account'])) {
    	if($_SESSION['account']['sponsor_accountid']) $sponsor_accountid = $_SESSION['account']['sponsor_accountid'];
    }
    
    if(is_array($_SESSION['member'])){
    	if($_SESSION['member']['sponsor_accountid']) $sponsor_accountid = $_SESSION['member']['sponsor_accountid'];
    }
	



	
	if(!empty($accountid)) {
		$sponsor_accountid = getTHECASHIER("SELECT sponsor_accountid FROM accounts WHERE accountid = '". $accountid ."';");
		$account_details = getTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';");
	}
	
	$sponsor_details = readTHECASHIER("SELECT * FROM affiliates WHERE hash = '". $sponsor_accountid ."';");
	
	if(
	(stristr($sponsor_details->associated_gateway,"ECP")) ||
	(stristr($account_details->gateway_profile,"ECP"))
	) {
		
		$dynamic_schedule['profile_name'] = "ECP";
		$dynamic_schedule['starting_fee'] = "12.9%";
		$dynamic_schedule['starting_payout_schedule'] = "30 Days";
		$dynamic_schedule['profile_html_table'] = "
	

<table style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center;'>
	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Merchant Rating:</b></nobr>
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Processing Fee:</b></nobr>
			</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Payout Schedule:</b></nobr>
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			99.0% - 100%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			30 Days
		</td>

	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			98.0 - 98.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			97.0 - 97.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			96.0 - 96.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			95.0 - 95.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			13.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			35 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			94.0 - 94.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			14.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			40 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			93.0 - 93.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			16.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			45 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			92.0 - 92.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			18.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			50 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			91.0 - 91.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			20.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			55 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			90.0 - 90.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			25.0%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			60 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			< 90%
		</td><td colspan='2' style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			(account deactivation and review)
		</td>
	</tr>
	
	
</table>";



	} else { /// DEFAULT
	
		$dynamic_schedule['profile_name'] = $master_config_default_gateway;
		$dynamic_schedule['starting_fee'] = "9.9%";
		$dynamic_schedule['starting_payout_schedule'] = "15 Days";
		$dynamic_schedule['profile_html_table'] = "
	

<table style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center;'>
	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Merchant Rating:</b></nobr>
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Processing Fee:</b></nobr>
			</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			<nobr><b>Dynamic Payout Schedule:</b></nobr>
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			99.0% - 100%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			9.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#00AA00;'>
			15 Days
		</td>

	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			98.0 - 98.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			10.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			20 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			97.0 - 97.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			11.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			25 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			96.0 - 96.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			12.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			30 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			95.0 - 95.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			13.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			35 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			94.0 - 94.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			14.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			40 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			93.0 - 93.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			16.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			45 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			92.0 - 92.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			18.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			50 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			91.0 - 91.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			20.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			55 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			90.0 - 90.9%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			25.0%
		</td><td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px;'>
			60 Days
		</td>
	</tr>

	<tr>
		<td style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			< 90%
		</td><td colspan='2' style='border-style:solid; border-color:#444444; border-width:1px; border-collapse:collapse; padding:5px; text-align:center; width:260px; color:#888888;'>
			(account deactivation and review)
		</td>
	</tr>
	
	
</table>";
	
	
	
	
	}
	
	return $dynamic_schedule;
	
}





function void_a_refund($transactionid) {
	
	$tmp_datetime = datetime();
	
	$the_three_transaction_details = get_the_three_transactions($transactionid);
	

	test("the_three_transaction_details",$the_three_transaction_details);
	


	/// TRANSLOG
	$tmp_sql = "
	UPDATE translog
	SET status = ''
	, datetime_updated = '". $tmp_datetime ."'
	WHERE translogid = '". $the_three_transaction_details['translog']['translogid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("update translog",$update);

	/// set the correct status
	$status_reset = "Approved";
	if($the_three_transaction_details['deposit']['requested_datetime'] < date("Y-m-d H:i:s",strtotime("-".$the_three_transaction_details['incoming']['DTR'] ." days"))) {
		$status_reset = "Completed";
	}
	
	/// CUSTOMER DEPOSIT
	$tmp_sql = "
	UPDATE transactions
	SET status = '". $status_reset ."'
	,return_datetime = NULL
	,return_reason = NULL
	,return_account_balance_before = NULL
	,return_account_balance_after = NULL
	,return_available_balance_before = NULL
	,return_available_balance_after = NULL
	,return_effects_merchant_rating = NULL
	, updated_datetime = '". $tmp_datetime ."'
	WHERE transactionid = '". $the_three_transaction_details['deposit']['transactionid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("CUSTOMER DEPOSIT",$update);

	/// CUSTOMER OUTGOING
	$tmp_sql = "
	UPDATE transactions
	SET status = '". $status_reset ."'
	,return_datetime = NULL
	,return_reason = NULL
	,return_account_balance_before = NULL
	,return_account_balance_after = NULL
	,return_available_balance_before = NULL
	,return_available_balance_after = NULL
	,return_effects_merchant_rating = NULL
	, updated_datetime = '". $tmp_datetime ."'
	WHERE transactionid = '". $the_three_transaction_details['outgoing']['transactionid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("CUSTOMER OUTGOING",$update);
	
	/// BUSINESS INCOMING
	$tmp_sql = "
	UPDATE transactions
	SET status = '". $status_reset ."'
	,return_datetime = NULL
	,return_reason = NULL
	,return_account_balance_before = NULL
	,return_account_balance_after = NULL
	,return_available_balance_before = NULL
	,return_available_balance_after = NULL
	,return_effects_merchant_rating = NULL
	, updated_datetime = '". $tmp_datetime ."'
	WHERE transactionid = '". $the_three_transaction_details['incoming']['transactionid'] ."';
	";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("BUSINESS INCOMING",$update);


	/// BUSINESS BALANCE
	$balance_before_update = balance($the_three_transaction_details['incoming']['accountid']);
	$new_account_balance = currency_format($balance_before_update['account_balance'] + $the_three_transaction_details['incoming']['transaction_net_value']);
	
	
	$tmp_sql = "
	UPDATE balances
	SET account_balance = '". $new_account_balance ."'
	, updated = '". $tmp_datetime ."'
	WHERE accountid = '". $the_three_transaction_details['incoming']['accountid'] ."'
	AND platform = 'BANGK.com'
	AND currency_iso3 = 'USD'
	;";
	test("tmp_sql",$tmp_sql);
	$update = updateTHECASHIER($tmp_sql);
	test("BUSINESS BALANCE",$update);
	
}



function country2iso3($country) {
	$country = trim($country);
	if(strlen($country)==3) return $country;
	return geo_data($country,"printable_name","iso3");	
}

function country2printable($country) {
	$country = trim($country);
	if(strlen($country)!=3) return $country;
	return geo_data($country,"iso3","printable_name");	
}



function clear_identities_and_wallets($business_accountid='',$creator_memberid='') {
	
	### GET MEMBERID
	if(
	(empty($creator_memberid)) &&
	(!empty($business_accountid))
	) {	
	
		$tmp_sql = "SELECT creator_memberid FROM accounts WHERE accountid = '". $business_accountid ."';";
		$creator_memberid = getTHECASHIER($tmp_sql);
		
	} else {
	
		$creator_memberid = $creator_memberid;
	
	}




	### IDS_PERSONAL 
	if(
	(!empty($creator_memberid))
	) {
	
		/// clear ids_personal
		$tmp_sql = "UPDATE ids_personal
		SET 
		status = 'CLEARED', 
		datetime_updated = '". datetime() ."'
		WHERE 
		memberid = '". $creator_memberid ."'
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%' OR status = 'VERIFIED')
		;";
		logger3("tmp_sql",$tmp_sql);
		$clear_old_submissions = updateTHECASHIER($tmp_sql);
		logger3("clear_old_submissions",$clear_old_submissions);
	}

	
	### IDS_BUSINESS & WALLET
	if(
	(!empty($creator_memberid))
	) {
	
		//test("clear_identities_and_wallets(): business_accountid",$business_accountid);
	
		/// clear ids_business
		$tmp_sql = "UPDATE ids_business
		SET 
		status = 'CLEARED', 
		datetime_updated = '". datetime() ."'
		WHERE 
		memberid = '". $creator_memberid ."'
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%' OR status = 'VERIFIED')
		;";
		//test("tmp_sql",$tmp_sql);
		$clear_old_submissions = updateTHECASHIER($tmp_sql);
		//test("clear_old_submissions",$clear_old_submissions);
		
		
		/// clear ids_business
		$tmp_sql = "UPDATE wallets
		SET 
		status = 'CLEARED', 
		datetime_updated = '". datetime() ."'
		WHERE 
		memberid = '". $creator_memberid ."'
		AND (status = 'SUBMITTED' OR status LIKE '%HOLD%' OR status = 'VERIFIED')
		;";
		//test("tmp_sql",$tmp_sql);
		$clear_old_submissions = updateTHECASHIER($tmp_sql);
		//test("clear_old_submissions",$clear_old_submissions);
	
	}
}



function get_ids_personal($memberid='',$accountid='') {


	if(!empty($memberid)) $add_memberid = "AND memberid = '". $memberid ."'";
	if(!empty($accountid)) $add_accountid = "AND accountid = '". $accountid ."'";

	### CURRENT IDENTITY
	// $current_account_identity_details = "";
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// accountid = '". $parent_accountid ."' 
	// AND 
	// (
	// (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL) OR
	// (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	// )
	// AND business_name = '". $tmp_account['accountname'] ."'
	// ;";
	 
	$current_account_identity_details = "";
	$tmp_sql = "SELECT * FROM ids_personal 
	WHERE 
	photo_id_filename != '' 
	AND photo_id_filename IS NOT NULL
	AND (proof_of_residence_filename IS NULL OR proof_of_residence_filename = '')
	$add_memberid
	$add_accountid
	ORDER BY datetime_created DESC
	;";
	 
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_personal['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
	//test("zzz. tmp_account['current']['identity']",$tmp_account['current']['identity']);
	 
	### CURRENT LOCATION
	$verified_account_location_details = "";
	//$tmp_sql = "SELECT * FROM ids_business 
	//WHERE 
	//accountid = '". $parent_accountid ."' 
	//AND 
	//(
	//(proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL) OR 
	//(business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	//)
	//AND business_name = '". $tmp_account['accountname'] ."'
	//;";
	 
	$tmp_sql = "SELECT * FROM ids_personal 
	WHERE 
	proof_of_residence_filename != '' 
	AND proof_of_residence_filename IS NOT NULL
	AND (photo_id_filename IS NULL OR photo_id_filename = '')
	$add_memberid
	$add_accountid
	ORDER BY datetime_created DESC
	;";
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_personal['current']['location'] = object2array(readTHECASHIER($tmp_sql));
	//test("tmp_account['current']['location']",$tmp_account['current']['location']);
	
	return $tmp_ids_personal;
}


function get_ids_business($memberid='',$accountid='') {


	//test("accountid",$accountid);
	//exit;
	// get business type
	if(!empty($accountid)) {
		
		$business_details = readTHECASHIER("SELECT * FROM accounts WHERE accountid = '". $accountid ."';");
		
		if(stristr($business_details->business_type,"PDBA")) {
			$ids_personal_details = get_ids_personal($memberid=$business_details->creator_memberid,$accountid='');
			//exit;
		}
	}



	if(!empty($memberid)) $add_memberid = "AND memberid = '". $memberid ."'";
	if(!empty($accountid)) $add_accountid = "AND accountid = '". $accountid ."'";

	### CURRENT IDENTITY
	// $current_account_identity_details = "";
	// $tmp_sql = "SELECT * FROM ids_business 
	// WHERE 
	// accountid = '". $parent_accountid ."' 
	// AND 
	// (
	// (business_certificate_filename != '' AND business_certificate_filename IS NOT NULL) OR
	// (business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	// )
	// AND business_name = '". $tmp_account['accountname'] ."'
	// ;";
	 
	$current_account_identity_details = "";
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE 
	business_certificate_filename != '' 
	AND business_certificate_filename IS NOT NULL
	AND (proof_of_business_location_filename IS NULL OR proof_of_business_location_filename = '')
	$add_memberid
	$add_accountid
	ORDER BY datetime_created DESC
	;";
	 
	//if($accountid == 5538) test("get_ids_business(): tmp_sql",$tmp_sql);
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['identity'] = object2array(readTHECASHIER($tmp_sql));
	//test("zzz. tmp_account['current']['identity']",$tmp_account['current']['identity']);
	 
	### CURRENT LOCATION
	$verified_account_location_details = "";
	//$tmp_sql = "SELECT * FROM ids_business 
	//WHERE 
	//accountid = '". $parent_accountid ."' 
	//AND 
	//(
	//(proof_of_business_location_filename != '' AND proof_of_business_location_filename IS NOT NULL) OR 
	//(business_legal_extension LIKE '%DBA' OR business_legal_extension = 'GROUP')
	//)
	//AND business_name = '". $tmp_account['accountname'] ."'
	//;";
	 
	$tmp_sql = "SELECT * FROM ids_business 
	WHERE 
	proof_of_business_location_filename != '' 
	AND proof_of_business_location_filename IS NOT NULL
	AND (business_certificate_filename IS NULL OR business_certificate_filename = '')
	$add_memberid
	$add_accountid
	ORDER BY datetime_created DESC
	;";
	 
	//test("tmp_sql",$tmp_sql);
	$tmp_ids_business['current']['location'] = object2array(readTHECASHIER($tmp_sql));
	//test("tmp_account['current']['location']",$tmp_account['current']['location']);
	
	if(!empty($ids_personal_details)) {
		
		$tmp_ids_business['current']['identity']['status'] = $ids_personal_details['current']['identity']['status'];
		$tmp_ids_business['current']['location'] = $ids_personal_details['current']['location'];
	}
	
	return $tmp_ids_business;
}


function is_this_business_account_verified($business_accountid) {
	
	$tmp_ids_business = get_ids_business($memberid='',$accountid=$business_accountid);
	//test("tmp_ids_business",$tmp_ids_business);
	
	$tmp_sql = "SELECT creator_memberid FROM accounts WHERE accountid = '". $business_accountid ."';";
	$business_owner_memberid = getTHECASHIER($tmp_sql);
	$tmp_ids_personal = get_ids_personal($memberid=$business_owner_memberid,$accountid='');
	//test("tmp_ids_personal",$tmp_ids_personal);
	
	
	if(
	(stristr($tmp_ids_personal['current']['identity']['status'],'VERIFIED')) &&
	(stristr($tmp_ids_personal['current']['location']['status'],'VERIFIED')) &&
	(stristr($tmp_ids_business['current']['identity']['status'],'VERIFIED')) &&
	(stristr($tmp_ids_business['current']['location']['status'],'VERIFIED'))
	) {
		return "VERIFIED";
	} else {
		return FALSE;
	}
}

function authorization_template_original_text_to_html($original_text) {
		
		/// clear for testing:
		//$_SESSION['voice_authorization_api'] = "";
		
		//test("1. original_text",$original_text);
	
		###
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_AMOUNT'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_AMOUNT'] = "<span style='color:#888888;'>[amount]</span>";
		}
		
		
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'] = "<span style='color:#888888;'>[amount_recurring]</span>";
		}
		
		
		
		if(isset($_SESSION['voice_authorization_api']['business_account_details'])) {
			$business_subcategory = MCC2TEXT($_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']);
		} else {
			$business_subcategory = MCC2TEXT($_SESSION['account']['business_subcategory']);
		}
		
		
		
		
		
		### If GATEWAY:
		logger3("_SESSION['template']['company']['text_name']",$_SESSION['template']['company']['text_name']);
		logger3("business_subcategory",$business_subcategory);
		logger3("_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']",$_SESSION['voice_authorization_api']['business_account_details']['business_subcategory']);
		logger3("_SESSION['voice_authorization_api']['business_account_details']['business_category']",$__SESSION['voice_authorization_api']['business_account_details']['business_category']);
		logger3("_SESSION['account']['business_subcategory']",$_SESSION['account']['business_subcategory']);
		
		if(
		(stristr($_SESSION['template']['company']['text_name'],"VOCASIGN")) &&
		(
		(stristr($business_subcategory,"GATEWAY")) ||
		(stristr($_SESSION['voice_authorization_api']['business_account_details']['business_subcategory'],"GATEWAY")) ||
		(stristr($_SESSION['voice_authorization_api']['business_account_details']['business_category'],"GATEWAY")) ||
		(stristr($_SESSION['account']['business_subcategory'],"GATEWAY"))
		)
		
		) {

			//test("2. business_subcategory",$business_subcategory);
			/// POSSIBLE GATEWAY VARS:
			
			logger3("2. _SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
			
			//$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']
			
			
			//test("2. _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
			//exit;
			
			/// set account business name
			$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = $_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'];
			
			if(!empty($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'])) {
				
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'];
					
			}
			
			logger3("_SESSION['voice_authorization_api']",$_SESSION['incoming_authorization_api']);
			
			
			
			
			if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'])) {
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = "<span style='color:#888888;'>[merchant name]</span>";
			}
			
			
			$submerchant_account_details = account($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_MID']);
			
			
			if($submerchant_account_details['business_subcategory']) $_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = $submerchant_account_details['business_subcategory'];
			
			
			
			if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'])) {
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = "<span style='color:#888888;'>[merchant category]</span>";
			}
		

			if(!empty($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'])) {
				
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = MCC2TEXT($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']);
					
			}
		
		
		
		} else { ///nomral:
		
			//test("_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']);
			
			/// set account business name
			if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'])) {
			
				$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'] = "<span style='font-size:105%;'>". $_SESSION['account']['accountname'] ." ". $_SESSION['account']['business_type'] ."</span>";
			
			}
			
			global $business_account_details;
			
			//test("business_account_details",$business_account_details);
			
			
			
			if(!empty($business_account_details)) {
				
				$tmp_merchant_AUTHORIZATION_BUSINESS_CATEGORY = MCC2TEXT($business_account_details['business_subcategory']);
				
			} else {
				
				$tmp_merchant_AUTHORIZATION_BUSINESS_CATEGORY = MCC2TEXT($_SESSION['account']['business_subcategory']); //  ." ". $_SESSION['account']['business_category'];
				
			}
			
			
			$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'] = strtolower($tmp_merchant_AUTHORIZATION_BUSINESS_CATEGORY);
			
			
		}
		
		//AUTHORIZATION_BUSINESS_CATEGORY
		
		
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] = "<span style='color:#888888;'>[customer name]</span>";
		}

		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'] = "<span style='color:#888888;'>[time of authorization]</span>";
		}
			
		
		//$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_FIRST_DIGIT'] = "";
		
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_LAST4_DIGITS'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_LAST4_DIGITS'] = "<span style='color:#888888;'>[last 4 digits]</span>";
		}
		
		// not an api paramater -- only for template transalation.  get brand from first-digit
		if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND'] = "<span style='color:#888888;'>[card brand]</span>";
		}
		




                if(empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_PASSPHRASE'])){
                    $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_PASSPHRASE'] = "<span style='color:#888888;' id='customer_secret_passphrase'>[customer secret passphrase]</span>";
                }




		###
		$original_text = str_replace("AUTHORIZATION_AMOUNT","$". $_SESSION['voice_authorization_api']['AUTHORIZATION_AMOUNT'],$original_text);
		$original_text = str_replace("AUTHORIZATION_RECURRING_AMOUNT","$". $_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'],$original_text);
		
		
		$tmp_AUTHORIZATION_BUSINESS_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']);
		$original_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$tmp_AUTHORIZATION_BUSINESS_NAME,$original_text);
		
		
		## test("_SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
		## 
		## AUTHORIZATION_MERCHANT_CATEGORY
		## 
		## AUTHORIZATION_BUSINESS_CATEGORY
		
		
		### SET BUSINESS CTEGORY
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'])) $tmp_category = $_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'];
		
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'])) $tmp_category = $_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'];
		
		if(!empty($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'])) $tmp_category = MCC2TEXT($_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']);
		
		//test("_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']",$_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC']);
		
		
		if(!empty($tmp_category)) {
			
			$original_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$tmp_category,$original_text);
		}
		
		
		

		$original_text = str_replace("AUTHORIZATION_CUSTOMER_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'],$original_text);
		
		
		$original_text = str_replace("AUTHORIZATION_CUSTOMER_TIME",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'],$original_text);
		//$original_text = str_replace("AUTHORIZATION_CARD_FIRST_DIGIT",$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_FIRST_DIGIT'],$original_text);
		$original_text = str_replace("AUTHORIZATION_CARD_LAST4_DIGITS",$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_LAST4_DIGITS'],$original_text);
		$original_text = str_replace("AUTHORIZATION_CARD_BRAND",$_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND'],$original_text);

		$original_text = str_replace("AUTHORIZATION_CUSTOMER_PASSPHRASE",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_PASSPHRASE'],$original_text);
        
        
        
        $original_text = str_replace("[speak your secret passphrase]","<span style='color:#E77D76;'>[speak your secret passphrase]</span>",$original_text);

		###
		$original_text = str_replace("\\n","<br>",$original_text);
		$original_text = str_replace("\\r","<br>",$original_text);
		$original_text = str_replace("
","<br>",$original_text);

		
		//test("2. original_text",$original_text);
		
		return $original_text;
		
		
		
}



function authorization_template_original_text_to_grammar($original_text) {
	
	logger3("authorization_template_original_text_to_grammar(): original_text",$original_text);
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
	
	$personalized_text = "";
	$personalized_text = $original_text;
	
	### REPLACE SINGLE DIGITS WITH WORDS:
	$personalized_text = str_replace(" 1 "," one ",$personalized_text);
	$personalized_text = str_replace(" 2 "," two ",$personalized_text);
	$personalized_text = str_replace(" 3 "," three ",$personalized_text);
	$personalized_text = str_replace(" 4"," four ",$personalized_text);
	$personalized_text = str_replace(" 5 "," five ",$personalized_text);
	$personalized_text = str_replace(" 6 "," six ",$personalized_text);
	$personalized_text = str_replace(" 7 "," seven ",$personalized_text);
	$personalized_text = str_replace(" 8 "," eight ",$personalized_text);
	$personalized_text = str_replace(" 9 "," nine ",$personalized_text);
	$personalized_text = str_replace(" 10 "," ten ",$personalized_text);
	$personalized_text = str_replace(" 72 "," seventy two ",$personalized_text);
	$personalized_text = str_replace(" 100% "," one hundred percent ",$personalized_text);
	
	### CUSTOMER AUTHORZATION TIME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'])) {
		$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_TIME","<ruleref uri='builtin:/grammar/date'/> at <ruleref uri='builtin:/grammar/time'/>",$personalized_text);
	}
	
	
	/// NAME=FIRSTNAME+LASTNAME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) {
		$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
		
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] .= " ". $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
		}
	}
	
	$tmp_AUTHORIZATION_CUSTOMER_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME']);
	$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_NAME",$tmp_AUTHORIZATION_CUSTOMER_NAME,$personalized_text);
	
        
        
        
        
        ##PASSPHRASE + NEGATIVE WORDS
        if(isset($_SESSION['voice_authorization_api']['biometric_passphrase'])){                
        
        
            $personalized_text = str_replace("[speak your secret passphrase]","
            
            	<one-of>
            	
            		<item>
            			". $_SESSION['voice_authorization_api']['biometric_passphrase'] ."
            		</item>

            		<item>
						speak your secret passphrase
					</item>

            		<item>
						speak my secret passphrase
					</item>
					
            		<item>
						my secret passphrase
					</item>

            		<item>
						your secret passphrase
					</item>
						
            		<item>
						my voice is my passport
					</item>

            		<item>
						my voice is my password
					</item>
					
            		<item>
						blah blah blah
					</item>

            		<item>
						something something something
					</item>
					
            		<item>
						whatever whatever whatever
					</item>
					
								
				</one-of>

            	",$personalized_text);
            	
        
        }
        
        
        
        
        
        
        
	### CUSTOMER AMOUNT (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'])) {
		$personalized_text = str_replace("AUTHORIZATION_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	
	### CUSTOMER AMOUNT_RECIURRING (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'])) {
		$personalized_text = str_replace("AUTHORIZATION_RECURRING_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	### IF GATEWAY VARS ARE SET:
	
	
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
	//exit;
	
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'])) {
	
		### GATEWAY MERCHANT DETAILS:
		$tmp_AUTHORIZATION_MERCHANT_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$tmp_AUTHORIZATION_MERCHANT_NAME,$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'],$personalized_text);
		
	} else { //normal:
		
		### BUSINESS DETAILS:
		$tmp_AUTHORIZATION_BUSINESS_NAME = trim($_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME']);
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$tmp_AUTHORIZATION_BUSINESS_NAME,$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'],$personalized_text);
	}
	
	
	
	
	
	### CARD DETAILS:
	$personalized_text = str_replace("AUTHORIZATION_CARD_LAST4_DIGITS","<ruleref uri='builtin:/grammar/digits?length=4'/>",$personalized_text);
	$card_brand = first_digit_to_card_brand($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND']);
	$personalized_text = str_replace("AUTHORIZATION_CARD_BRAND",$card_brand,$personalized_text);


	### VOCAPASS UPDATE:
	// note $_SESSION['voice_authorization_api']['UPDATE_PIN'] will be set in api. 
	$personalized_text = str_ireplace("[speak your 12-digit update PIN]",$_SESSION['voice_authorization_api']['UPDATE_PIN'],$personalized_text);
	
	
	/// .com -> "dot com"
	$personalized_text = str_ireplace(".com"," dot com",$personalized_text);
	$personalized_text = str_ireplace(".org"," dot org",$personalized_text);
	$personalized_text = str_ireplace(".net"," dot net",$personalized_text);
	
	
	### FINAL PATCHES:
	$personalized_text = str_replace("...","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(",","",$personalized_text);
	$personalized_text = str_replace(".","",$personalized_text);
	$personalized_text = str_replace("\\n"," ",$personalized_text);
	$personalized_text = str_replace("\\r"," ",$personalized_text);
	$personalized_text = str_replace("
"," ",$personalized_text);
	
	//$personalized_text = str_replace("\n"," ",$personalized_text);
	//$personalized_text = str_replace("\r"," ",$personalized_text);
	
	
	
	

	$originate_grammar = "";
	
	$originate_grammar .= "<?xml version='1.0' encoding ='iso-8859-1'?>";
	$originate_grammar .= "<!DOCTYPE grammar PUBLIC '-//W3C//DTD GRAMMAR 1.0//EN' 'http://www.w3.org/TR/speech-grammar/grammar.dtd'>";
	$originate_grammar .= "<grammar version='1.0' xmlns='http://www.w3.org/2001/06/grammar' xml:lang='en-GB' mode='voice' root='main_rule'>";
	$originate_grammar .= "<rule id='main_rule' scope='public'>";
	$originate_grammar .= "<one-of>";
	$originate_grammar .= "<item xml:lang='en-GB'>";
	
	
	$originate_grammar .= $personalized_text;
	
	
	$originate_grammar .= "</item>";
	$originate_grammar .= "<item xml:lang='en-US'>";
	
	
	$originate_grammar .= $personalized_text;
	
	
	$originate_grammar .= "</item>";
	$originate_grammar .= "</one-of>";	
	$originate_grammar .= "</rule>";
	$originate_grammar .= "</grammar>";
	
	logger3("authorization_template_original_text_to_grammar(): originate_grammar",$originate_grammar);
	return $originate_grammar;
	
	
	
	
	
	
	
	
	
	
}



function authorization_template_original_text_to_grammar_ATT($original_text) {
	
	logger3("authorization_template_original_text_to_grammar(): original_text",$original_text);
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);
	
	$personalized_text = "";
	$personalized_text = $original_text;
	
	### REPLACE SINGLE DIGITS WITH WORDS:
	$personalized_text = str_replace(" 1 "," one ",$personalized_text);
	$personalized_text = str_replace(" 2 "," two ",$personalized_text);
	$personalized_text = str_replace(" 3 "," three ",$personalized_text);
	$personalized_text = str_replace(" 4"," four ",$personalized_text);
	$personalized_text = str_replace(" 5 "," five ",$personalized_text);
	$personalized_text = str_replace(" 6 "," six ",$personalized_text);
	$personalized_text = str_replace(" 7 "," seven ",$personalized_text);
	$personalized_text = str_replace(" 8 "," eight ",$personalized_text);
	$personalized_text = str_replace(" 9 "," nine ",$personalized_text);
	$personalized_text = str_replace(" 10 "," ten ",$personalized_text);
	$personalized_text = str_replace(" 72 "," seventy two ",$personalized_text);
	$personalized_text = str_replace(" 100% "," one hundred percent ",$personalized_text);
	
	### CUSTOMER AUTHORZATION TIME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TIME'])) {
		$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_TIME","<ruleref uri='builtin:/grammar/date'/> at <ruleref uri='builtin:/grammar/time'/>",$personalized_text);
	}
	
	
	/// NAME=FIRSTNAME+LASTNAME
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) {
		$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
		
		if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) {
			$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'] .= " ". $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
		}
	}
	
	$personalized_text = str_replace("AUTHORIZATION_CUSTOMER_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'],$personalized_text);
	
        ##PASSPHRASE
        if(isset($_SESSION['voice_authorization_api']['biometric_passphrase'])){                
            $personalized_text = str_replace("[your customer will be prompted for her/his secret passphrase]",$_SESSION['voice_authorization_api']['biometric_passphrase'],$personalized_text);
        }
        
        
	### CUSTOMER AMOUNT (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'])) {
		$personalized_text = str_replace("AUTHORIZATION_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	
	### CUSTOMER AMOUNT_RECIURRING (USD)
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_RECURRING_AMOUNT'])) {
		$personalized_text = str_replace("AUTHORIZATION_RECURRING_AMOUNT","<item xml:lang='en-US'><ruleref uri='builtin:/grammar/currency'/></item>",$personalized_text);
	}
	
	### IF GATEWAY VARS ARE SET:
	
	
	logger3("authorization_template_original_text_to_grammar(): _SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME']);
	//exit;
	
	if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'])) {
	
		### GATEWAY MERCHANT DETAILS:
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_NAME'],$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_MERCHANT_CATEGORY'],$personalized_text);
		
	} else { //normal:
		
		### BUSINESS DETAILS:
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_NAME",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_NAME'],$personalized_text);
		
		$personalized_text = str_replace("AUTHORIZATION_BUSINESS_CATEGORY",$_SESSION['voice_authorization_api']['AUTHORIZATION_BUSINESS_CATEGORY'],$personalized_text);
	}
	

	
	
	### CARD DETAILS:
	$personalized_text = str_replace("AUTHORIZATION_CARD_LAST4_DIGITS","<ruleref uri='builtin:/grammar/digits?length=4'/>",$personalized_text);
	$card_brand = first_digit_to_card_brand($_SESSION['voice_authorization_api']['AUTHORIZATION_CARD_BRAND']);
	$personalized_text = str_replace("AUTHORIZATION_CARD_BRAND",$card_brand,$personalized_text);
	
	### VOCAPASS UPDATE:
	// note $_SESSION['voice_authorization_api']['UPDATE_PIN'] will be set in api. 
	$personalized_text = str_ireplace("[speak your 12-digit update PIN]",$_SESSION['voice_authorization_api']['UPDATE_PIN'],$personalized_text);

	### VOCAPASS UPDATE:
	// note $_SESSION['voice_authorization_api']['RESET_PIN'] will be set in api. 
	$personalized_text = str_ireplace("[speak your 12-digit reset PIN]",$_SESSION['voice_authorization_api']['RESET_PIN'],$personalized_text);
	
	
	
	
	
	### FINAL PATCHES:
	$personalized_text = str_replace("...","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(";","",$personalized_text);
	$personalized_text = str_replace(",","",$personalized_text);
	$personalized_text = str_replace(".","",$personalized_text);
	$personalized_text = str_replace("\\n"," ",$personalized_text);
	$personalized_text = str_replace("\\r"," ",$personalized_text);
	$personalized_text = str_replace("
"," ",$personalized_text);
	
	//$personalized_text = str_replace("\n"," ",$personalized_text);
	//$personalized_text = str_replace("\r"," ",$personalized_text);
	
	
	
	

	$originate_grammar = "";
	

	$originate_grammar .= "<grammar xml:lang='en-US' root='main_rule'>";
	$originate_grammar .= "<rule id='main_rule' scope='public'>";
	$originate_grammar .= "<item>";
        //$originate_grammar .= "<item>";
	
	
	$originate_grammar .= $personalized_text;
	
        
	//$originate_grammar .= "</item>";
	$originate_grammar .= "</item>";
	$originate_grammar .= "</rule>";
	$originate_grammar .= "</grammar>";
	
	logger3("authorization_template_original_text_to_grammar_ATT(): originate_grammar",$originate_grammar);
	return $originate_grammar;
	
	
	
	
	
	
	
	
	
	
}





function MCC2TEXT($MCC) {
	
	### SERVICES
	if($MCC == "7995") return "gambling services";
	if($MCC == "7379") return "technical support services";
	if($MCC == "4818") return "telecommunication services";
	if($MCC == "7994") return "gaming services";
	if($MCC == "8999") return "professional consulting services";
	if($MCC == "5962") return "travel services";
	if($MCC == "7311") return "marketing services";
	if($MCC == "5967") return "digital download services";
	if($MCC == "8398") return "a non-profit donation";
	
	### PRODCUTS
	if($MCC == "7296") return "fashion products";
	if($MCC == "5732") return "electronic products";
	if($MCC == "5734") return "software products";
	if($MCC == "5122") return "nutraceuticals products";
	if($MCC == "0000") return "gateway";
}


//check if account has enough money and debit amount if already exists
function debit_money_from_account($account_hash,$amount){

	
    $tmp_account = account($account_hash);
    //test('tmp_account', $tmp_account);
    
    $tmp_balance = balance($tmp_account['accountid']);
    //test('tmp_balance', $tmp_balance);
    
    
    
	if(
	(stristr($_SESSION['template']['company']['text_name'],"VOCASIGN")) &&
	(stristr($_SESSION['account']['business_subcategory'],"GATEWAY"))
	) { // SPECIAL GATEWAY BALANCE


		$balance = $tmp_balance['vocasign_gateway'];
		$balance = $balance + $amount;


	} else { // NORMAL
		
	
    	$balance = $tmp_balance['account_balance'];
		
		
    	if(($balance - $amount) < 0) return "NOT_ENOUGH_MONEY";
		
    	//test('balance before', $balance);
    	//Update balance
    	$balance = $balance - $amount;
    	//test('balance after', $balance);
    }
		
    
    $query = "UPDATE balances SET account_balance = ". $balance." WHERE balanceid=". $tmp_balance['balanceid'] ." AND accountid=". $tmp_balance['accountid'] ."";    
    $tmp_update_balance = updateTHECASHIER($query);
    //test('query', $query);
    //test('tmp_update_balance', $tmp_update_balance);
    
	return "OK";
	
}



function vocapass_preferences($accountid) {
	return vocasign($accountid);
}

function vocasign($accountid) {
    $table_name = 'vocasign';
    if(stristr($_SESSION['template']["company"]["text_name"],"vocaPASS")) {
        $table_name = 'vocapass_preferences'; 
    }
	$tmp_sql = "SELECT * FROM ". $table_name ." WHERE accountid = '". $accountid ."';";
	logger3("vocasign(): tmp_sql",$tmp_sql);
	$sql_results = object2array(readTHECASHIER($tmp_sql));
	return $sql_results;
}


function first_digit_to_card_brand($first_digitof_card) {
	
	if($first_digitof_card == "3") {
		return "AMEX";
	} else 
	if($first_digitof_card == "4") {
		return "VISA";
	} else
	if($first_digitof_card == "5") {
		return "MasterCard";
	} else
	if($first_digitof_card == "6") {
		return "DISCOVER";
	} else {
		return  FALSE;
	}
}



function find_voip_rate($complete_phone_number,$voip_gateway='flowroute',$business_subcategory) {

	global $master_config_verisign_voip_rate_premium;
	
	//test("voip_gateway",$voip_gateway);
	
	//test("business_subcategory",$business_subcategory);
	
	if(stristr($business_subcategory,"GATEWAY")) {
	
	 	$rate = "0.50";
	 	//test("rate",$rate);
	 	///exit;
	 	return $rate;
	
	}
	
	
	while($complete_phone_number) {
	
		//test("complete_phone_number",$complete_phone_number);
		
		$tmp_sql = "SELECT * FROM $voip_gateway WHERE prefix = '". $complete_phone_number."';";
		$voip_details = readTHECASHIER($tmp_sql,"voip_rates");
		//test("voip_details",$voip_details);
		
		if(empty($voip_details->rate)) {
			$complete_phone_number = substr($complete_phone_number, 0, -1);
		} else {
			return $voip_details->rate * $master_config_verisign_voip_rate_premium;
		}	
	}
}


function log_biometric_registration_session() {

	//$_SESSION['']
	
	logger3("log_biometric_registration_session() _SESSION['voice_authorization_api']",$_SESSION['voice_authorization_api']);

	$biometric_registration_session_id = "";
	$email_verification_hash = hash_me();
        if(isset($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])){
           //$email_verification_hash = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
        }
	$ACCOUNT_NUMBER = $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'];
	$SERVICE_PASSWORD = $_SESSION['voice_authorization_api']['SERVICE_PASSWORD'];
	$AUTHORIZATION_TEMPLATE = $_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'];
	$CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
	
	$AUTHORIZATION_CUSTOMER_FIRSTNAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
	$AUTHORIZATION_CUSTOMER_LASTNAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
	$AUTHORIZATION_CUSTOMER_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_NAME'];
	
	$emailaddress = $_SESSION['voice_authorization_api']['CUSTOMER_EMAILADDRESS'];
	$verified_status = "";
	$datetime_created = datetime();
	$datetime_updated = $datetime_created;
	
	
	$tmp_sql = "INSERT into biometric_registration_session
	
	(
	biometric_registration_session_id,
	email_verification_hash,
	ACCOUNT_NUMBER,
	SERVICE_PASSWORD,
	AUTHORIZATION_TEMPLATE,
	CUSTOMER_SESSION_ID,
	AUTHORIZATION_CUSTOMER_FIRSTNAME,
	AUTHORIZATION_CUSTOMER_LASTNAME,
	emailaddress,
	verified_status,
	datetime_created,
	datetime_updated
	)
	
	VALUES
	
	(
	'$biometric_registration_session_id',
	'$email_verification_hash',
	'$ACCOUNT_NUMBER',
	'$SERVICE_PASSWORD',
	'$AUTHORIZATION_TEMPLATE',
	'$CUSTOMER_SESSION_ID',
	'$AUTHORIZATION_CUSTOMER_FIRSTNAME',
	'$AUTHORIZATION_CUSTOMER_LASTNAME',
	'$emailaddress',
	'$verified_status',
	'$datetime_created',
	'$datetime_updated'
	)";
	
	logger3("log_biometric_registration_session(): tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql);
	logger3("log_biometric_registration_session(): insert_results",$insert_results);
	return $email_verification_hash;

}


function authorization_cancel_update($business_set_user_status_url="",$CUSTOMER_SESSION_ID="") {

	logger3("authorization_cancel_update(): business_set_user_status_url",$business_set_user_status_url);
	logger3("authorization_cancel_update(): CUSTOMER_SESSION_ID",$CUSTOMER_SESSION_ID);
	
	if(empty($CUSTOMER_SESSION_ID)) $CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
	if(empty($CUSTOMER_SESSION_ID)) return "FAIL: NO URL";
	
	if($business_set_user_status_url) $tmp_url = $business_set_user_status_url;
	
	
	if(empty($tmp_url)) $tmp_url = $tmp_url = $_SESSION['voice_authorization_api']['vocasign_account_details']['business_set_user_status_url'];

	logger3("authorization_cancel_update(): tmp_url",$tmp_url);
	
	if(empty($tmp_url)) {
	
		return "FAIL: NO URL";
	
	} else {
	
		if(stristr("http",$tmp_url)) $tmp_url = "http://".$tmp_url;
		$tmp_properties = "CUSTOMER_SESSION_ID=". $CUSTOMER_SESSION_ID;
		$tmp_properties .= "&CUSTOMER_SESSION_STATUS=CANCELED";                    
		
		logger3("authorization_cancel_update(): tmp_url: " , $tmp_url);
		logger3("authorization_cancel_update(): tmp_properties: " , $tmp_properties);

		$tmp_kurl = kurl($tmp_url,$tmp_properties);
		logger3("authorization_cancel_update(): tmp_kurl: " , $tmp_kurl); 
		return TRUE;
	}
}



function insert_new_usergaent_details($memberid="",$useragent_data="") {
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	if(empty($memberid)) return "FAILED - NO MEMBERID";
	
	if(empty($useragent_data)) $useragent_data = $_SERVER['HTTP_USER_AGENT'];
	if(empty($useragent_data)) return "FAILED - NO HTTP_USER_AGENT";
	
	
	$tmp_sql = "INSERT INTO member_useragent_history (
	`useragentid`,
	`memberid`,
	`useragent_data`,
	`datetime` 
	) VALUES (
	'". $blank_useragentid ."',
	'". $memberid ."',
	'". $useragent_data ."',
	'". datetime() ."'
	);
	";
	logger3("insert_current_usergaent_details(): tmp_sql",$tmp_sql);
	$insert_results = insertTHECASHIER($tmp_sql);
	logger3("insert_current_usergaent_details(): insert_results",$insert_results);
	return $insert_results;
	
}


function match_usergaent_details($memberid="",$useragent_data="") {
	
	
	if(empty($memberid)) $memberid = $_SESSION['member']['memberid'];
	if(empty($memberid)) return "FAIL: NO MEMBERID";

	if(empty($useragent_data)) $useragent_data = $_SERVER['HTTP_USER_AGENT'];
	if(empty($useragent_data)) return "FAILED - NO HTTP_USER_AGENT";
	
	$tmp_sql = "SELECT useragent_data 
	FROM 
	member_useragent_history 
	WHERE
	memberid = '". $memberid ."' AND memberid != '' AND memberid != '0'
	ORDER BY datetime DESC 
	LIMIT 1
	;";
	
	logger3("match_current_usergaent_details(): tmp_sql",$tmp_sql);
	$known_useragent_data = getTHECASHIER($tmp_sql);
	logger3("match_current_usergaent_details(): useragent_data",$useragent_data);
	
	if($useragent_data == $known_useragent_data) {
	
		return "MATCH";
		
	} else {
		
		return "FAIL";
	}
	

}


function generate_vocapass_update_pin($MEMBER_BIOMETRIC_ID,$VOICE_AUTHORIZATION_CATEGORY,$voiceprintid) {
	
	$tmp_sql = "SELECT pin FROM vocaPASS_reset_pins WHERE MEMBER_BIOMETRIC_ID = '". $MEMBER_BIOMETRIC_ID ."' AND datetime_created > '". $tmp_48_hours_ago ."';";
	$already_exists = getTHECASHIER($tmp_sql);
	
	if(!empty($already_exists)) {
		
		$tmp_sql = "UPDATE vocaPASS_reset_pins SET datetime_created = '". datetime() ."' WHERE pin = '". $already_exists ."';";
		logger3("tmp_sql",$tmp_sql);
		$update_reults = updateTHECASHIER($tmp_sql);
		logger3("update_reults",$update_reults);
		return $already_exists;
		exit;
	}	
	
	
	$already_exists = "UNKNOWN";
	while(!empty($already_exists)) {
		$vocaPASS_update_pin = rand(100,999). "-". rand(100,999). "-". rand(100,999). "-". rand(100,999);
		$tmp_48_hours_ago = strtotime("-48 hours");
		$tmp_48_hours_ago = date("Y-m-d H:i:s",$tmp_48_hours_ago);
		$tmp_sql = "SELECT resetid FROM vocaPASS_reset_pins WHERE pin = '". $vocaPASS_update_pin ."' AND datetime_created > '". $tmp_48_hours_ago ."';";
		$already_exists = getTHECASHIER($tmp_sql);
	}

	$resetid = "";
	$memberid = "";
	$member_biometric_id = $MEMBER_BIOMETRIC_ID;
	$voiceprintid = $voiceprintid;
	$pin = $vocaPASS_update_pin;
	$category = $VOICE_AUTHORIZATION_CATEGORY;
	$datetime_created = datetime();
	$tmp_sql = "INSERT into vocaPASS_reset_pins (
		`resetid`,
		`memberid`,
		`member_biometric_id`,
		`voiceprintid`,
		`pin`,
		`category`,
		`datetime_created`
	) VALUES (
		'" . $resetid . "',
		'" . $memberid . "',
		'" . $member_biometric_id . "',
		'" . $voiceprintid . "',
		'" . $pin . "',
		'" . $category . "',
		'" . $datetime_created . "')
	;";
	logger3("tmp_sql",$tmp_sql);
	$vocaPASS_reset_pins_results = insertTHECASHIER($tmp_sql);
	return $vocaPASS_update_pin;
}



function audiofilename2voiceprintid($path_to_audio,$audio_file_name) {
	
	logger3("audiofilename2voiceprintid(): 000. path_to_audio",$path_to_audio);
	logger3("audiofilename2voiceprintid(): 000. audio_file_name",$audio_file_name);
	
	
	$tmp_audio_file_name = explode(".",$audio_file_name);
	
	if(!empty($tmp_audio_file_name[1])) {
		$audio_file_name = $tmp_audio_file_name[0];
	}
	
	
	$tmp_sql = "SELECT * FROM voicefiles WHERE 
				filename = '". $audio_file_name ."';
				";
	logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);
	
	$voicefiles_details = readTHECASHIER($tmp_sql);
	logger3("audiofilename2voiceprintid(): voicefiles_details",$voicefiles_details);
	
	
	
//	$tmp_sql = "SELECT DISTINCT voiceprintid FROM voiceprints WHERE voicefileid 
//				LIKE 
//				'". $voicefiles_details->voicefileid .",%'
//				,'%,". $voicefiles_details->voicefileid .",%'
//				,'%,". $voicefiles_details->voicefileid ."'
//				ORDER BY created ASC
//				LIMIT 1
//				;";
//	logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);
	
        
        
    $tmp_sql = "SELECT * FROM vocamatch_audio WHERE
        		audio_filename LIKE '%". $audio_file_name .".%';
        		";
        			
	logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);	
	$vocamatch_audio_details = readTHECASHIER($tmp_sql);
	logger3("audiofilename2voiceprintid(): vocamatch_audio_details",$vocamatch_audio_details);
	 
        
	$tmp_sql = "SELECT DISTINCT voiceprintid FROM voiceprints WHERE ";
    if($voicefiles_details->voicefileid) {
    	$tmp_sql .= "(voicefileids LIKE  '". $voicefiles_details->voicefileid .",%' OR voicefileids LIKE  '%,". $voicefiles_details->voicefileid .",%')";
    
    }
    else if($vocamatch_audio_details) {
            $tmp_sql .= "(vocamatch_audio_id = '".$vocamatch_audio_details->vocamatch_audio_id."' AND vocamatch_audio_id > '0')";
    }
    
    ///$tmp_sql .= " ORDER BY created ASC LIMIT 1;";
    $tmp_sql .= " ORDER BY created DESC LIMIT 1;";
    logger3("audiofilename2voiceprintid(): tmp_sql",$tmp_sql);
                
	$tmp_voiceprintid = getTHECASHIER($tmp_sql);
	logger3("audiofilename2voiceprintid(): tmp_voiceprintid",$tmp_voiceprintid);
	
	
	if(!empty($tmp_voiceprintid)) {
		
		$voiceprintid = $tmp_voiceprintid;
		logger3("audiofilename2voiceprintid(): 000_voiceprintid",$voiceprintid);
		
	} else { ### GENERATE A VOICEPRINT:
	
		$UUID = explode("_",$audio_file_name);
		if(!empty($UUID[1])) {
			$UUID = $UUID[0];
		} else {
			$UUID = $audio_file_name;
		}
        logger3("audiofilename2voiceprintid(): UUID",$UUID);
		$description = "Login";	
		logger3("audiofilename2voiceprintid(): path_to_audio",$path_to_audio);
		logger3("audiofilename2voiceprintid(): audio_file_name",$audio_file_name);
		logger3("audiofilename2voiceprintid(): description",$description);
		$voiceprintid = generate_voiceprint($path_to_audio,$audio_file_name,$description="Login");
		logger3("audiofilename2voiceprintid(): 111_voiceprintid",$voiceprintid);
	}
	
	logger3("audiofilename2voiceprintid(): 222_voiceprintid",$voiceprintid);
	return $voiceprintid;
	
}



function update_biometric_profiles($member_biometric_id,$voiceprintid) {

	logger3("update_biometric_profiles() member_biometric_id",$member_biometric_id);
	logger3("update_biometric_profiles() voiceprintid",$voiceprintid);
	
	$date_time = datetime();
	$tmp_sql = "INSERT into biometric_profiles (
	`biometric_profile_index_id`,
	`voiceprintid`,
	`member_biometric_id`,
	`datetime_created`,
	`datetime_updated`
	) VALUES (
	'" . $tmp_biometric_profile_index_id . "',
	'" . $voiceprintid . "',
	'" . $member_biometric_id . "',
	'" . $date_time . "',
	'" . $date_time . "'
	);";
	logger3("update_biometric_profiles() tmp_sql",$tmp_sql);
	$biometric_profile_index_id = insertTHECASHIER($tmp_sql);
	logger3("update_biometric_profiles() RETURN biometric_profile_index_id",$biometric_profiles_id);
	
	return $biometric_profile_index_id;
}



function check_biometrics_now($check_type, $filename, $voiceprintids, $tolerance, $return_format="") {
    global $logging;
    global $master_config_ibmsiv_host;
    global $master_config_testing_biometric_matching;

    # prepare session:
    logger3("
    
    
    
    
    
    
    
    START: check_biometrics_now()
    
    
    
    ", $a);
    logger3("### BUILD THE LOOK-UP SESSIONS...", $a);
    logger3('filename:', $filename);
    logger3('voiceprintids:', $voiceprintids);
    logger3("Check Type:", $check_type);
    logger3("Tolerance:", $tolerance);


    ### PREP VARS:
    $response = NULL;
    $response = array();
    $results = NULL;
    $results = array();


    ##############################################################################


    $mh = curl_multi_init();


    $possible_duplicates = NULL;
    $possible_duplicates = array();
    $pd = 0;
    //$fn = 0;
    $master_counter = 0;
    //while (isset($filenames[$fn])) {
    //logger3("filenames[$fn]: ", $filenames[$fn]);


    ##############################################################################
    # prepare requests / handles:

    $i = 0;
    //while (isset($voiceprintids[$i])) {
	foreach($voiceprintids as $key => $voiceprintid) {
        //logger3("[i]: [", $i . "]", $a);
        logger3("voiceprintid: ", $voiceprintid);

        # set url:
        $siv_url = "http://" . $master_config_ibmsiv_host . "/ibmsiv/score";

        #set parameters for sv:
        logger3("mmmmmm_filename",$filename);
        
        $parameters = "voiceprint=". $voiceprintid ."&input-wave-uri=". $filename;
        
        logger3("SIV_URL", $siv_url . "?" . $parameters);



        # initialize:
        $ch[$master_counter] = curl_init();
        //logger3("ch[$vp]: ", $ch[$master_counter]);
        #set headers:
        curl_setopt($ch[$master_counter], CURLOPT_HEADER, 0);

        #set number of parameters
        curl_setopt($ch[$master_counter], CURLOPT_POST, 1);

        # dunno what this does:
        curl_setopt($ch[$master_counter], CURLOPT_RETURNTRANSFER, 1);

        #curl_setopt($ch, CURLOPT_VERBOSE, 1);
        # set path to server
        curl_setopt($ch[$master_counter], CURLOPT_URL, $siv_url);

        #set parameter values:
        curl_setopt($ch[$master_counter], CURLOPT_POSTFIELDS, $parameters);

        # set multi handle 
        curl_multi_add_handle($mh, $ch[$master_counter]);

        #update voiceid
        $master_counter++;
    }

    #update filname
    //$fn++;
    //}
    ##############################################################################
    # execute:

    $running = 1;
    while ($running > 0) {
        //logger3("running...", $running);
        curl_multi_exec($mh, $running);
    }


    ##############################################################################
    # get responses:
    logger3("### RAW (PER LOOKUP) RESULTS...", $a);

    # used to make final decsision:
    $duplicate_voiceprintids = NULL;
    $duplicate_voiceprintids = array();

    //$fn = 0;
    $master_counter = 0;
    //while (isset($filenames[$fn])) {
    $result = "DOES NOT MATCH";
    $i = 0;
    foreach($voiceprintids as $key => $voiceprintid) {

        //logger3("[vp]: [", $i . "]",$a);
        logger3("voiceprintids: ", $voiceprintids);

        $response[$key] = curl_multi_getcontent($ch[$master_counter]);
        logger3("response[$key]: ", $response[$key]);       

        $tmp_response = explode("name=\"result.score\" expr=\"'", $response[$key]);
        $tmp_response = explode("'\"/>", $tmp_response[1]);
        logger3("filename: ", $filename . " vs. voiceprintid[$key]: " . $voiceprintid . " = score: " . $tmp_response[0]);

		if($tmp_response[0] > $high_score) $high_score = $tmp_response[0];
		
		logger3("high_score",$high_score);
		
        if ($tmp_response[0] >= $tolerance) {
	        
            $result = "MATCHES";
        }
        else{
            //IF ALREADY FOUND A MATCHES, DONT REPLACE IT
            if($result!='MATCHES'){
                if(stristr($check_type,"Biometric Password Update")) {
                    $result = "INVALID";
                }
            }
        }

        # remove handle
        curl_multi_remove_handle($mh, $ch[$master_counter]);

        # update voicefileid
        $i++;
        $master_counter++;
    }
    # update filename
    //$fn++;
    //}
    ##############################################################################
    # all done / close session:
    curl_multi_close($mh);
    
    logger3("high_score",$high_score);
    
    if($return_format == "high_score") {
	    return $high_score;
    } else {
	    return $result;
    }
    
}




function vocaONE_api_sessions($action) {
	
	### LIST OF PAGES THIS IS ON:
	### 1. voice_authorizations.api
	### 2. vocaSIGN_api_version_WHITELABEL.gatei
	### 3. 
	
	
	### SET #############################################
	if(stristr($action,"SET")) {
		

		///////////////////////////////////////////////////
		/// START: LOG THE INCOMING SESSION:
		///////////////////////////////////////////////////
		
		$set_apiid  = "";
		$set_hash = $_SESSION['incoming_api_session']['hash'] = hash_me();
		
		if(empty($_SESSION['incoming_api_session']['service_name'])) {
			$set_service_name = $_SESSION['incoming_api_session']['service_name'] = $_SESSION['template']['company']['text_name'];
		} else {
			$set_service_name = $_SESSION['incoming_api_session']['service_name'];
		}
		
		if(empty($_SESSION['incoming_api_session']['freeswitch_uuid'])) {
			$set_freeswitch_uuid = $_SESSION['incoming_api_session']['freeswitch_uuid'] = "";
		} else {
			$set_freeswitch_uuid = $_SESSION['incoming_api_session']['freeswitch_uuid'];
		}
		
		if(empty($_SESSION['incoming_api_session']['API_VERSION'])) {
			$set_API_VERSION = $_SESSION['incoming_api_session']['API_VERSION'] = "";
		} else {
			$set_API_VERSION = $_SESSION['incoming_api_session']['API_VERSION'];
		}
		
		if(empty($_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'])) {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'] = $_SESSION['incoming_api_session']['ACCOUNT_NUMBER'];
		} else {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'];
		}
		
		if(empty($_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'])) {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'] = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'];
		} else {
			$set_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'];
		}
		
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'])) {
			$set_CUSTOMER_SESSION_ID = $_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'] = "";
		} else {
			$set_CUSTOMER_SESSION_ID = $_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'];
		}
		
        if(empty($_SESSION['incoming_api_session']['VOICE_BIOMETRIC_MATCHING_SESSION_ID'])) {
			$set_VOICE_BIOMETRIC_MATCHING_SESSION_ID = $_SESSION['incoming_api_session']['VOICE_BIOMETRIC_MATCHING_SESSION_ID'] = "";
		} else {
			$set_VOICE_BIOMETRIC_MATCHING_SESSION_ID = $_SESSION['incoming_api_session']['VOICE_BIOMETRIC_MATCHING_SESSION_ID'];
		}


        if(empty($_SESSION['incoming_api_session']['CUSTOMER_USERNAME'])) {
			$set_CUSTOMER_USERNAME = $_SESSION['incoming_api_session']['CUSTOMER_USERNAME'] = "";
		} else {
			$set_CUSTOMER_USERNAME = $_SESSION['incoming_api_session']['CUSTOMER_USERNAME'];
		}
		
		
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'])) {
			$set_CUSTOMER_BIOMETRIC_ID = $_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'] = "";
		} else {
			$set_CUSTOMER_BIOMETRIC_ID = $_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'])) {
			$set_CUSTOMER_FULL_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'] = "";
		} else {
			$set_CUSTOMER_FULL_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'])) {
			$set_CUSTOMER_FIRST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'] = "";
		} else {
			$set_CUSTOMER_FIRST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'])) {
			$set_CUSTOMER_LAST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'] = "";
		} else {
			$set_CUSTOMER_LAST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) {
			$set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'] = "";
		} else {
			$set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) {
			$set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'] = "";
		} else {
			$set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'])) {
			$set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'] = "";
		} else {
			$set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'])) {
			$set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'] = "";
		} else {
			$set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'];
		}
		
		if(empty($_SESSION['incoming_api_session']['CUSTOMER_IP'])) {
			$set_CUSTOMER_IP = $_SESSION['incoming_api_session']['CUSTOMER_IP'] = "";
		} else {
			$set_CUSTOMER_IP = $_SESSION['incoming_api_session']['CUSTOMER_IP'];
		}
		
		if(empty($_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'])) {
			$set_AUTHORIZATION_CATEGORY = $_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'] = "";
		} else {
			$set_AUTHORIZATION_CATEGORY = $_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'];
		}
		
		if(empty($_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'])) {
			$set_AUTHORIZATION_TEMPLATE = $_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'] = "";
		} else {
			$set_AUTHORIZATION_TEMPLATE = $_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'];
		}
		
		if(empty($_SESSION['incoming_api_session']['VOICE_SOURCE'])) {
			$set_VOICE_SOURCE = $_SESSION['incoming_api_session']['VOICE_SOURCE'] = "";
		} else {
			$set_VOICE_SOURCE = $_SESSION['incoming_api_session']['VOICE_SOURCE'];
		}
		
		if(empty($_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'])) {
			$set_VOICE_AUTHORIZATION_TEXT = $_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'] = "";
		} else {
			$set_VOICE_AUTHORIZATION_TEXT = $_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'];
		}
		

		
		
		if(empty($_SESSION['incoming_api_session']['grammar_filename'])) {
			$set_grammar_filename = $_SESSION['incoming_api_session']['grammar_filename'] = "";
		} else {
			$set_grammar_filename = $_SESSION['incoming_api_session']['grammar_filename'];
		}
		
		if(empty($_SESSION['incoming_api_session']['asr_results'])) {
			$set_asr_results = $_SESSION['incoming_api_session']['asr_results'] = "";
		} else {
			$set_asr_results = $_SESSION['incoming_api_session']['asr_results'];
		}
		
		if(empty($_SESSION['incoming_api_session']['authorization_attempt'])) {
			$set_authorization_attempt = $_SESSION['incoming_api_session']['authorization_attempt'] = "";
		} else {
			$set_authorization_attempt = $_SESSION['incoming_api_session']['authorization_attempt'];
		}
		
		if(empty($_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'])) {
			$set_AUTHORIZATION_STATUS = $_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'] = "";
		} else {
			$set_AUTHORIZATION_STATUS = $_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'];
		}
		
		if(empty($_SESSION['incoming_api_session']['voice_authorizations_hash'])) {
			$set_voice_authorizations_hash = $_SESSION['incoming_api_session']['voice_authorizations_hash'] = "";
		} else {
			$set_voice_authorizations_hash = $_SESSION['incoming_api_session']['voice_authorizations_hash'];
		}
		
		if(empty($_SESSION['incoming_api_session']['memberid'])) {
			$set_memberid = $_SESSION['incoming_api_session']['memberid'] = "";
		} else {
			$set_memberid = $_SESSION['incoming_api_session']['memberid'];
		}
		
		if(empty($_SESSION['incoming_api_session']['datetime_created'])) {
			$set_datetime_created = $_SESSION['incoming_api_session']['datetime_created'] = datetime();
		} else {
			$set_datetime_created = $_SESSION['incoming_api_session']['datetime_created'];
		}
		
		if(empty($_SESSION['incoming_api_session']['datetime_updated'])) {
			$set_datetime_updated = $_SESSION['incoming_api_session']['datetime_updated'] = $set_datetime_created;
		} else {
			$set_datetime_updated = $_SESSION['incoming_api_session']['datetime_updated'];
		}
		

		$set_GATEWAY_MERCHANT_NAME = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'];
		$set_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_EMAILADDRESS'];
		$set_GATEWAY_MERCHANT_MID = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MID'];
		$set_GATEWAY_MERCHANT_MCC = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'];
		
		
		

		#######
		####### START: voice_authorization_api  (gives data input priority OVER ['incoming_api_session'])
		#######
		
		if(isset($_SESSION['voice_authorization_api'])) {
			
			if(!empty($_SESSION['voice_authorization_api']['service_name'])) $set_service_name = $_SESSION['voice_authorization_api']['service_name'];
			
			if(!empty($_SESSION['voice_authorization_api']['freeswitch_uuid'])) $set_freeswitch_uuid = $_SESSION['voice_authorization_api']['freeswitch_uuid'];
			
			if(!empty($_SESSION['voice_authorization_api']['API_VERSION'])) $set_API_VERSION = $_SESSION['voice_authorization_api']['API_VERSION'];
			
			if(!empty($_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_HASH'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_HASH'];
			
			if(!empty($_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_ID'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'])) $set_CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_USERNAME'])) $set_CUSTOMER_USERNAME = $_SESSION['voice_authorization_api']['CUSTOMER_USERNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])) $set_CUSTOMER_BIOMETRIC_ID = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'])) $set_CUSTOMER_FULL_NAME = $_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $set_CUSTOMER_FIRST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $set_CUSTOMER_LAST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'])) $set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'])) $set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_IP'])) $set_CUSTOMER_IP = $_SESSION['voice_authorization_api']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'])) $set_AUTHORIZATION_CATEGORY = $_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'])) $set_AUTHORIZATION_TEMPLATE = $_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_SOURCE'])) $set_VOICE_SOURCE = $_SESSION['voice_authorization_api']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'])) $set_VOICE_AUTHORIZATION_TEXT = $_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MID'])) $set_GATEWAY_MID = $_SESSION['voice_authorization_api']['GATEWAY_MID'];
			
			if(!empty($_SESSION['voice_authorization_api']['grammar_filename'])) $set_grammar_filename = $_SESSION['voice_authorization_api']['grammar_filename'];
			
			if(!empty($_SESSION['voice_authorization_api']['asr_results'])) $set_asr_results = $_SESSION['voice_authorization_api']['asr_results'];
			
			if(!empty($_SESSION['voice_authorization_api']['authorization_attempt'])) $set_authorization_attempt = $_SESSION['voice_authorization_api']['authorization_attempt'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'])) $set_AUTHORIZATION_STATUS = $_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['voice_authorization_api']['voice_authorizations_hash'])) $set_voice_authorizations_hash = $_SESSION['voice_authorization_api']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['voice_authorization_api']['memberid'])) $set_memberid = $_SESSION['voice_authorization_api']['memberid'];
			

				
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'])) $set_GATEWAY_MERCHANT_NAME = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'])) $set_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'])) $set_GATEWAY_MERCHANT_MID = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'])) $set_GATEWAY_MERCHANT_MCC = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'];
			
		
		
		}

		#######
		####### END: voice_authorization_api
		#######
		


		#######
		####### START: vocaONE_api_sessions  (gives data input priority OVER ALL)
		#######
		
		
		
		if(isset($_SESSION['vocaONE_api_sessions'])) {
			
			if(!empty($_SESSION['vocaONE_api_sessions']['service_name'])) $set_service_name = $_SESSION['vocaONE_api_sessions']['service_name'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['freeswitch_uuid'])) $set_freeswitch_uuid = $_SESSION['vocaONE_api_sessions']['freeswitch_uuid'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['API_VERSION'])) $set_API_VERSION = $_SESSION['vocaONE_api_sessions']['API_VERSION'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['ACCOUNT_NUMBER'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['vocaONE_api_sessions']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['BUSINESS_ACCOUNT_HASH'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['vocaONE_api_sessions']['BUSINESS_ACCOUNT_HASH'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['BUSINESS_ACCOUNT_ID'])) $set_BUSINESS_ACCOUNT_HASH = $_SESSION['vocaONE_api_sessions']['BUSINESS_ACCOUNT_ID'];
			
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_SESSION_ID'])) $set_CUSTOMER_SESSION_ID = $_SESSION['vocaONE_api_sessions']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_USERNAME'])) $set_CUSTOMER_USERNAME = $_SESSION['vocaONE_api_sessions']['CUSTOMER_USERNAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_BIOMETRIC_ID'])) $set_CUSTOMER_BIOMETRIC_ID = $_SESSION['vocaONE_api_sessions']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_FULL_NAME'])) $set_CUSTOMER_FULL_NAME = $_SESSION['vocaONE_api_sessions']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $set_CUSTOMER_FIRST_NAME = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $set_CUSTOMER_LAST_NAME = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $set_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'])) $set_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'])) $set_CUSTOMER_EMAIL_ADDRESS = $_SESSION['vocaONE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_IP'])) $set_CUSTOMER_IP = $_SESSION['vocaONE_api_sessions']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CATEGORY'])) $set_AUTHORIZATION_CATEGORY = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_TEMPLATE'])) $set_AUTHORIZATION_TEMPLATE = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['VOICE_SOURCE'])) $set_VOICE_SOURCE = $_SESSION['vocaONE_api_sessions']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['VOICE_AUTHORIZATION_TEXT'])) $set_VOICE_AUTHORIZATION_TEXT = $_SESSION['vocaONE_api_sessions']['VOICE_AUTHORIZATION_TEXT'];
			
			### GATEWAY
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MID'])) $set_GATEWAY_MID = $_SESSION['vocaONE_api_sessions']['GATEWAY_MID'];
			
			### AUDIO
			if(!empty($_SESSION['vocaONE_api_sessions']['grammar_filename'])) $set_grammar_filename = $_SESSION['vocaONE_api_sessions']['grammar_filename'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['asr_results'])) $set_asr_results = $_SESSION['vocaONE_api_sessions']['asr_results'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['authorization_attempt'])) $set_authorization_attempt = $_SESSION['vocaONE_api_sessions']['authorization_attempt'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_STATUS'])) $set_AUTHORIZATION_STATUS = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['voice_authorizations_hash'])) $set_voice_authorizations_hash = $_SESSION['vocaONE_api_sessions']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['memberid'])) $set_memberid = $_SESSION['vocaONE_api_sessions']['memberid'];
			

			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_NAME'])) $set_GATEWAY_MERCHANT_NAME = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_NAME'];
				
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'])) $set_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MID'])) $set_GATEWAY_MERCHANT_MID = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MCC'])) $set_GATEWAY_MERCHANT_MCC = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MCC'];
				
			

		}
		
		#######
		####### END: vocaONE_api_sessions
		#######




		$tmp_sql = "INSERT INTO `vocaONE_api_sessions`
		(
			`apiid`,
			`hash`,
			`service_name`,
			`freeswitch_uuid`,
			`API_VERSION`,
			`BUSINESS_ACCOUNT_HASH`,
			`CUSTOMER_SESSION_ID`,
            `VOICE_BIOMETRIC_MATCHING_SESSION_ID`,
			`CUSTOMER_BIOMETRIC_ID`,
			`CUSTOMER_USERNAME`,
			`CUSTOMER_FULL_NAME`,
			`CUSTOMER_FIRST_NAME`,
			`CUSTOMER_LAST_NAME`,
			`CUSTOMER_TELEPHONE_COUNTRY_ISO3`,
			`CUSTOMER_TELEPHONE_COUNTRY_CODE`,
			`CUSTOMER_TELEPHONE_NUMBER`,
			`CUSTOMER_EMAIL_ADDRESS`,
			`CUSTOMER_IP`,
			`AUTHORIZATION_CATEGORY`,
			`AUTHORIZATION_TEMPLATE`,
			`VOICE_SOURCE`,
			`VOICE_AUTHORIZATION_TEXT`,
			`GATEWAY_MERCHANT_NAME`,
			`GATEWAY_MERCHANT_EMAILADDRESS`,
			`GATEWAY_MERCHANT_MID`,
			`GATEWAY_MERCHANT_MCC`,
			`grammar_filename`,
			`asr_results`,
			`authorization_attempt`,
			`AUTHORIZATION_STATUS`,
			`voice_authorizations_hash`,
			`memberid`,
			`datetime_created`,
			`datetime_updated`
		) VALUES (
			'". $set_apiid ."',
			'". $set_hash ."',
			'". $set_service_name .".()',
			'". $set_freeswitch_uuid ."',
			'". $set_API_VERSION ."',
			'". $set_BUSINESS_ACCOUNT_HASH ."',
			'". $set_CUSTOMER_SESSION_ID ."',
            '". $set_VOICE_BIOMETRIC_MATCHING_SESSION_ID ."',
			'". $set_CUSTOMER_BIOMETRIC_ID ."',
			'". $set_CUSTOMER_USERNAME ."',
			'". $set_CUSTOMER_FULL_NAME ."',
			'". $set_CUSTOMER_FIRST_NAME ."',
			'". $set_CUSTOMER_LAST_NAME ."',
			'". $set_CUSTOMER_TELEPHONE_COUNTRY_ISO3 ."',
			'". $set_CUSTOMER_TELEPHONE_COUNTRY_CODE ."',
			'". $set_CUSTOMER_TELEPHONE_NUMBER ."',
			'". $set_CUSTOMER_EMAIL_ADDRESS ."',
			'". $set_CUSTOMER_IP ."',
			'". $set_AUTHORIZATION_CATEGORY ."',
			'". $set_AUTHORIZATION_TEMPLATE ."',
			'". $set_VOICE_SOURCE ."',
			'". addslashes($set_VOICE_AUTHORIZATION_TEXT) ."',
			'". $set_GATEWAY_MERCHANT_NAME ."',
			'". $set_GATEWAY_MERCHANT_EMAILADDRESS ."',
			'". $set_GATEWAY_MERCHANT_MID ."',
			'". $set_GATEWAY_MERCHANT_MCC ."',
			'". $set_grammar_filename ."',
			'". $set_asr_results ."',
			'". $set_authorization_attempt ."',
			'". $set_AUTHORIZATION_STATUS ."',
			'". $set_voice_authorizations_hash ."',
			'". $set_memberid ."',
			'". $set_datetime_created ."',
			'". $set_datetime_updated ."'
		);
		";
		
		logger3("tmp_sql",$tmp_sql);
		$_SESSION['incoming_api_session']['apiid'] = $insert_results = insertTHECASHIER($tmp_sql);
		logger3("vocaONE_api_sessions_set_apiid",$_SESSION['incoming_api_session']['apiid']);
		return $_SESSION['incoming_api_session']['apiid'];
		
		///////////////////////////////////////////////////
		/// END: LOG THE INCOMING SESSION:
		///////////////////////////////////////////////////
	}
	
	
	
	### UPDATE #############################################
	if(stristr($action,"UPDATE")) {
		
		
		$update_apiid = $_SESSION['incoming_api_session']['apiid'];
		$update_hash = $_SESSION['incoming_api_session']['hash'];
		$update_service_name = $_SESSION['incoming_api_session']['service_name'];
		$update_freeswitch_uuid = $_SESSION['incoming_api_session']['freeswitch_uuid'];
		$update_API_VERSION = $_SESSION['incoming_api_session']['API_VERSION'];
		$update_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_HASH'];
		if(!empty($_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'])) $update_BUSINESS_ACCOUNT_HASH = $_SESSION['incoming_api_session']['BUSINESS_ACCOUNT_ID'];
		$update_CUSTOMER_SESSION_ID = $_SESSION['incoming_api_session']['CUSTOMER_SESSION_ID'];
		$update_CUSTOMER_BIOMETRIC_ID = $_SESSION['incoming_api_session']['CUSTOMER_BIOMETRIC_ID'];
		$update_CUSTOMER_USERNAME = $_SESSION['incoming_api_session']['CUSTOMER_USERNAME'];
		$update_CUSTOMER_FULL_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FULL_NAME'];
		$update_CUSTOMER_FIRST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_FIRST_NAME'];
		$update_CUSTOMER_LAST_NAME = $_SESSION['incoming_api_session']['CUSTOMER_LAST_NAME'];
		$update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
		$update_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
		$update_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['incoming_api_session']['CUSTOMER_TELEPHONE_NUMBER'];
		$update_CUSTOMER_EMAIL_ADDRESS = $_SESSION['incoming_api_session']['CUSTOMER_EMAIL_ADDRESS'];
		$update_CUSTOMER_IP = $_SESSION['incoming_api_session']['CUSTOMER_IP'];
		$update_AUTHORIZATION_CATEGORY = $_SESSION['incoming_api_session']['AUTHORIZATION_CATEGORY'];
		$update_AUTHORIZATION_TEMPLATE = $_SESSION['incoming_api_session']['AUTHORIZATION_TEMPLATE'];
		$update_VOICE_SOURCE = $_SESSION['incoming_api_session']['VOICE_SOURCE'];
		$update_VOICE_AUTHORIZATION_TEXT = $_SESSION['incoming_api_session']['VOICE_AUTHORIZATION_TEXT'];
		$update_grammar_filename = $_SESSION['incoming_api_session']['grammar_filename'];
		$update_asr_results = $_SESSION['incoming_api_session']['asr_results'];
		$update_authorization_attempt = $_SESSION['incoming_api_session']['authorization_attempt'];
		$update_AUTHORIZATION_STATUS = $_SESSION['incoming_api_session']['AUTHORIZATION_STATUS'];
		$update_voice_authorizations_hash = $_SESSION['incoming_api_session']['voice_authorizations_hash'];
		$update_memberid = $_SESSION['incoming_api_session']['memberid'];
		$update_datetime_created = $_SESSION['incoming_api_session']['datetime_created'];
		$update_datetime_updated = $_SESSION['incoming_api_session']['datetime_updated'] = datetime();
		
		### GATEWAY:
		$update_GATEWAY_MERCHANT_NAME = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_NAME'];
		$update_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_EMAILADDRESS'];
		$update_GATEWAY_MERCHANT_MID = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MID'];
		$update_GATEWAY_MERCHANT_MCC = $_SESSION['incoming_api_session']['GATEWAY_MERCHANT_MCC'];
		
		#######
		####### START: voice_authorization_api  (gives data input priority OVER ['incoming_api_session'])
		#######
		
		if(isset($_SESSION['voice_authorization_api'])) {
			
			if(!empty($_SESSION['voice_authorization_api']['apiid'])) $update_apiid = $_SESSION['voice_authorization_api']['apiid'];
			
			if(!empty($_SESSION['voice_authorization_api']['service_name'])) $update_service_name = $_SESSION['voice_authorization_api']['service_name'];
			
			if(!empty($_SESSION['voice_authorization_api']['freeswitch_uuid'])) $update_freeswitch_uuid = $_SESSION['voice_authorization_api']['freeswitch_uuid'];
			
			if(!empty($_SESSION['voice_authorization_api']['API_VERSION'])) $update_API_VERSION = $_SESSION['voice_authorization_api']['API_VERSION'];
			
			if(!empty($_SESSION['voice_authorization_api']['BUSINESS_ACCOUNT_HASH'])) $update_BUSINESS_ACCOUNT_HASH = $_SESSION['voice_authorization_api']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'])) $update_CUSTOMER_SESSION_ID = $_SESSION['voice_authorization_api']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'])) $update_CUSTOMER_BIOMETRIC_ID = $_SESSION['voice_authorization_api']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'])) $update_CUSTOMER_FULL_NAME = $_SESSION['voice_authorization_api']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $update_CUSTOMER_FIRST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $update_CUSTOMER_LAST_NAME = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $update_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['voice_authorization_api']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'])) $update_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'])) $update_CUSTOMER_EMAIL_ADDRESS = $_SESSION['voice_authorization_api']['AUTHORIZATION_CUSTOMER_EMAILADDRESS'];
			
			if(!empty($_SESSION['voice_authorization_api']['CUSTOMER_IP'])) $update_CUSTOMER_IP = $_SESSION['voice_authorization_api']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'])) $update_AUTHORIZATION_CATEGORY = $_SESSION['voice_authorization_api']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'])) $update_AUTHORIZATION_TEMPLATE = $_SESSION['voice_authorization_api']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_SOURCE'])) $update_VOICE_SOURCE = $_SESSION['voice_authorization_api']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'])) $update_VOICE_AUTHORIZATION_TEXT = $_SESSION['voice_authorization_api']['VOICE_AUTHORIZATION_TEXT'];
			
			if(!empty($_SESSION['voice_authorization_api']['grammar_filename'])) $update_grammar_filename = $_SESSION['voice_authorization_api']['grammar_filename'];
			
			if(!empty($_SESSION['voice_authorization_api']['asr_results'])) $update_asr_results = $_SESSION['voice_authorization_api']['asr_results'];
			
			if(!empty($_SESSION['voice_authorization_api']['authorization_attempt'])) $update_authorization_attempt = $_SESSION['voice_authorization_api']['authorization_attempt'];
			
			if(!empty($_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'])) $update_AUTHORIZATION_STATUS = $_SESSION['voice_authorization_api']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['voice_authorization_api']['voice_authorizations_hash'])) $update_voice_authorizations_hash = $_SESSION['voice_authorization_api']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['voice_authorization_api']['memberid'])) $update_memberid = $_SESSION['voice_authorization_api']['memberid'];
			
			# GATEWAY:
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'])) $update_GATEWAY_MERCHANT_NAME = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_NAME'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'])) $update_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_EMAILADDRESS'];

			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'])) $update_GATEWAY_MERCHANT_MID = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'])) $update_GATEWAY_MERCHANT_MCC = $_SESSION['voice_authorization_api']['GATEWAY_MERCHANT_MCC'];
			
		}
		
		#######
		####### END: voice_authorization_api
		#######


		#######
		####### START: vocaONE_api_sessions  (gives data input priority OVER ALL)
		#######
		
		//test("functions_shared_SESSION_vocaONE_api_sessions",$_SESSION['vocaONE_api_sessions']);
		
		if(isset($_SESSION['vocaONE_api_sessions'])) {
			
			if(!empty($_SESSION['vocaONE_api_sessions']['apiid'])) $update_apiid = $_SESSION['vocaONE_api_sessions']['apiid'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['service_name'])) $update_service_name = $_SESSION['vocaONE_api_sessions']['service_name'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['freeswitch_uuid'])) $update_freeswitch_uuid = $_SESSION['vocaONE_api_sessions']['freeswitch_uuid'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['API_VERSION'])) $update_API_VERSION = $_SESSION['vocaONE_api_sessions']['API_VERSION'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['BUSINESS_ACCOUNT_HASH'])) $update_BUSINESS_ACCOUNT_HASH = $_SESSION['vocaONE_api_sessions']['ACCOUNT_NUMBER'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_SESSION_ID'])) $update_CUSTOMER_SESSION_ID = $_SESSION['vocaONE_api_sessions']['CUSTOMER_SESSION_ID'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_BIOMETRIC_ID'])) $update_CUSTOMER_BIOMETRIC_ID = $_SESSION['vocaONE_api_sessions']['CUSTOMER_BIOMETRIC_ID'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_FULL_NAME'])) $update_CUSTOMER_FULL_NAME = $_SESSION['vocaONE_api_sessions']['CUSTOMER_FULL_NAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'])) $update_CUSTOMER_FIRST_NAME = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_FIRSTNAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'])) $update_CUSTOMER_LAST_NAME = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CUSTOMER_LASTNAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'])) $update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 = $_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_ISO3'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'])) $update_CUSTOMER_TELEPHONE_COUNTRY_CODE = $_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_COUNTRY_CODE'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'])) $update_CUSTOMER_TELEPHONE_NUMBER = $_SESSION['vocaONE_api_sessions']['CUSTOMER_TELEPHONE_NUMBER'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'])) $update_CUSTOMER_EMAIL_ADDRESS = $_SESSION['vocaONE_api_sessions']['CUSTOMER_EMAIL_ADDRESS'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['CUSTOMER_IP'])) $update_CUSTOMER_IP = $_SESSION['vocaONE_api_sessions']['CUSTOMER_IP'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CATEGORY'])) $update_AUTHORIZATION_CATEGORY = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_CATEGORY'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_TEMPLATE'])) $update_AUTHORIZATION_TEMPLATE = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_TEMPLATE'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['VOICE_SOURCE'])) $update_VOICE_SOURCE = $_SESSION['vocaONE_api_sessions']['VOICE_SOURCE'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['VOICE_AUTHORIZATION_TEXT'])) $update_VOICE_AUTHORIZATION_TEXT = $_SESSION['vocaONE_api_sessions']['VOICE_AUTHORIZATION_TEXT'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['grammar_filename'])) $update_grammar_filename = $_SESSION['vocaONE_api_sessions']['grammar_filename'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['asr_results'])) $update_asr_results = $_SESSION['vocaONE_api_sessions']['asr_results'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['authorization_attempt'])) $update_authorization_attempt = $_SESSION['vocaONE_api_sessions']['authorization_attempt'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['AUTHORIZATION_STATUS'])) $update_AUTHORIZATION_STATUS = $_SESSION['vocaONE_api_sessions']['AUTHORIZATION_STATUS'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['voice_authorizations_hash'])) $update_voice_authorizations_hash = $_SESSION['vocaONE_api_sessions']['voice_authorizations_hash'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['memberid'])) $update_memberid = $_SESSION['vocaONE_api_sessions']['memberid'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_NAME'])) $update_GATEWAY_MERCHANT_NAME = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_NAME'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'])) $update_GATEWAY_MERCHANT_EMAILADDRESS = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_EMAILADDRESS'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MID'])) $update_GATEWAY_MERCHANT_MID = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MID'];
			
			if(!empty($_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MCC'])) $update_GATEWAY_MERCHANT_MCC = $_SESSION['vocaONE_api_sessions']['GATEWAY_MERCHANT_MCC'];
			
			
		}
		
		#######
		####### END: vocaONE_api_sessions
		#######
		
		
		if(empty($update_service_name)) $update_service_name = $_SESSION['template']['company']['text_name'];
		if(empty($update_CUSTOMER_IP)) $update_CUSTOMER_IP = $_SERVER['REMOTE_ADDR'];
		
		
		$tmp_sql = "UPDATE `vocaONE_api_sessions` SET
		`service_name` = '". $update_service_name .".()',
		`freeswitch_uuid` = '". $update_freeswitch_uuid ."',
		`API_VERSION` = '". $update_API_VERSION ."',
		`BUSINESS_ACCOUNT_HASH` = '". $update_BUSINESS_ACCOUNT_HASH ."',
		`CUSTOMER_SESSION_ID` = '". $update_CUSTOMER_SESSION_ID ."',
		`CUSTOMER_BIOMETRIC_ID` = '". $update_CUSTOMER_BIOMETRIC_ID ."',
		`CUSTOMER_FULL_NAME` = '". $update_CUSTOMER_FULL_NAME ."',
		`CUSTOMER_FIRST_NAME` = '". $update_CUSTOMER_FIRST_NAME ."',
		`CUSTOMER_LAST_NAME` = '". $update_CUSTOMER_LAST_NAME ."',
		`CUSTOMER_TELEPHONE_COUNTRY_ISO3` = '". $update_CUSTOMER_TELEPHONE_COUNTRY_ISO3 ."',
		`CUSTOMER_TELEPHONE_COUNTRY_CODE` = '". $update_CUSTOMER_TELEPHONE_COUNTRY_CODE ."',
		`CUSTOMER_TELEPHONE_NUMBER` = '". $update_CUSTOMER_TELEPHONE_NUMBER ."',
		`CUSTOMER_EMAIL_ADDRESS` = '". $update_CUSTOMER_EMAIL_ADDRESS ."',
		`CUSTOMER_IP` = '". $update_CUSTOMER_IP ."',
		`AUTHORIZATION_CATEGORY` = '". $update_AUTHORIZATION_CATEGORY ."',
		`AUTHORIZATION_TEMPLATE` = '". $update_AUTHORIZATION_TEMPLATE ."',
		`VOICE_SOURCE` = '". $update_VOICE_SOURCE ."',
		`VOICE_AUTHORIZATION_TEXT` = '". addslashes($update_VOICE_AUTHORIZATION_TEXT) ."',
		
		`GATEWAY_MERCHANT_NAME` = '". $update_GATEWAY_MERCHANT_NAME ."',
		`GATEWAY_MERCHANT_EMAILADDRESS` = '". $update_GATEWAY_MERCHANT_MAILADDRESS ."',
		`GATEWAY_MERCHANT_MID` = '". $update_GATEWAY_MERCHANT_MID ."',
		`GATEWAY_MERCHANT_MCC` = '". $update_GATEWAY_MERCHANT_MCC ."',
		
		`grammar_filename` = '". $update_grammar_filename ."',
		`asr_results` = '". $update_asr_results ."',
		`authorization_attempt` = '". $update_authorization_attempt ."',
		`AUTHORIZATION_STATUS` = '". $update_AUTHORIZATION_STATUS ."',
		`voice_authorizations_hash` = '". $update_voice_authorizations_hash ."',
		`memberid` = '". $update_memberid ."',
		`datetime_updated` = '". $update_datetime_updated ."'
		 WHERE
		 apiid = '". $update_apiid ."'
		 ;";
		///test("tmp_sql",$tmp_sql);
		$update_results = updateTHECASHIER($tmp_sql);
		//test("vocaONE_api_sessions_update_results",$update_results);
		
	}

}

function is_mobile_device(){
    global $master_config_root_path;
    require_once($master_config_root_path . "shared/Mobile_Detect.php");        
    $detect = new Mobile_Detect;

    //if(strstr($_SERVER['HTTP_USER_AGENT'],'iPhone'))
    //return true;
    return $detect->isMobile();
}


function get_audio_from_url($remote_url, $target_path=''){
    global $master_config_root_path;
    $target_path = $master_config_root_path."authorizations/audio/";
    if(empty($target_path)) $target_path = $default_path;
    $filename_without_ext = hash_me();
    
    $content = get_headers($remote_url,1);
    $content = array_change_key_case($content, CASE_LOWER);
    if ($content['content-disposition']) {
        $tmp_name = explode('=', $content['content-disposition']);
        if ($tmp_name[1]) 
            $realfilename = trim($tmp_name[1],'";\'');
    } else  
    {
        $stripped_url = preg_replace('/\\?.*/', '', $remote_url);
        $realfilename = basename($stripped_url);
    } 
    $tmp_name = explode('.', $realfilename);
    $ext1 = $tmp_name[count($tmp_name)-1];
    $local_file_path = $target_path.$filename_without_ext.'.'.$ext1;
    
    $remote_file_contents = file_get_contents($remote_url );    
    logger3('local_file_path', $local_file_path);
    $audio_copied = file_put_contents($local_file_path, $remote_file_contents);
    if(file_exists($local_file_path)) return $filename_without_ext.'.'.$ext1;
    else return false;
}



function get_ATT_asr_confidence($filename, $returnFullResponse = false){
	$result = 0;
	if($returnFullResponse) $result = array();
	
	if(!is_file($filename)){
		logger3('File Not found', $filename);
		return $confidence_level;		
	} 
	
 	//ATT OAuth TokenID START
	$crl = curl_init();
	
	$headr = array();
	$headr[] = 'Accept: application/json';
	$headr[] = 'Content-Type: application/x-www-form-urlencoded';
	
	curl_setopt($crl, CURLOPT_URL, "https://api.att.com/oauth/token" );
	curl_setopt($crl, CURLOPT_POST, 1);
	curl_setopt($crl, CURLOPT_POSTFIELDS, "client_id=neievhiljxpujabllr3fcznrypitk1tq&client_secret=yguidj8omy6clrwyiniu2tllkxonpbha&grant_type=client_credentials&scope=SPEECH,STTC" ); // change APPID and APPSECRET to the values from your developer console
	curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
	curl_setopt ($crl, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($crl, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
	
	$result=curl_exec ($crl);	
	$decoded_json = json_decode($result, true);	
	$token_id = $decoded_json["access_token"];
	
	logger3('token_id', $token_id);
		
	curl_close($crl);
	//ATT OAuth TokenID END		
	
	//ATT START
	$crl2 = curl_init();
	
	$headr = array();
	$headr[] = 'Authorization: Bearer ' . $token_id;
	$headr[] = 'Accept: application/json';
	$headr[] = 'Content-Type: audio/wav';
	$headr[] = 'X-SpeechContext: SMS';
	
	curl_setopt($crl2, CURLOPT_URL, "https://api.att.com/speech/v3/speechToText" );
	curl_setopt($crl2, CURLOPT_POST, 1);
	$file = fopen($filename, 'r'); //change FILENAME to the name of your file
	$size = filesize($filename); //change FILENAME to the name of your file
	$fildata = fread($file,$size);
	curl_setopt($crl2, CURLOPT_POSTFIELDS, $fildata);
	curl_setopt($crl2, CURLOPT_HTTPHEADER,$headr);
	curl_setopt ($crl2, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($crl2, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($crl2, CURLOPT_RETURNTRANSFER, true);
	
	$result2=curl_exec ($crl2);	
	$decoded_json2 = json_decode($result2, true);
	logger3('filesize', $size);	
	logger3('result', $decoded_json2);	
	
	if(isset($decoded_json2["Recognition"]["NBest"][0])){	
		$result_text = $decoded_json2["Recognition"]["NBest"][0]["ResultText"];
		logger3('result_text', $result_text);
			
		$confidence_level = $decoded_json2["Recognition"]["NBest"][0]["Confidence"];
		logger3('confidence_level', $confidence_level);
		$result = $confidence_level;
		
		//return full response
		if($returnFullResponse){
			logger3("returnFullResponse", $returnFullResponse);
			$result = $decoded_json2["Recognition"]["NBest"][0];			
		}
	}
	curl_close($crl2);
	//ATT END
			
	return $result . "||" . $result_text;
}

function create_dns_a_record($business_name){
	$business_name = trim($business_name);
	if(empty($business_name)){
		logger3('business_name', "DNS (A) record can't be empty.");
		return false;
	} 
	
	$output = shell_exec("/BANGK\!/www/test/video-conference/create_dns_a_record.sh '$business_name'");
	//test("output",$output);
	$output = substr($output, strpos($output, '; BIND data file for local loopback interface'));
	//logger3("output",$output);			
	
	$domain = 'video-conference.link';
	$sub_domain = $business_name . '.'.$domain.'';
	$a_record = $sub_domain . '.';
	$pos = stripos($output, $a_record);
	if ($pos !== false) {
		logger3($sub_domain, "DNS (A) record has successfully been created.");	
		
		return true;		
	}
	else {
		logger3($sub_domain, "Failed to create DNS record");		
	}
	return true;

}

function replace_dns_a_record($business_name_old, $business_name_new){
	$business_name_old = trim($business_name_old);
	$business_name_new = trim($business_name_new);
	if(empty($business_name_old)){
		logger3('business_name_old', "DNS (A) record can't be empty.");
		return false;
	} 
	if(empty($business_name_new)){
		logger3('business_name_new', "DNS (A) record can't be empty.");
		return false;
	} 
	
	$output = shell_exec("/BANGK\!/www/test/video-conference/replace_dns_a_record.sh '$business_name_old'  '$business_name_new'");
	//test("output",$output);	
	$output = substr($output, strpos($output, '; BIND data file for local loopback interface'));
	//logger3("output",$output);
	
	$domain = 'video-conference.link';
	$sub_domain = $business_name_new . '.'.$domain.'';
	$a_record = $sub_domain . '.';
	$pos = stripos($output, $a_record);
	if ($pos !== false) {
		logger3($sub_domain, "DNS (A) record has successfully been created.");	
		
		return true;		
	}
	else {
		logger3($sub_domain, "Failed to create DNS record");		
	}
	return true;

}

?>