<?


###	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 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_bangk($font_size="18px",$reg_size="12px") {
	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 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 = '" . $_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 = '" . $_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 = '" . $_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);
 			$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 = "/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 $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);
 			$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 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 = '" . $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);
	
	//test("result",$result);
	
	$result_array = array();
	$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($conent) {
	
	$conent = str_replace("<br>","",$conent);
	$conent = nl2br($conent);
	$conent = stripslashes($conent);
	$conent = faq_personalizer($conent);
	return $conent;
}


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";
	
	mail($to, $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);
	
	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);
	
	//test("to",$to);
	//test("subject",$subject);
	//test("message",$message);
	
	mail($to, $subject, $message, $headers);
}


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

	$headers = "";
	$headers .= "From: " . $from_name  . " <" . $reply_to . ">\r\n";
	$headers .= "Reply-To: " . $from_name . " <" . $reply_to . ">\r\n";
	
	$headers.="Return-Path:" . $reply_to . "\r\n";

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


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 = '" . $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 = '" . $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;
	
	if(!$dynamic_DTR) {
		$active_DTR = $master_config_DTR;
	} else {
		$active_DTR = $dynamic_DTR;
	}

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

	$tmp_sql = "SELECT * FROM transactions WHERE transactionid = '" . $transactionid . "';";
	$tmp_transaction_details = readTHECASHIER($tmp_sql);
	
	//logger3("tmp_sql",$tmp_sql);
	//test("transaction_details->requested_datetime",$tmp_transaction_details->requested_datetime);
	
	if($tmp_transaction_details->rebill_datetime) {
		$requested_datetime = $tmp_transaction_details->rebill_datetime;
	} else {
		$requested_datetime = $tmp_transaction_details->requested_datetime;
	}
	
	
	$DTR_value = ceil( ($active_DTR - 1) - (strtotime(date("Y-m-d")) - 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";
	}
	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);
	}

	$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;'>				
														<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($_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>
															</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>
							<span style='color:#AA0000; font-weight:bold;'>+</span> <u>REQUEST A REFUND</u>:
						</td><td style='text-align:left; padding-left:8px;'>
							<span class='css_satisfaction_guaranteed'>
								<a href='https://transaction-support.".$_SESSION['template']['company']['domain']."/?action=REFUND_REQUEST".$add_properties."'>Click here to REQUEST A REFUND</a>
							</span>
						</td>
					</tr>
					
					<tr>
						<td>
							<span style='color:#AA0000; font-weight:bold;'>+</span> REPORT FRAUD:
						</td>
						<td style='text-align:left; padding-left:8px;'>
							<span class='css_satisfaction_guaranteed'>
								<a href='https://transaction-support.".$_SESSION['template']['company']['domain']."/?action=REPORT_FRAUD".$add_properties."'>Click here to <span  style='font-size:13px;'>REPORT FRAUD</span></a>
							</span>
						</td>
					</tr>
					
					<tr>
						<td>
							<span style='color:#AA0000; font-weight:bold;'>+</span> CUSTOMER SERVICE & SUPPORT:
						</td>
						<td style='text-align:left; padding-left:8px;'>
							<span class='css_satisfaction_guaranteed'>
								<a href='https://" . $_SESSION['template']['company']['host_support'] . "' target='" . $_SESSION['template']['company']['name'] . "'>Click here for CUSTOMER SERVICE & SUPPORT</a>
							</span>
						</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
	
	unset($tmp_member);
	logger3("0. tmp_memberid",$tmp_memberid);
	
	// alternative: emailaddress
	if(
	(stristr($tmp_memberid,"@")) &&
	(stristr($tmp_memberid,"."))
	) {
		$tmp_sql = "SELECT * FROM members WHERE emailaddress = '" . $tmp_memberid . "';";
		$tmp_member = object2array(readTHECASHIER($tmp_sql));
		logger3("1. tmp_sql",$tmp_sql);
		logger3("1. tmp_member",$tmp_member);	
	}
	
	// memberid
	if(
	(!isset($tmp_member['memberid']))
	) {
		$tmp_sql = "SELECT * FROM members WHERE memberid = '" . $tmp_memberid . "';";
		$tmp_member = object2array(readTHECASHIER($tmp_sql));
		logger3("2. tmp_sql",$tmp_sql);
		logger3("2. tmp_member",$tmp_member);	
	}
	
	
	// alternative: hash
	if(
	(!isset($tmp_member['memberid']))
	) {
		$tmp_sql = "SELECT * FROM members WHERE hash = '" . $tmp_memberid . "';";
		$tmp_member = object2array(readTHECASHIER($tmp_sql));
		logger3("3. tmp_sql",$tmp_sql);
		logger3("3. tmp_member",$tmp_member);	
	}
	
	

	// alternative: authorization number (counts through all possible country+number confinations)
	if(
	(!isset($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']) {
			$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(
	(isset($tmp_memberid)) &&
	(!isset($tmp_member['memberid']))
	) {
		$tmp_possible_phone_number = clean_authorization_number($tmp_memberid);
		logger3("11. 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(isset($tmp_phone_number['memberid'])) {
			$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(isset($tmp_member['memberid'])) {
		$tmp_sql = "SELECT accountid FROM permissions WHERE memberid = '" . $tmp_member['memberid'] . "' AND accounttype = 'Personal' AND permissions != '';";
		$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(isset($tmp_member['memberid'])) {
		$tmp_sql = "SELECT accountid FROM permissions WHERE memberid = '" . $tmp_member['memberid'] . "' AND accounttype = 'Business' AND permissions = 'MASTER' AND (admin = '' OR admin IS NULL)";
		$tmp_results = arrayTHECASHIER($tmp_sql);
		if($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(isset($tmp_member['memberid'])) {
		$tmp_results = arrayTHECASHIER("SELECT accountid FROM permissions WHERE memberid = '" . $tmp_member['memberid'] . "' AND accounttype = 'Shared' AND status != 'SELF' AND status != 'DELETED';");	
		if($tmp_results[0]) $tmp_member['accounts']['shared'] = $tmp_results;
		unset($tmp_results);
	}
	
	### :NEW: GET ADMIN ACCOUNT(S):
	if(isset($tmp_member['memberid'])) {
		$tmp_results = arrayTHECASHIER("SELECT accountid FROM permissions WHERE memberid = '" . $tmp_member['memberid'] . "' AND admin != 'NULL' AND admin != '';");	
		if($tmp_results[0]) $tmp_member['accounts']['admin'] = $tmp_results;
		unset($tmp_results);
	}
	
	### SET MULTIPLE ACCOUNTS
	if( 
	($tmp_member['accounts']['admin']) || 
	($tmp_member['accounts']['shared']) || 
	($tmp_member['accounts']['business']) 
	) {
		$tmp_member['accounts']['multiple'] = "YES";	
	}
	
	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;
	
	
	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);
		logger3("tmp_account",$tmp_account);
		
		### FIRST LOOKUP FAILED -- TRY SYSTEM_EMAIL_ACCOUNT
		if(!$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 = '" . $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 = '" . $tmp_accountid . "';";
		$tmp_account = object2array(readTHECASHIER($tmp_sql));
		logger3("tmp_sql",$tmp_sql);
		logger3("tmp_account",$tmp_account);	
	}


	if($_SESSION['member']['memberid']) {
	
		$tmp_sql = "SELECT admin FROM permissions WHERE memberid = '" . $_SESSION['member']['memberid'] . "' AND accountid = '" . $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 = '".$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);
	
	
	### return info
	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 = '" . $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 = '" . $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($client) {

	//echo $_SERVER['HTTP_HOST'];
	//test("client",$client);

	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);
	
	$tmp_sql = "SELECT templateid FROM templates_companies WHERE client = '" . $tmp_host . "';";
	//logger3("tmp_sql",$tmp_sql);
	$tmp_templateid = getTHECASHIER($tmp_sql);
	
	
	if(
	($tmp_templateid != NULL) &&
	($client != "blingk.nsdb-demo.com") &&
	($client != "blingk.nsdb-development.com")
	){
		$client = $tmp_host;
	} else {
		$client = strtolower($master_config_database_company_template);
	}
	
	//test("client",$client);
	

	### DEFINE VARS:
	$_SESSION['template'] = $template = NULL;
	$_SESSION['template'] = $template = array();
	
	
	### FIRST GET COMPAANY TEMPLATE:
	$_SESSION['template']['company'] = object2array(readTHECASHIER("SELECT * FROM templates_companies WHERE client = '" . $client . "';"));
	
	//test("_SESSION['template']['company']",$_SESSION['template']['company']);
	
	### NOW GET HTML TEMPLATES:
	$templateid = "";
	$templateid = array();
	$templateid = arrayTHECASHIER("SELECT templateid FROM templates_pages WHERE client = 'BANGK!'");
	
	$i = 0;
	while($templateid[$i]) {
		$template_html = "";
		$template_html = array();
		$template_html = object2array(readTHECASHIER("SELECT * FROM templates_pages where templateid = '" . $templateid[$i] . "'"));
		$template_name = $template_html['template'];
		$_SESSION['template'][$template_name] = $template_html;
		$i = $i + 1;
	}
	
	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") {
		return "/link_images/" . $image_file_name;
	} else {
		return "https://" . $_SESSION['template']['company']['host_images'] . "/" . $image_file_name;
	}
}


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


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 == "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);
	}	
	
	
}


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) {
	
	$tmp_balance = array();
	
	$tmp_account_details = account($accountid);
	

	$tmp_balance = object2array(readTHECASHIER("SELECT * FROM balances 
												WHERE 
												accountid = '" . $tmp_account_details['accountid'] . "' 
												AND platform = '".$_SESSION['template']['company']['domain']."'
												AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."';"));
										
	### 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 = $_SESSION['template']['company']['domain'];
		$tmp_currency_iso3 = $_SESSION['template']['company']['currency1'];
		$tmp_accountid = $tmp_account_details['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_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 . "',
			'" . $tmp_platform . "',
			'" . $tmp_currency_iso3 . "',
			'" . $tmp_accountid . "',
			'" . $tmp_account_balance . "',
			'" . $tmp_sponsor_balance . "',
			'" . $tmp_approved . "',
			'" . $tmp_available . "',
			'" . $tmp_blingk_credit . "',
			'" . $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 = '" . $tmp_account_details['accountid'] . "' 
													AND platform = '".$_SESSION['template']['company']['domain']."'
													AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."';"));
												
												
	}
	
	$datetime_rolling_schedule = datetime(strtotime("-30 days"));

	
	$tmp_sql = "SELECT SUM(transaction_net_value) FROM transactions 
				WHERE 
				accountid = '" . $tmp_account_details['accountid'] . "' 
				AND platform = '".$_SESSION['template']['company']['domain']."' 
				AND currency_0_iso3 = '".$_SESSION['template']['company']['currency1']."' 
				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 = '" . $tmp_account_details['accountid'] . "' 
				AND description = 'Incoming' 
				AND updated_datetime > '" . $datetime_rolling_schedule . "';";
	$tmp_fees = getTHECASHIER($tmp_sql);
	
	$tmp_balance['sponsor'] = $tmp_balance['balance']['sponsor'] = $tmp_balance['sponsor_balance'];
	
	//legacy:
	
	$tmp_balance['approved'] = $tmp_balance['balance']['approved'] = $tmp_approved - $tmp_fees;
	
	$tmp_balance['account'] = $tmp_balance['balance']['account'] = $tmp_balance['account_balance'];	
	
	$tmp_balance['balance']['available'] = $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 = '".$_SESSION['template']['company']['domain']."' 
				AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."' 
				AND accountid = '" . $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 simple_blingk_credit($accountid) {
	$tmp_sql = "SELECT blingk_credit FROM balances WHERE 
				platform = '".$_SESSION['template']['company']['domain']."' 
				AND currency_iso3 = '".$_SESSION['template']['company']['currency1']."' 
				AND accountid = '" . $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,$processing_message=null) {
	//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") {
		logger3("method == javascript == TRUE",NULL,NULL);
		if(isset($artificial_delay)) {
		
			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") {
		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,$currency_code_1,$accountid) {
	
	if($accountid) {
		$tmp_account = account($accountid);
	} else {
		$tmp_account = $_SESSION['account'];
	}
	
	if(!stristr($tmp_account['currency_transaction'],"OFF")) {
	
		if($currency_code_0) {
			$tmp_currency_code_0 = $currency_code_0;
		
		} else if(isset($_SESSION['account']['currency_0_iso3'])) {
			$tmp_currency_code_0 = $_SESSION['account']['currency_0_iso3'];
		
		} else {
			$tmp_currency_code_0 = $_SESSION['template']['company']['currency1'];
		}
		
		if(
		(isset($tmp_currency_code_0)) &&
		(isset($currency_code_1)) &&
		($tmp_currency_code_0 != $currency_code_1)
		) {
			return TRUE;
		}
	}
	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 = '" . $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 = '" . $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];

	}

	### 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];

	}
	

	### 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];

	}
	
	
	
	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];
	}
	
	
	
	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];
	}



	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];
	}
	
	
	
	### 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'];
	
	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' ORDER BY created ASC");

		
	### UN-SUSPEND ACCOUNTS:
	$i = 0;
	while($tmp_accounts[$i]) {
		
		updateTHECASHIER("DELETE FROM banned WHERE accountid = '$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 = '" . $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 = '" . $banned_member->bannedid . "';");
				$banned_info = readTHECASHIER("SELECT * FROM banned WHERE bannedid = '" . $banned_member->bannedid . "'");
				logger3("banned_info",$banned_info);
			}
			
		
		} else if($accountid) {
			$banned_info = readTHECASHIER("SELECT * FROM banned WHERE status != '' AND accountid = '$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>
			Per your request, this account has been suspended (and queued for deletion).<br>
			<font color=000099>You may Log-IN to your account below (functions 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 = '$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 = '$tmp_memberid'");
				 
				} else {
					$tmp_memberid = $banned_info->memberid;
					$tmp_acccounts = arrayTHECASHIER("SELECT accountid FROM accounts WHERE creator = '$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 = '$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'");
			
				$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'");
			
			$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 = '" . $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'");
			
		$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'");
			
				$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 = '$banned_info->bannedid'");
					
				updateTHECASHIER("UPDATE banned SET attempts = '$updated_attempts' WHERE bannedid = '$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 = '$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 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 = '" . $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 = '" . $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) {
	
	$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);
	$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 = '" . $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 = '{$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 = '" . $current_base_prints[voiceid2] . "'");
			$voiceid3_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid = '" . $current_base_prints[voiceid3] . "'");
			$voiceid4_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid = '" . $current_base_prints[voiceid4] . "'");
			$voiceid5_filename = getTHECASHIER("SELECT filename from voice_authorizations where voiceid = '" . $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) {

	//$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,$kurl_parameters);
	
	
	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);
	
	# 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);
		
	# 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;
	
}

function geobytes($ip) {
	//test("ip",$ip);
	
	//logger("+++++++++++++++++++function: geobytes: ip: " . $ip);
	
	logger3("start: geobytes()",$X);
	logger3("0. ip",$ip);
	//test("0. ip",$ip);
	
	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 = "202.58.240.108";
	}
	
	//test("1. ip",$ip);
	//test("ip",$ip);
	
	$geobytes_method = "local";  // curl or local
	logger3("geobytes_method",$geobytes_method);	

	$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);
	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 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) {
	
	//test("authorization_number function memberid",$memberid);
	$results = NULL;
	$results = array();
	$results = object2array(readTHECASHIER("SELECT * FROM phone_numbers WHERE memberid = '" . $memberid . "' AND description = 'Authorization' AND (status = 'Active' OR status = 'skip');"));
	$results['authorization_number'] = $results['phone_number'] = $results['number']; //fix
	$results['voiceprintid'] = getTHECASHIER("SELECT voiceprintid FROM voiceprints WHERE memberid = '" . $memberid . "' AND description = 'Registration';");
	
	return $results;
}


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($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(!$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_function.txt","voicefileids[2]: " . $voicefileids[2]);
		if($logging) logf("/tmp/biometric_registration_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_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 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 = '" . $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","
	
	### Fucntion biometric_registration() ########################################################
	
	
	
	");
	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 >= '50' 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 >= '50' 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 >= '50' 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 *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/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)) {
		
			$post_fields = "input-wave-uri=/root/audio/incoming_voice_authorizations/" . $filenames[$vf] . ".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 = '" . $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 transaction($transactionid) {

	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 = '" . $transactionid . "';";
		$variable = object2array(readTHECASHIER($tmp_sql));
	}

	logger3("variable['translogid']",$variable['translogid']);
	
	if(!empty($variable['translogid'])) {
		$tmp_sql = "SELECT * FROM translog WHERE translogid = '" . $variable['translogid'] . "';";
		logger3("tmp_sql",$tmp_sql);
		$variable['translog'] = object2array(readTHECASHIER($tmp_sql));
		logger3("variable['translog']",$variable['translog']);
	}
	
	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 = '" . $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 = '{$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 = '$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;
	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++;
	}
	
	
	## 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']['emailaddress'];
	} else {
		$tmp_business_account_emailaddress = "(your registered COMPANY_NAME Business Account Emailaddress)";
	}
	
	$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("QUESTION", "javascript:go_to_answer", $text_to_personalize);
	$text_to_personalize = str_replace("TOPIC", "javascript:list_the_questions", $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 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 = '" . $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 = '" . $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 = "v1";
	
	
	if($use == "v1") {
		$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
	}
	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 == "v2") {
		//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 == "v3") {
		//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( (!$output) || (!$field) || (!$output) ) return "error";

	### 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 _data WHERE name = '" . $data . "';";
		logger3("tmp_sql",$tmp_sql);
		$tmp_results = readTHECASHIER();
		logger3("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_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 = '" . $tmp_transaction['accountid'] . "' AND  requested_datetime = '" . $tmp_transaction['requested_datetime'] . "';";
	
	
	//logger3("tmp_sql",$tmp_sql);
		
	$variable = object2array(readTHECASHIER($tmp_sql));
	
	if(!$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 = '" . $tmp_method_details[1] . "' AND  requested_datetime = '" . $tmp_transaction['requested_datetime'] . "';";	
		//logger3("tmp_sql",$tmp_sql);
		$variable = object2array(readTHECASHIER($tmp_sql));
		
	}
	
	//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 = '" . $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 = '" . $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']);
	
	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 = '" . $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 = '" . $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() {
	
	//global $master_config_basic_limits_transaction;
	
	// if($_SESSION['account']['currency_0_iso3']) {
	// 	$var['currency_0_code'] = $_SESSION['account']['currency_0_iso3'];
	// } else {
	// 	$var['currency_0_code'] = $_SESSION['template']['company']['currency1'];
	// }
	// 
	// if( ($_SESSION['account']['currency_0_iso3']) && ($_SESSION['account']['currency_0_iso3'] != $_SESSION['template']['company']['currency1']) ) {
	// 	$var['currency_0_value'] = currency_format($get_fx($_SESSION['account']['currency_0_iso3'],$_SESSION['account']['currency_0_iso3'],$master_config_basic_limits_transaction));
	// } else {
	// 	$var['currency_0_value'] = currency_format($master_config_basic_limits_transaction);
	// }
	// 
	### RETURNS:
	//$_['currency_0_value']
	
	// return $var;
	
	if($_SESSION['template']['company']['cclimit_day'] == "0.00") {
		$var['currency_0_value'] = currency_format(1000000);
	} else {
		$var['currency_0_value'] = currency_format($_SESSION['template']['company']['cclimit_day']);
	}
	return $var['currency_0_value'];
}

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 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) {

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

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)
{
	require_once ("email_verify.shared");
	return validateEmail($email, true, true, 'shea.writer@nsdb.com', 'nsdb.com', true);
	
}

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 = '" . $accountid . "' AND DEVICE_ID = '".$DEVICE_ID."';";
	
	} else {
		$tmp_sql = "SELECT * FROM FIRSTDATA_TPSP_merchants WHERE accountid = '" . $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);
	//test("results",$results);
	
	
	if($results == TRUE) {
		return $new_extension_number;
	} else {
		return FALSE;
	}
}



function get_email_account_details($accountid=null) {

	if(!$accountid) return FALSE;
	
	$tmp_sql = "SELECT * FROM email_accounts WHERE accountid = '".$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) {

	logger3("000. set_deposit_translogid",$set_deposit_translogid);
	logger3("000. set_deposit_transactionid",$set_deposit_transactionid);
	logger3("000. set_reason_code",$set_reason_code);
	
	if(stristr($set_reason_code,"CHARGEBACK")) $set_reason_code = "11";
	if(stristr($set_reason_code,"REFUND")) $set_reason_code = "12";
	

	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
	include($_SESSION['template']['company']['file_path'] . "shared/process_chargeback.shared");
	if($process_chargeback == "COMPLETE") {
		return "COMPLETE";
		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() {
	global $master_config_platform_emulation;
	if(!empty($master_config_platform_emulation)) {
		return $master_config_platform_emulation; 
	} else {
		return $_SESSION['template']['company']['host_www']; 
	}
}


	
function get_active_system_email_account($accountid) {

	
	$tmp_sql = "SELECT * FROM email_accounts WHERE 
	    accountid = '" . $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\!/www/test/count_unread_LIVE.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);

	
	// 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);
	
	
	$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
	
	$tmp_account_name = trim($tmp_account_name);
	
	//$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_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
	


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

	return $clean_account_name;

}





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";
	
	$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 = "xe6";
	$exists = getTHECASHIER("SELECT email_account_id FROM email_accounts WHERE username = '".$tmp_username."' AND host = '".$tmp_host."';");
	if(!empty($exists)) $tmp_host = "97e";

	$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."'
	)";
	
	$add_results = add_postfix_email_account($personal_name=$tmp_account_details['accountname'],$username=$tmp_username,$host=$tmp_host,$password=$tmp_password);
	
	
}


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);
	##########################################################
	
}



?>